簡體   English   中英

JSON保持獲取舊數據

[英]JSON keep Getting the old data

我的JSON解析器不斷獲取我較早訪問的成員數據,即使我本該獲取另一個數據EX:Job數據也是如此。 這是我的JSONParser.java代碼:

package travenz.tacos;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
       try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        url += "?";
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        json = EntityUtils.toString(httpResponse.getEntity());
        Log.d("JSON", json);

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

       // try parse the string to a JSON object
       try {
           jObj = new JSONObject(json);
       } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data " + e.toString());
       }

       // return JSON String
       return jObj;

}
public JSONObject setJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();         

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 20);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.d("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
public JSONObject getJSONFromUrlWithParams(String url, List<NameValuePair> params) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?"+paramString;
        HttpGet httpGet = new HttpGet(url);
        Log.d("url", url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 20);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.d("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;    

    }
}

這是我獲取工作數據的代碼:

private static final String JOB_URL = "http://192.168.1.6/DatabaseCon/selectalltugas.php";
class LoadJobList extends AsyncTask<String, String, String> {

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

    /**
     * getting Job JSON
     * */
    protected String doInBackground(String... args) {

        // getting JSON string from URL
        JSONObject json = jsonParser.getJSONFromUrl(JOB_URL);

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

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

            if (success == 1) {
                job = json.getJSONArray(TAG_JOBS);
                // looping through All messages
                for (int i = 0; i < job.length(); i++) {
                    JSONObject c = job.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String date = c.getString(TAG_DATE);
                    String time = c.getString(TAG_TIME);
                    String place = c.getString(TAG_PLACE);
                    String detail = c.getString(TAG_DETAIL);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DATE, date);
                    map.put(TAG_TIME, time);
                    map.put(TAG_PLACE, place);
                    map.put(TAG_DETAIL, detail);

                    // adding HashList to ArrayList
                    JobList.add(map);
                }
            } else {
                // no products found
                nodata = true;
            }

        } 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(
                            JobSchedule.this, JobList,
                            R.layout.job_list_item, new String[] { TAG_ID, TAG_NAME, TAG_DATE, TAG_TIME, TAG_PLACE },
                            new int[] {R.id.jid, R.id.name, R.id.date, R.id.time, R.id.place });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.job_schedule, menu);
        return true;
        }

}

從我上面發布的URL,應該是正確的php,我已經檢查了php文件。 它的絕對類型為:從作業中選擇*代替成員,但是即使我重新啟動模擬器並且沒有首先進入成員頁面,我仍會獲取以前訪問的成員數據

您將jObj作為類級別的變量,您可能應該將其作為方法級別的變量(在getJsonFromUrl()方法中聲明),並為其指定默認值或null

我猜想您正在捕獲JSONException或其他連接異常之一,並且它的先前值未設置為新輸入,然后您返回的是舊版本,或更糟的是,該版本是另一個方法的上次運行版本。

在這種情況下,即使在獲取或解析JSON時發生錯誤,您jObj返回jObj 這意味着,如果發生錯誤,則jObj仍將被設置為其最后一個值,並將其返回。

其他類級別的變量(InputStream is和String json)也是如此。 我實際上建議您刪除所有類級別的變量,並使所有類的方法為static 這樣,您可以確保不會返回任何過時的數據。

這是您的課程更改:

public class JSONParser
{
    public static JSONObject getJSONFromUrl(String url)
    {
        String json = null;
        JSONObject jObj = null;

        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            url += "?";
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            json = EntityUtils.toString(httpResponse.getEntity());
            Log.d("JSON", json);
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (NullPointerException e)
        {
            Log.e("JSON Parser", "json String was null");
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }

    public static JSONObject setJSONFromUrl(String url, List<NameValuePair> params)
    {
        InputStream is = null;
        String json = null;
        JSONObject jObj = null;
        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 20);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            json = sb.toString();
            Log.d("JSON", json);
        }
        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        finally 
        {
            // you should always close any open handles in a finally clause
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {}
            }
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        catch (NullPointerException e)
        {
            Log.e("JSON Parser", "json String was null");
        }
        // return JSON String
        return jObj;
    }

    public static JSONObject getJSONFromUrlWithParams(String url, List<NameValuePair> params)
    {
        InputStream is = null;
        String json = null;
        JSONObject jObj = null;

        // Making HTTP request
        try
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            Log.d("url", url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

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

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 20);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            json = sb.toString();
            Log.d("JSON", json);
        }
        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        finally
        {
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        // try parse the string to a JSON object
        try
        {
            jObj = new JSONObject(json);
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

請注意,這只是隨着OP提供更多代碼而發展緩慢的可能實現。 JayR的答案可能是更好的解決方案。 使JSONParser具有靜態方法的選擇是一個可選的設計決策。 但是,可能仍應應用對安全關閉InputStream所做的更改。

這是因為在調用Web服務調用時,僅使用JSONParser的單個實例。

嘗試為每個調用創建一個新實例,以使它們具有不同的響應。

你可以這樣做。

JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(JOB_URL);

“ json”現在具有您想要的響應值。

希望能幫助到你。 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM