Android+PHP+MYSQL把数据库中的数据显示在Android界面上

俗话说,好记性不如烂笔头。今天终于体会其中的道理了。昨天写好的代码不知道为何找不到了。所以今天我一定得抽出一点时间把我的代码保存起来,以防我的代码再没有了。

还是先上图片。

这个界面是用ListView实现的,数据是数据库里面的数据,服务器为thinkPHP。我就不废话那么多,直接把我的代码拷贝上了、

总的思想就是,利用账号查询数据库中的信息,然后对返回的信息进行解析。这里我把账号保存到了本地。

Data.java

package cn.edu.aynu.rjxy.entity;

public class Data {
    private int id;
    private String exp_name;
    private String exp_tech;
    private String exp_type;
    private String exp_source;
    private String exp_tno;
    private String istate;
    private String sno;
    private String sname;
    private String passwd;
    private String grade;
    private String school;
    private String qq;
    private String clas;
    private String cellphone;
    private String email;
    private String spec;
    public String getSpec() {
        return spec;
    }
    public void setSpec(String spec) {
        this.spec = spec;
    }
    public String getSno() {
        return sno;
    }
    public void setSno(String sno) {
        this.sno = sno;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public String getQq() {
        return qq;
    }
    public void setQq(String qq) {
        this.qq = qq;
    }
    public String getClas() {
        return clas;
    }
    public void setClas(String clas) {
        this.clas = clas;
    }
    public String getCellphone() {
        return cellphone;
    }
    public void setCellphone(String cellphone) {
        this.cellphone = cellphone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    public String getExp_type() {
        return exp_type;
    }
    public void setExp_type(String exp_type) {
        this.exp_type = exp_type;
    }
    public String getExp_source() {
        return exp_source;
    }
    public void setExp_source(String exp_source) {
        this.exp_source = exp_source;
    }
    public String getExp_tno() {
        return exp_tno;
    }
    public void setExp_tno(String exp_tno) {
        this.exp_tno = exp_tno;
    }
    public String getIstate() {
        return istate;
    }
    public void setIstate(String istate) {
        this.istate = istate;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getExp_name() {
        return exp_name;
    }
    public void setExp_name(String exp_name) {
        this.exp_name = exp_name;
    }
    public String getExp_tech() {
        return exp_tech;
    }
    public void setExp_tech(String exp_tech) {
        this.exp_tech = exp_tech;
    }
    @Override
    public String toString() {
        return "Data [id=" + id + ", exp_name=" + exp_name + ", exp_tech="
                + exp_tech + "]";
    }

}
SharedPreferencesUtils.java
package cn.edu.aynu.rjxy.utils;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SharedPreferencesUtils {
    //保存账号和密码到minemessage.xml
    public static boolean saveUserInfo(Context context,String cellphone,String qq,String email){
        SharedPreferences sp = context.getSharedPreferences("minemessage", Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("cellphone", cellphone);
        edit.putString("qq", qq);
        edit.putString("email", email);
        edit.commit();
        return true;
    }
    //保存账号和密码到data.xml
    public static boolean saveUserInfo02(Context context,String sno,String password,String spinnerId){
        SharedPreferences sp = context.getSharedPreferences("data", Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("sno", sno);
        edit.putString("password", password);
        edit.putString("spinnerId", spinnerId);
        edit.commit();
        return true;
    }
    //保存账号和密码到select.xml
        public static boolean saveUserInfo03(Context context,String sno,String id){
            SharedPreferences sp = context.getSharedPreferences("select", Context.MODE_PRIVATE);
            Editor edit = sp.edit();
            edit.putString("sno", sno);
            edit.putString("id", id);
            edit.commit();
            return true;
        }

    //从data.xml文件中获取存贮的账号和密码
    public static Map<String,String> getUserInfo(Context context){
        SharedPreferences sp = context.getSharedPreferences("data", Context.MODE_PRIVATE);
        String sno = sp.getString("sno", null);
        String password = sp.getString("password", null);
        String spinnerId = sp.getString("spinnerId", null);
        Map<String,String> userMap = new HashMap<String, String>();
        userMap.put("sno", sno);
        userMap.put("password", password);
        userMap.put("spinnerId", spinnerId);
        return userMap;
    }
    //从minemessage.xml文件中获取存贮的账号和密码
    public static Map<String,String> getUserInfo02(Context context){
        SharedPreferences sp = context.getSharedPreferences("minemessage", Context.MODE_PRIVATE);
        String cellphone = sp.getString("cellphone", null);
        String qq = sp.getString("qq", null);
        String email = sp.getString("email", null);
        Map<String,String> userMap = new HashMap<String, String>();
        userMap.put("cellphone", cellphone);
        userMap.put("qq", qq);
        userMap.put("email", email);
        return userMap;
        }
    //从select.xml文件中获取存贮的账号和密码
        public static Map<String,String> getUserInfo03(Context context){
            SharedPreferences sp = context.getSharedPreferences("select", Context.MODE_PRIVATE);
            String sno = sp.getString("sno", null);
            String id = sp.getString("id", null);
            Map<String,String> userMap = new HashMap<String, String>();
            userMap.put("sno", sno);
            return userMap;
            }
}
StreamTools.java
package cn.edu.aynu.rjxy.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTools {

    public static String readStream(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer))!=-1) {
                baos.write(buffer,0,len);
            }
            baos.close();
            return new String(baos.toByteArray());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }
}

MineActivity.java
package cn.edu.aynu.rjxy.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.aynu.rjxy.entity.Data;
import cn.edu.aynu.rjxy.utils.SharedPreferencesUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MineActivity extends Activity {
    private static final int CHANGE_UI = 1;
    private static final int ERROR = 2;
    private ListView lv;
    private List<Data> datas = new ArrayList<Data>();
    //主线程创建消息处理器
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGE_UI) {
                try {
                    JSONArray arr = new JSONArray((String)msg.obj);
                      for (int i = 0; i < arr.length(); i++) {
                          JSONObject temp = (JSONObject) arr.get(i);
                         // Log.d("json", temp.getInt("id")+temp.getString("exp_name")+temp.getString("exp_tech"));
                          Data data = new Data();
                          data.setId(temp.getInt("id"));
                          data.setExp_name(temp.getString("exp_name"));
                          data.setExp_tech(temp.getString("exp_tech"));
                          data.setExp_source(temp.getString("exp_source"));
                          data.setExp_type(temp.getString("exp_type"));
                          data.setExp_tno(temp.getString("tname"));
                          data.setIstate(temp.getString("istate"));
                         //这个地方可以获取到值但是适配器那位0
                          datas.add(data);

                      }
                      lv.setAdapter(new MyAdapter());
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
    };
    protected String sno;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        lv = (ListView) findViewById(R.id.lv);
        select();
        //取出账号和密码
        Map<String,String> userInfo = SharedPreferencesUtils.getUserInfo(this);

        if (userInfo != null) {
              sno = userInfo.get("sno");
        }

    }

    private void select(){
        //子线程更新UI
         new Thread(){
                public void run(){
                     try {
                        StringBuilder builder = new StringBuilder();
                        String path = "http://10.6.78.254:2016/xampp/graduate/index.php/home/Student/test_check";
                         URL url = new  URL(path);
                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                         //区别2、请求方式post
                         conn.setRequestMethod("POST");
                         conn.setRequestProperty("User-Agent", "Mozilla/5.0(compatible;MSIE 9.0;Windows NT 6.1;Trident/5.0)");
                         //区别3、必须指定两个请求的参数
                         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//请求的类型  表单数据
                         //System.out.println(sno);
                         String data = "sno="+sno;
                         conn.setRequestProperty("Content-Length", data.length()+"");//数据的长度
                         //区别4、记得设置把数据写给服务器
                         conn.setDoOutput(true);//设置向服务器写数据
                         byte[] bytes = data.getBytes();
                         conn.getOutputStream().write(bytes);//把数据以流的方式写给服务器
                         int code = conn.getResponseCode();
                         if (code == 200) {
                              InputStream is = conn.getInputStream();
                             BufferedReader reader = new BufferedReader
                                  (new InputStreamReader(is,"UTF-8"));
                             for(String s=reader.readLine();s!=null;s=reader.readLine())
                          {
                              builder.append(s);
                          }
                          String content = builder.toString();
                        //通知主线程更新UI
                          Message message = new Message();
                          message.what = CHANGE_UI;
                          message.obj = content;
                          handler.sendMessage(message);
                    }else{
                        Log.e(HomeActivity.class.toString(), "Failed");
                    }
                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }

                };
            }.start();
    }
     class MyAdapter extends BaseAdapter{

            @Override
            public int getCount() {
                Log.d("AAA", ""+datas.size());
                return datas.size();

            }

            @Override
            public Object getItem(int position) {

                return datas.get(position);
            }

            @Override
            public long getItemId(int position) {

                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(MineActivity.this, R.layout.ui_setting_select, null);

                TextView exp_name = (TextView) view.findViewById(R.id.tv_name);
                TextView exp_tech = (TextView) view.findViewById(R.id.tv_tech);
                TextView exp_type = (TextView) view.findViewById(R.id.tv_type);
                TextView exp_source = (TextView) view.findViewById(R.id.tv_source);
                TextView exp_tno = (TextView) view.findViewById(R.id.tv_tno);

                Data data = datas.get(position);
                Log.d("aaaaa",datas.get(position).getExp_name() );

                exp_name.setText(datas.get(position).getExp_name());
                //Log.i("exp_name", datas.get(position).getExp_name());
                exp_tech.setText(datas.get(position).getExp_tech());
                exp_type.setText(datas.get(position).getExp_type());
                exp_source.setText(datas.get(position).getExp_source());
                exp_tno.setText(datas.get(position).getExp_tno());

                return view;
            }

     }
}
activity_mine.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:padding="5dp"
    android:orientation="vertical" >
  <ListView
         android:id="@+id/lv"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginLeft="5dp">
     </ListView>  

</RelativeLayout>

item_mine.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp"
    android:background="#FFFFFF"
    android:orientation="vertical">
     <View
    android:layout_width="fill_parent"
    android:layout_height="2dip"
    android:layout_marginTop="5dip"/>

    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
        style="@style/LTexTviewStyle"
        android:text="毕业设计名称" />

