【问题标题】:Error Parsing JSON Data - Asynchronous Task解析 JSON 数据时出错 - 异步任务
【发布时间】:2013-12-15 20:41:02
【问题描述】:

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

但是 - 我的错误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

【问题讨论】:

  • 旁注:mysql_* 函数已弃用,请改用mysqli_* 函数。
  • “错误解析数据”日志后打印的内容
  • 只写/签入doInBackground:Log.d("log_tag", result);
  • 可能是没有找到 TextView,你在第二个“catch”中捕获了所有 Exception
  • 你能把你的json贴在这里吗?调试起来真的很有帮助

标签: java php android json android-asynctask


【解决方案1】:

形成你的代码:

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

问题是它可能不是 Json 异常,而是 any 异常。实际上,不建议捕获类型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

附注

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

【讨论】:

  • 我删除了主要的Exception 并且应用程序崩溃了。我稍后会尝试您的handler 建议-谢谢:)
【解决方案2】:

我将您的 json 粘贴到 assets 文件夹中的本地文件中并尝试检索它。它工作正常。这是我的代码。我无法使用您的代码,因为该网址在我这边不起作用。无论如何,这是我的代码:-

    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;
    }

}

【讨论】:

  • 谢谢老兄,我今晚晚些时候试试这个,或者明天,当地时间周五下午 6 点在这里 :)
  • 我在JSONParser jParser = new JSONParser(); 得到一个错误我试图在stackoverflow.com/questions/13202304/… 找到这个类的一个例子我应该遵循那个吗?或者可能是这样的:androidhive.info/2012/05/how-to-connect-android-with-php-mysql。感谢您的帮助。
  • 老兄听着,这是一个从url解析json的类。无论您使用哪种方法,逐行调试您的代码并查看它是否有效。你应该调试你的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
相关资源
最近更新 更多