JSON不断收到旧数据 [英] JSON keep Getting the old data

查看:114
本文介绍了JSON不断收到旧数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON解析器不断收到我访问早些时候甚至当我应该得到另一个数据EX我的成员数据:就业数据。这里是我的JSONParser.java code:

My JSON parser keep getting my member data which I accessed earlier even when I was supposed to get another data EX:Job data. Here is my JSONParser.java Code:

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;    

    }
}

这是我的code获取作业数据:

and this is my code to get job data:

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文件。这肯定类型:SELECT * FROM工作,而不是成员,但我还是让我的previously访问即使我重新启动我的模拟器,并没有先进入会员页面数据成员

from the URL I posted above, It should be the correct php and I already checked the php file to. It definitely typed: select * from jobs instead of members but I'm still getting my previously accessed member data even if I restarted my emulator and didn't enter the member page first

推荐答案

您有 jObj 作为类级别的变量,你应该把它作为一种方法级别的变量(声明它的 getJsonFromUrl()方法内),并为它指定一个默认值或

You have jObj as a class level variable, you should probably have it as a method level variable (declare it inside the getJsonFromUrl() method) and assign it a default value or null.

我猜你是受凉JSONException或其他连接例外之一,它是没有得到设置为新的输入,然后您返回旧版本或者更糟的是,从一个版本的previous价值另一种方法的最后运行。

I would guess that you are catching a JSONException or one of the other connection Exceptions and the previous value for it is not getting set to the new input and then you are returning the old version or worse, a version from another method's last run.

在此情况下,即使发生错误或者提取或解析您返回 jObj 无论JSON。这意味着,如果发生了错误,那么 jObj 仍然会设置其最后的值和得到,而不是返回。

In this case, even though errors occur either fetching or parsing the JSON you return the jObj regardless. This means that if an error has occurred then jObj will still be set to its last value and that gets returned instead.

同样也适用于其他类级别变量(InputStream为字符串和JSON)真。其实,我建议你删除所有类级别变量,使所有的类的方法静态。这样,你可以肯定的是以往任何时候都不会返回过期数据。

The same also holds true for the other class level variables (InputStream is and String json). I would actually suggest that you remove all class level variables and make all the class' methods static. That way you can be sure no stale data is ever returned.

下面是类改变:

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提供了更多code可能实现。通过JayR答案是可能是更好的修复。选择使JSONParser有静态方法是一个可选的设计决策。但是,更改关闭InputStream的安全可能仍然应该适用的。

Note that this is just a possible implementation that developed slowly as the OP supplied more code. The answer by JayR is an probably the better fix. The choice to make the JSONParser have static methods is an optional design decision. However, the changes made to closing the InputStream safely probably should still be applied.

这篇关于JSON不断收到旧数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