如何使用从Mysql数据库中获取的数据填充android列表视图?

时间:2014-04-04 10:04:02

标签: android mysql

我正在创建一个应用程序,我必须从Mysql数据库中获取所选数据。 这是我到目前为止所做的。

MainActivity.java

package com.clientmanager;

import java.util.ArrayList;
 import java.util.List;

 import org.apache.http.HttpResponse;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.ResponseHandler;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.BasicResponseHandler;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.ProgressDialog;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.Toast;

public class MainActivity extends Activity
 {
    Button b;
     EditText et;
   HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button)findViewById(R.id.buttonlogin);
    et = (EditText)findViewById(R.id.userid);
   /* pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);*/

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(MainActivity.this, "",
                    "Validating user...", true);
            new Thread(new Runnable() {
                public void run() {
                    login();
                }
            }).start();
        }
    });
}

void login(){
    try{

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://192.168.0.114/cm/check.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
        nameValuePairs.add(new BasicNameValuePair("userid",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
       // nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response=httpclient.execute(httppost);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);
        runOnUiThread(new Runnable() {
            public void run()
            {
               // tv.setText("Response from PHP : " + response);
                dialog.dismiss();
            }
        });

        if(response.equalsIgnoreCase("User Found")){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
                }
            });

            startActivity(new Intent(MainActivity.this, Projects.class));
        }else{
            showAlert();
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
public void showAlert(){
    MainActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Login Error.");
            builder.setMessage("User not Found.")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    });
}
}

Projects.java

package com.clientmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

 import org.apache.http.NameValuePair;
 import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;

 import android.app.ListActivity;
 import android.app.ProgressDialog;
 import android.content.Intent;
 import android.os.AsyncTask;
 import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
      import android.widget.ListAdapter;
      import android.widget.ListView;
      import android.widget.SimpleAdapter;
      import android.widget.TextView;

public class Projects extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> projectsList;

// url to get all products list
private static String urlallproducts = "http://192.168.0.114/cm/getallprojects.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PROJECTS = "projects";
private static final String TAG_USERID = "userid";
private static final String TAG_CAR_REG_NO = "car reg no";
private static final String TAG_ADDRESS = " address";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    // Hashmap for ListView
    projectsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProjects().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id)
        {
            // getting values from selected ListItem
            String userid = ((TextView) view.findViewById(R.id.uid)).getText().toString();

            // Starting new intent
           Intent in = new Intent(getApplicationContext(),listitem.class);
            startActivity(in);
            // sending pid to next activity
           // in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
           // startActivityForResult(in, 100);
        }
    });

}

   /* // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
        }

     }
 */
    /**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProjects extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Projects.this);
        pDialog.setMessage("Loading projects. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(urlallproducts, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Projects: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PROJECTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_USERID);
                    String project = c.getString(TAG_PROJECTS);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_USERID, id);
                    map.put(TAG_PROJECTS, project);

                    // adding HashList to ArrayList
                    projectsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
               // Intent i = new Intent(getApplicationContext(),
                        //NewProductActivity.class);
                // Closing all previous activities
               // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               // startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(Projects.this, projectsList,R.layout.list_item, new String[] { TAG_USERID,
                        TAG_ADDRESS},new int[] { R.id.uid, R.id.add });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

getallprojects.php

<?php

/*
 * Following code will list all the products
 */

  // array for JSON response
   $response = array();


  // include db connect class
 require_once ('dbconnect.php');

 // connecting to db
 $db = new DB_CONNECT();

// get all products from products table
    $result = mysql_query("SELECT *FROM tbl_user ") or die(mysql_error());

  // check for empty result
   if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["projects"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $project = array();
    $project["userid"] = $row["userid"];
    $project["project"] = $row["project"];
    $project["car reg no"] = $row["car reg no"];
    $project["address"] = $row["address"];


    // push single project into final response array
    array_push($response["projects"], $project);
}
// success
    $response["success"] = 1;

// echoing JSON response
    echo json_encode($response);
 } else {
   // no products found
   $response["success"] = 0;
  $response["message"] = "No projects found";

    // echo no users JSON
    echo json_encode($response);
 }

&GT;

我的应用未显示列表视图中提取的数据。 日志中没有错误。

请指导。我们将不胜感激。

0 个答案:

没有答案