获取错误的结果来自PHP服务器的Andr​​oid应用程序

问题描述:

大家好,我具有在使用JSON的PHP服务器获取结果的问题。基本上,第一个活动运行良好,并通过PHP的服务器正从数据库选择合适的结果。结果得到的第一个活动是年数。

Guys I am having issue in getting result from php server using JSON. Basically the first activity is running good and getting the appropriate results from Database through PHP Server. The result getting in the first activity are number of years.

不是用户选择年份,并希望根据选定的一年得到的结果。

than the user select the year and want to get the result based on selected year.

但是,当过一年选择它是从PHP文件中获取和数据库是错误的结果。这是获得previous结果今年第二活性以及替代月份,路径和字节数组图像。

But when ever the year is selected the result which is getting from the PHP file and database is wrong. It is getting the previous result year in the second activity as well instead of month, path and byte array for image.

显示年活动课:

public class DisplayYears extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> magazinesList;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MAGAZINE = "magazines";
private static final String TAG_PID = "ID";
private static final String TAG_YEAR = "year";
JSONArray magazines = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_years);
    magazinesList = new ArrayList<>();
    new LoadAllYears().execute();
    ListView lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            int pyears = Integer.parseInt(((TextView) view.findViewById(R.id.years)).getText()
                    .toString());
            Intent in = new Intent(getApplicationContext(),
                    DisplayMagazine.class);
            in.putExtra("year", pyears);
            startActivity(in);
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 100) {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}
class LoadAllYears extends AsyncTask<String, String, String> {
   @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(DisplayYears.this);
        pDialog.setMessage("Loading Years. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<>();
        //String url_all_magazines = "http://172.16.26.190/shifaspeaks/get_all_years.php";
        String url_all_magazines = "http://192.168.1.4/shifaspeaks/get_all_years.php";
        JSONObject json = jParser.makeHttpRequest(url_all_magazines, "GET", params);
        Log.d("All Magazines: ", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                magazines = json.getJSONArray(TAG_MAGAZINE);
                for (int i = 0; i < magazines.length(); i++) {
                    JSONObject c = magazines.getJSONObject(i);
                    String year = c.getString(TAG_YEAR);
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TAG_YEAR, year);
                    magazinesList.add(map);
                }
            } else {
                Intent i = new Intent(getApplicationContext(),
                        MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        DisplayYears.this, magazinesList,
                        R.layout.list_item, new String[] { TAG_PID,
                        TAG_YEAR},
                        new int[] { R.id.id, R.id.years});
                setListAdapter(adapter);
            }
        });
    }
}

显示年PHP文件:

Display Year PHP file:

<?php
mysql_connect('127.0.0.1:3306','root','');
mysql_select_db("shifaspeaks");
$response = array();
$result = mysql_query("SELECT DISTINCT year FROM magazine") 
die(mysql_error());
if (mysql_num_rows($result) > 0) {
 $response["magazines"] = array();
while ($row = mysql_fetch_array($result)) {
    // temp user array
    $magazine = array();
    //$magazine["id"] = $row["ID"];
    //$magazine["month"] = $row["month"];
    $magazine["year"] = $row["year"];
    //$magazine["path"] = $row["path"];
    array_push($response["magazines"], $magazine);
}
$response["success"] = 1;
echo json_encode($response);
}

 else {
$response["success"] = 0;
$response["message"] = "No magazines found";
echo json_encode($response);
}
?>

显示杂志活动课:

Display Magazine Activity Class:

public class DisplayMagazine extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> magazinesList;
int year;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MAGAZINE = "magazines";
private static final String TAG_MAGAZINE_IMAGE="magazineImage";
private static final String TAG_MONTH = "month";
private static final String TAG_PATH = "path";
JSONArray magazines = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_magazine);
    Intent i=getIntent();
    year=i.getIntExtra("year",0);
    magazinesList = new ArrayList<>();
    new LoadAllMagazines().execute();
    ListView lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 100) {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}