    <TextView
        android:id="@+id/tv_name"
        style="@style/TextViewStyle"
        android:text="25" />
    </RelativeLayout>
     <View
    android:layout_width="fill_parent"
    android:layout_height="0.2dip"
    android:layout_marginTop="5dip"
    android:background="#bb000000"/>
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
        style="@style/LTexTviewStyle"
        android:text="题目类型" />

    <TextView
        android:id="@+id/tv_type"
        style="@style/TextViewStyle"
        android:text="25" />
    </RelativeLayout>
     <View
    android:layout_width="fill_parent"
    android:layout_height="0.2dip"
    android:layout_marginTop="5dip"
    android:background="#bb000000"/>
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
        style="@style/LTexTviewStyle"
        android:text="题目来源" />

    <TextView
        android:id="@+id/tv_source"
        style="@style/TextViewStyle"
        android:text="25" />
    </RelativeLayout>
     <View
    android:layout_width="fill_parent"
    android:layout_height="0.2dip"
    android:layout_marginTop="5dip"
    android:background="#bb000000"/>
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
        style="@style/LTexTviewStyle"
        android:text="指导老师" />

    <TextView
        android:id="@+id/tv_tno"
        style="@style/TextViewStyle"
        android:text="25" />
    </RelativeLayout>
     <View
    android:layout_width="fill_parent"
    android:layout_height="0.2dip"
    android:layout_marginTop="5dip"
    android:background="#bb000000"/>
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
        style="@style/LTexTviewStyle"
        android:text="技术要求" />

