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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ‘你还没有选题‘;
    }
    }

 

以上是关于Android+PHP+MYSQL把数据库中的数据显示在Android界面上的主要内容,如果未能解决你的问题,请参考以下文章

在 Android Studio 中将 MySQL 中的数据显示到 TextView 中

Android(PHP + MySQL)中的这段代码有啥问题?

将 POST 数据从 Android 应用程序发送到 PHP MySQL

Android应用程序解码来自PHP MySql数据库的JSON响应,没有特殊字符

使用 GCM、PHP 和 MySQL 的 Android 推送通知

通过android使用php更新mysql数据库