Androidhive教程修改可能

时间:2014-09-13 21:08:20

标签: php android json listview

Hello和goood day for all,任何建议如何修改androidhive显示listview中的所有产品以显示listview中的所有搜索产品。我有一个搜索学生matricID的PHP代码,显示JSON列表中的所有学生科目。

    <?php

$hostname_localhost ="mysql.serverfree.com";
$database_localhost ="u658807642_andr";
$username_localhost ="u658807642_majd";
$password_localhost ="amirah";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);
// array for JSON response
$response = array();
$matricID= $_REQUEST['matricID'];
// get all products from products table
//$result = mysql_query("SELECT *FROM tbl_semester") or die(mysql_error());
$order = "SELECT tbl_semester.pid, tbl_semester.matricID, tbl_semester.code, tbl_semester.course, tbl_semester.point, tbl_semester.crdhour, tbl_semester.grdpoint, tbl_semester.reattempt, tbl_semester.grd";
$order .= " FROM tbl_semester WHERE tbl_semester.matricID =  '$matricID'"; 
$result = mysql_query($order);
if (mysql_num_rows($result) > 0) {
$response["tbl_semester"] = array();
while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["pid"] = $row["pid"];
    $product["matricID"] = $row["matricID"];
    $product["code"] = $row["code"];
    $product["course"] = $row["course"];
    $product["point"] = $row["point"];
    $product["crdhour"] = $row["crdhour"];
    $product["grdpoint"] = $row["grdpoint"];
    $product["reattempt"] = $row["reattempt"];
    $product["grd"] = $row["grd"];


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

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

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

可以在这里测试结果:

http://miramajdi.bugs3.com/android/getrecord.php?matricID=226629A131 http://miramajdi.bugs3.com/android/getrecord.php?matricID=226629A132

我成功运行了androidhive教程,但它显示了listview中数据库的所有数据,并附有PID和产品名称。

但是在我的php代码中,app需要将设置matricID发送到php,找到并将JSON列表发送回app并显示到listview中。

    package i.uumportal;

import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SEMESTERcgpa extends ActionBarActivity {

ListView listView1;
Button button1;
Spinner spinner1;
TextView textView1;
TextView textView4;
TextView textView5;

String tUser;
String tPass;
String matricID;

//----------------------------------------------------------------------
private String array_spinner[];
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> semesterList;
// url to get all products list
private static String url_all_products = "http://miramajdi.bugs3.com/android/getrecord.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SEMESTER = "tbl_semester";
private static final String TAG_PID = "pid";
private static final String TAG_COURSE = "course";
// products JSONArray
JSONArray tbl_semester = null;

//-------------------------------------------------------------------------

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_semestercgpa);

       //Declare 
       button1 = (Button) findViewById(R.id.button1);
       final TextView textView1=(EditText) findViewById(R.id.editText1);
       final TextView textView4 = (TextView) findViewById(R.id.textView4);
       final TextView textView5 = (TextView) findViewById(R.id.textView5);
       Bundle b = getIntent().getExtras();

       textView4.setText(b.getCharSequence("tuser"));
       textView5.setText(b.getCharSequence("tpass"));

       matricID=textView1.getText().toString();

        //Home button function
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), Calculator.class);
                //Create a bundle object
                Bundle b = new Bundle();
                //Inserts a String value into the mapping of this Bundle
                b.putString("tuser", textView4.getText().toString());
                b.putString("tpass", textView5.getText().toString());
                //Add the bundle to the intent.
                intent.putExtras(b);
                //start the DisplayActivity
                startActivity(intent);
                finish();

            }});

        semesterList = new ArrayList<HashMap<String, String>>();
        new LoadAllProducts().execute();

        }


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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SEMESTERcgpa.this);
            pDialog.setMessage("Loading products. 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>();
            params.add(new BasicNameValuePair("matricID", matricID));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

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

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

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

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String course = c.getString(TAG_COURSE);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_COURSE, course);

                        // adding HashList to ArrayList
                        semesterList.add(map);
                    }
                } else {
                    Toast.makeText(SEMESTERcgpa.this,"No record found", Toast.LENGTH_SHORT).show();
                    // 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
            listView1 = (ListView) findViewById(R.id.listView1);
            pDialog.dismiss();
            //Updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */

                ListAdapter adapter = new SimpleAdapter(SEMESTERcgpa.this, semesterList,R.layout.cgpalist_main, new String[] { TAG_PID,TAG_COURSE},new int[] { R.id.pid, R.id.course });
                listView1.setAdapter(adapter);// setListAdapter(adapter);
            }
        });

        }

    }}

可以看到,我使用了从发送matricID之前的intent到此活动然后显示到texview4,然后将String matricID设置为text4。

matricID将与JSON get进行比较。我没有得到错误,但在模拟器中失败。需要建议或示例代码可以匹配并使用上面的PHP。

0 个答案:

没有答案