-1

在此处输入图像描述我在这方面遇到了很多麻烦。我有一个解析过的 json 数组,效果很好。我有另一个网页供我尝试解析的单个用户使用。这是php。它的有效json。

{
    "userURL": "http://forum.example.com.php?u=426561",
    "userId": "426561",
    "forumName": "example name",
    "totalPosts": "19787",
    "postsPerDay": "8.11",
    "totalThanks": "40585",
    "joinDate": "2007-02-20",
    "yearsJoined": "6",
    "referrals": "17",
    "friendCount": "61",
    "recognizedDeveloper": "1",
    "recognizedContributor": "0",
    "recognizedThemer": "0",
    "moderator": "0",
    "recognizedEliteDeveloper": "0",
    "romCount": "100",
    "kernelCount": "1",
    "tutorialCount": "0",
    "modCount": "21",
    "themeCount": "0",
    "originalAppCount": "0",
    "toolkitCount": "0",
    "scriptCount": "0",
    "sOffCount": "0",
    "recoveryCount": "0",
    "score": "687",
    "rank": "1 out of 122"
}

这是我的解析器类。

public class JSONParser1 {

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

// constructor
public JSONParser1() {

}

public JSONObject getJSONFromUrl(String url) {

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

        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"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } 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 class GetScore extends Activity {


private static String url = "http://example.com"


private static String TAG_NAME = "forumName";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.getscore);

    JSONParser1 jParser1 = new JSONParser1();
    JSONObject json = jParser1.getJSONFromUrl(url);

    try {
        json = new JSONObject(TAG_NAME);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  //get nickname
   try {
    json.getString("forumName");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  ///.... get other value for object
}   
}

我如何将它与资源 ID 联系起来?任何帮助将不胜感激。

public class GetScore extends Activity {

private static String url = "http://example.com"
private static String TAG_NAME = "forumName";
private JSONParser1 jParser1 ;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getscore);

    jParser1 = new JSONParser1();
    new GetJSONTask().execute(url);


}


    class GetJSONTask extends AsyncTask<String, Void, JSONObject> {

       private Exception exception;





protected JSONObject doInBackground(String... urls) {
    try {
        JSONParser1 jParser = new JSONParser1();
        return jParser.getJSONFromUrl(urls[0]);
    } catch (Exception e) {
        return null;
    }
}




protected void onPostExecute(JSONObject json) {
    // do all the parsing here:

    //get nickname
    try {
        // You then reset the same variable here
        // the previous object is now lost, or if it throws an exception,
        // the previously set value remains (whether null or not)
        json = new JSONObject(TAG_NAME);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // This object could easily be null, or could be valid if the previous
    // call failed
    try {
        json.getString("forumName");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }}}}
4

3 回答 3

1

问题正在发生,因为您试图在 UI 线程上执行网络操作。您需要使用后台线程进行网络操作。

使用AsyncTask如下:

public class GetScore extends Activity {

    private static String url = "http://example.com"
    private static String TAG_NAME = "forumName";
    private JSONParser1 jParser1 ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.getscore);

        jParser1 = new JSONParser1();
        new GetJSONTask().execute(url);

        // do not parse here..
        ...
        ...
    }
    ...
    ...

 class GetJSONTask extends AsyncTask<String, Void, JSONObject> {

    private Exception exception;

    protected JSONObject doInBackground(String... urls) {
        try {
            JSONParser1 jParser = new JSONParser1();
            return jParser.getJSONFromUrl(urls[0]);
        } catch (Exception e) {
            return null;
        }
    }

    protected void onPostExecute(JSONObject json) {
        // do all the parsing here:

        try {
            String forumName = json.getString("forumName");
            Log.i("POST FORUM NAME:", forumName);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } 
 }
}

参考:http: //developer.android.com/reference/android/os/AsyncTask.html

在方法中添加了一个简单的日志选项,onPostExecute()它按预期显示了论坛的名称。

在此处输入图像描述

于 2013-10-28T03:25:13.277 回答
0

所以我以这种方式将它添加到我的布局中。谢谢阿穆利亚的帮助

class GetJSONTask extends AsyncTask<String, Void, JSONObject> {



    protected JSONObject doInBackground(String... urls) {
        setContentView(R.layout.getscore2);


        try {
        JSONParser1 jParser = new JSONParser1();
        return jParser.getJSONFromUrl(urls[0]);
    } catch (Exception e) {
        return null;
    }
}

protected void onPostExecute(JSONObject json) {
    // do all the parsing here:

    try {
        String forumName = json.getString("forumName");
        final TextView id1 = (TextView)findViewById(R.id.forumUser);
        id1.setText(forumName);


        Log.i("POST FORUM NAME:", forumName);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
于 2013-10-28T07:35:50.380 回答
0

可能不是答案,但这似乎是可疑的:

JSONParser1 jParser1 = new JSONParser1();
JSONObject json = jParser1.getJSONFromUrl(url); 
// you get a JSON object from the URL
// you never actually use the value you get from the web page    

try {
    // You then reset the same variable here
    // the previous object is now lost, or if it throws an exception,
    // the previously set value remains (whether null or not)
    json = new JSONObject(TAG_NAME); 
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// This object could easily be null, or could be valid if the previous
// call failed
try {
    json.getString("forumName");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我不知道出了什么问题,但看起来你有一个 NullPointerException,或者至少它是没有额外知识的罪魁祸首。您可能应该花一些时间来学习处理异常的正确方法。您当前仅打印堆栈跟踪的方法正确。

您需要查看您的代码,并确保您知道它可能采用的所有可能路径,包括异常。请记住,当我们有异常浮动时,代码路径不再是线性的。

我找不到一篇关于处理异常的好文章,我个人是从 Joshua Bloch 的Effective Java中学习到的,我强烈推荐阅读它来改进你的代码。

于 2013-10-28T03:34:17.007 回答