分析JSON数据时出错-异步任务


Error Parsing JSON Data - Asynchronous Task

在解析JSON数据时,我在主异常中发现了错误Error parsing Data

然而,我的错误No Data Found没有被JSONException捕获,这让我认为数据库正在被成功读取,

我的服务器上有一个php文件:

<?php
mysql_connect("database_ip","database_username","database_password");
mysql_select_db("database_name");
$sql=mysql_query("select * from table");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>

在线导航到php文件将显示预期的JSON数据:

[{"KEY_ROWID":"1","KEY_NAME":"Andrew","KEY_SCORE":"100","KEY_DATE":"0000-00-00 00:00:00"},{"KEY_ROWID":"2","KEY_NAME":"Peter","KEY_SCORE":"5000","KEY_DATE":"2013-11-29 10:58:21"}]

在Android中,我使用Async任务来读取数据:

class Task extends AsyncTask<String, String, Void> {
        InputStream is = null;
        String result = "";
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            String url_select = "http://mywebsite.com/myphpfile.php";
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);
            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                // read content
                is = httpEntity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "'n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            return null;
        }
        protected void onPostExecute(Void v) {
            try {
                JSONArray Jarray = new JSONArray(result);
                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject Jasonobject = Jarray.getJSONObject(i);
                    text = (TextView) findViewById(R.id.textView1);
                    // get an output on the screen
                    String name = Jasonobject.getString("KEY_NAME");
                    text.append(name + "'n");
                }
            }
            catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "NO Data Found",
                        Toast.LENGTH_LONG).show();
            }
            catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        }
    }

在我的活动onCreate中,我实例化异步类:

new Task().execute();

关于分析数据时出错的原因,有什么建议吗?

感谢

注意:使用println()输出变量"result"会将Json输出到logcat,如预期

形成您的代码:

...
catch (Exception e) {
            // TODO: handle exception
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

问题是它可能不是Json异常,而是任何异常。在实践中,不建议捕获类型Exception。我们应该只捕获Exception类的特定子类型。在我们的例子中,findViewById抛出:NullPointerException。所以,首先将其更改为NullPointerException(除了JSONException之外),然后再次运行程序。

我会把Error parsing data改成通用的。

假设我们在findViewById上没有异常,并且我们的text不是null

尝试使用Handler更新主线程(又名GUI):

private Handler mHandler = null;
 ...
 mHandler = new Handler();
 ... 
    mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    text = (TextView) findViewById(R.id.textView1);
                    JSONArray Jarray = new JSONArray(result);
                    for (int i = 0; i < Jarray.length(); i++) {
                        JSONObject Jasonobject = Jarray.getJSONObject(i);
                        // get an output on the screen
                        String name = Jasonobject.getString("KEY_NAME");
                        text.append(name + "'n");
                    }
                }
                catch (JSONException e1) {
                    Toast.makeText(getBaseContext(), "NO Data Found",
                            Toast.LENGTH_LONG).show();
                }
                catch (NullPointerException e) {
                    // TODO: handle exception
                    Log.e("log_tag", "Error  " + e.toString());
                }
            }
        }, 100); // dummy delay

附带说明

放在循环for 外部的行text = (TextView) findViewById(R.id.textView1);

Dud i将您的json粘贴到assets文件夹中的本地文件中,并尝试检索它。它运行良好。这是我的密码。我不能使用你的代码,因为url在我这边不起作用。无论如何,这是我的代码:-

    package com.example.test;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
    static InputStream is = null;
    static JSONObject jObj = null;
    String jsonString;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Making HTTP request
        // String url = "http://api.worldbank.org/countries/ir?format=json";
        String url = "http://10.0.2.2/andApp/artikel.php";
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        // JSONArray json = jParser.getJSONFromUrl(url);
        // JSONObject json = jParser.getJSONFromUrl1(url);
        // JSONObject json = null;
        JSONArray json = null;
        try {
            InputStream is = getAssets().open("json1.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            jsonString = new String(buffer, "UTF-8");
            // json = new JSONObject(jsonString);
            json = new JSONArray(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            JSONArray json2 = json;
            // .getJSONArray("artikel");
            for (int i = 0; i < json2.length(); i++) {
                JSONObject c = json2.getJSONObject(i);
                // Storing JSON item in a Variable
                String name = c.optString("KEY_ROWID", "");
                String capitalCity = c.optString("KEY_NAME", "");
                String score = c.optString("KEY_SCORE", "");
                String date = c.optString("KEY_DATE", "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}