class LoadAllMagazines extends AsyncTask<String, String, String> {
   @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(DisplayMagazine.this);
        pDialog.setMessage("Loading Magazines. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("year", String.valueOf(year)));
        //String url_all_magazines = "http://172.16.26.190/shifaspeaks/get_all_magazines.php";
        String url_all_magazines = "http://192.168.1.4/shifaspeaks/get_all_magazines.php";
        JSONObject json = jParser.makeHttpRequest(url_all_magazines, "GET", params);
        Log.d("All Magazines: ", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                magazines = json.getJSONArray(TAG_MAGAZINE);
                    for (int i = 0; i < magazines.length(); i++) {
                    JSONObject c = magazines.getJSONObject(i);
                    String month = c.getString(TAG_MONTH);
                    String path = c.getString(TAG_PATH);
                    String imageString=c.getString(TAG_MAGAZINE_IMAGE);
                    byte[] image= Base64.decode(imageString.getBytes(), Base64.DEFAULT);
                    Bitmap decodedByte= BitmapFactory.decodeByteArray(image,0,image.length);
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TAG_MONTH, month);
                    map.put(TAG_PATH, path);
                    map.put(TAG_MAGAZINE_IMAGE,decodedByte.toString());
                    magazinesList.add(map);
                }
            } else {
                Intent i = new Intent(getApplicationContext(),
                        MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        DisplayMagazine.this, magazinesList,
                        R.layout.list_item2, new String[] {TAG_MAGAZINE_IMAGE, TAG_MONTH,
                        TAG_PATH},
                        new int[] {R.id.magazineImage, R.id.month, R.id.path});
                setListAdapter(adapter);
            }
        });
    }
}

显示杂志PHP文件:

Display Magazine PHP file :

<?php
mysql_connect('127.0.0.1:3306','root','');
mysql_select_db("shifaspeaks");
$response = array(); 
if(isset($_GET["year"])){
$year = $_GET["year"];
$result = mysql_query("SELECT month, path, magazineImage FROM magazine where year='$year'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
    $response["magazines"] = array();
    while ($row = mysql_fetch_array($result)) {
        $magazine = array();
        $magazine["month"] = $row["month"];
        $magazine["magazineImage"]=$row["magazineImage"];
        $magazine["path"] = $row["path"];
        array_push($response["magazines"], $magazine);
    }
    $response["success"] = 1;
    echo json_encode($response);
} else {
    $response["success"] = 0;
    $response["message"] = "No magazines found";
    echo json_encode($response);    
}
}
?>

请帮我出并预先感谢您。

Please Help me out and Thank You in advance.

您应该有ListView和阵列适配器类属性。我们必须从源(ArrayList的)到ListView显示数据的方式是通过一个适配器。

You should have the listview and array adapter as class attributes. The way we have to show data from a source (ArrayList) to a listview is through an Adapter.

在活动DisplayYears:

In activity DisplayYears:

public class DisplayYears extends ListActivity 
{
   ...
   private ArrayList<HashMap<String, String>> magazinesList;

   private ArrayAdapter arrayAdapter; // Here you have to define the Adapter (ArrayAdapter, CursorAdapter, or a custom Adapter, etc ...)

   private ListView lv;
   ...

在onCreate方法你必须告诉到ListView谁是适配器将提供数据。

In the onCreate method you have to tell to the listview who is the adapter that will provide the data.

protected void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.display_years);

   // Init ArrayList
   magazinesList = new ArrayList<>();

   //Set Array Adapter with Array List
   arrayAdapter = new ArrayAdapter(this, magazinesList);

   // Get a reference to the ListView, and attach this adapter to it.
   lv = (ListView) findViewById(R.id.listviewXmlLayout);

   lv.setAdapter(arrayAdapter);

   // Here lv.setOnItemClickListener implementation

   // Start Request to Server 
   new LoadAllYears().execute();
}

关键部分是在这里从LoadAllMagazines类onPostExecute。在onPostExecute的AsynTask线程与UI线程进行通信。

The key part here is the onPostExecute from LoadAllMagazines class. In onPostExecute the AsynTask thread communicates with the UI thread.

您应该从doInBackground方法返回一个JSON是这样的:

You should return a Json from doInBackground method like this:

JSONObject doInBackground(String... args)

我们需要从onPostExecute服务器接收到的数据来更新该ArrayList(magazinesList)。 (不要再内存分配给magazinesList因为适配器(arrayAdapter)具有记忆参考magazinesList和一个新的内存分配将打破这种关系)。

We need to update the ArrayList (magazinesList) with the data received from the server on onPostExecute. (Do not assign again memory to magazinesList because the adapter (arrayAdapter) has a memory reference to magazinesList and a new memory allocation will break this relationship).

class LoadAllMagazines extends AsyncTask<String, String, JSONObject> 
{
   ...

   JSONObject doInBackground(String... args)
   {
      // Return Json received from server.
   }

   protected void onPostExecute(JSONObject file_url) 
   {
      pDialog.dismiss();

      // Parse the Json file

      // Clear the ArrayList
      magazinesList.clear();

      // Load magazinesList with data received from server

      // And the magic happens here! You only have to notify the adapter about the new changes in the ArrayList       
      arrayAdapter.notifyDataSetChanged();

      // It is using observer pattern. Any changes in the ArrayList, we notify the Adapter and then it will tell the listView about the new changes.
   };
}

请检查它是否适合你!