    <TextView
        android:id="@+id/tv_tech"
        style="@style/TextViewStyle"
        android:text="25" />
    </RelativeLayout>
     <View 

    android:layout_width="fill_parent"
    android:layout_height="0.2dip"
    android:layout_marginTop="5dip"
    android:background="#bb000000"/>
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
   <Button
       android:id="@+id/btn_reselect"
       android:onClick="reselect"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="退选"
       android:layout_alignParentRight="true"
       android:textColor="#000000"
       android:background="#FFFFFF"/>

    </RelativeLayout>
</LinearLayout>

PHP端的代码:

//Android端查看我的选题
    public function test_check(){
     $sno = I(‘sno‘);
     $Experiment = M("Experiment");
     //$sno = ‘130906008‘;
    $exp_tno = $Experiment -> where("sno = ‘".$sno."‘") -> getField(‘exp_tno‘);
    //echo $exp_tno;
    $RowCount = $Experiment -> where("sno = ‘".$sno."‘") -> Count();
    if($RowCount == 1){
     $myModel = new \Think\Model();
        $result=$myModel->query("select *from g_experiment,g_teacher where sno = $sno && tno = $exp_tno ;");
        $this ->ajaxReturn($result);
    }else{
    echo ‘你还没有选题‘;
    }
    }
时间: 2024-12-16 13:50:28

Android+PHP+MYSQL把数据库中的数据显示在Android界面上的相关文章

MySQL删除数据库中所有表方法

MySQL删除数据库中所有表方法技术 maybe yes 发表于2015-01-23 12:16 原文链接 : http://blog.lmlphp.com/archives/66  来自 : LMLPHP后院 通过使用 CONCAT 函数将数据库表名称和需要执行的 SQL 语句连接起来,输出在控制台:然后从控制台复制这些内容,粘贴,执行,OK.table_schema 条件为需要操作的数据库名称,参考 SQL 语句如下: SELECT CONCAT('DROP TABLE IF EXISTS 

MySQL 删除数据库中重复数据(以部分数据为准)

delete from zqzrdp where tel  in (select min(dpxx_id) from  zqzrdp  group by tel  having count(tel)>1); 执行,报错 异常意为:你不能指定目标表的更新在FROM子句.傻了,MySQL 这样写,不行,让人郁闷. 难倒只能分步操作,蛋疼 以下是网友写的,同样是坑爹的代码,我机器上运行不了. 1. 查询需要删除的记录,会保留一条记录.  代码如下 复制代码 select a.id,a.subject,

mysql导入数据库中的存储过程和函数出现错误的解决办法

mysql导入数据库中的存储过程和函数出现错误的解决办法 调用一个远程拷贝的本地Mysql的储存过程 报错:[Err] 1449 - The user specified as a definer ('repl'@'192.168.1.%') does not exist  解决想法: 凭借以前经常见到的[email protected]报错,给root赋值所有权限: grant all privileges on *.* to [email protected]"%" identif

mysql查看数据库中所有表的行数,并进行排序

mysql查看数据库中所有表的行数,并进行排序: 进行数据库迁移或还原后,可以通过比较行数,检查数据是否正确. mysql> use information_schema; mysql> select table_name,table_rows from tables where TABLE_SCHEMA= 'kpsumi' order by table_rows desc; 原文地址:http://blog.51cto.com/9285090/2119096

Android 通过API获取数据库中的图片文件

Overview 今天复习了一下Android 如何将我们数据库中图片获取出来,并且将其转换为bitmap进行显示. 开发环境以及技术 使用Visual Studio 2019 Android Studio 3.5 API 使用 ASP .NET WEB API 开发 数据库操作只用Entity Framework 使用本地数据库作为数据源 如果你是一个需要开发软件和API的程序员,那么你可以看一下,如果你不是可以选择跳过 $\color{#6995C2}{API开发}$. API 开发 这里我

优化MD5在(MySQL)数据库中的存储

1.MD5在MySQL数据库中的存储 用CHAR(32)来存储MD5值是一个常见的技巧.如果你的应用程序使用VARCHAR(32),则对每个值得字符串长度都需要花费额外的不 必要的开销.这个十六进制的值可以使用UNHEX()和HEX()函数来存储在BINARY(16)在BINARY(16)数据类型的中且更为高效.用这 种转换可以让每行占用的存储空间从32字节减少到16字节. 下面的示例展示了原始MD5以及压缩后的MD5占用的空间对比: 这个原则也适用其他16进制的值,例如为所有列的散列值而定义的

nodejs+mysql 处理数据库中的时间戳返回到前台格式不对

mysql 日期的字段都是timeStamp 格式为YYYY-MM-DD  hh:mm:ss 如下图 可是直接通过select语句取到的时间在后台打印出的是下图的格式 将取到日期不做任何处理返回给前台又变成了下面的格式 所以写了一个简单的函数,对从数据库中取到的时间进行一下处理在返回给前台.函数只是简单的做了日期拼接,并在小于10的数前补0 function makeDate(date) { try { var newDate = new Date(date); //在小于10的月份前补0 va

MYSQL 查看数据库中所有用户及拥有权限

查看MYSQL数据库中所有用户 mysql> SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;+---------------------------------------+| query                                 |+---------------------------------------+| User: 'cactiuser'@

Mysql获取数据库中存在的字典信息

有时候自己写工具需要从远程数据库中获得各种表信息,这样首先就要取得数据字典 列一下mysql的获取方式 use information_schema; select schema_name from schemata; select table_name from tables where table_schema='information_schema' order by table_name; 1.首先use一下information_schema 2.从schemata表中获取出可用的sc