JSON继续获取旧数据

时间:2014-05-30 01:48:59

标签: android json

我的JSON解析器不断获取我之前访问过的成员数据,即使我本来应该获得另一个数据EX:作业数据。这是我的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文件。它肯定是键入的:从作业而不是成员中选择*但即使我重新启动我的模拟器并且没有首先进入成员页面,我仍然可以获得以前访问过的成员数据

2 个答案:

答案 0 :(得分:0)

您有jObj作为类级别变量,您应该将其作为方法级别变量(在getJsonFromUrl()方法中声明)并为其指定默认值或null

我猜你正在捕获一个JSONException或其他连接之一Exceptions并且之前的值没有设置为新输入然后你将返回旧版本或者更糟糕的是,来自另一个方法的版本&# 39;最后一次运行。

在这种情况下,即使在获取或解析JSON时发生错误,也会返回jObj。这意味着如果发生错误,则jObj仍将设置为其最后一个值,而是返回该值。

对于其他类级别变量(InputStream is和String json)也是如此。我实际上建议您删除所有类级变量并使所有类&#39;方法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的更改可能仍应该应用。

答案 1 :(得分:0)

这是因为在调用Web服务调用时,您只使用单个JSONParser实例。

尝试为每个调用创建一个新实例,以便它们具有不同的响应。

你可以这样做。

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

&#39; JSON&#39;现在具有你想要的回应价值。

希望它有所帮助。干杯!