【问题标题】:Android List variable can't be set from internal class无法从内部类设置 Android List 变量
【发布时间】:2015-03-04 21:30:11
【问题描述】:

我正在尝试使用从 RESTApi 获得的 JSONObjects 填充我的 ListView。

我正在调用下面的方法来获取Json字符串“result”。

protected void onPostExecute(String result) {
    try {

        //Filling the JSONArray "list" with the given result
        item = new JSONArray(result);

        Toast.makeText(getBaseContext(), "Received!" + item.toString(), Toast.LENGTH_LONG).show();

        //LIST DOES EXIST WITH THE TOAST!

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

但是每当我尝试调用它时,我在检查 JSONArray 是否包含 JSONObjects 时,JSONArray 是空的。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //This is where I call the function from above
    new HttpAsyncTask().execute("http://rest-chaase.rhcloud.com/api/products");

    //Testing to see if the list exists
    Toast.makeText(getBaseContext(), "Received!" + item.toString(), Toast.LENGTH_LONG).show();

    //LIST DOESN'T EXIST (NullPointerException)
}

为什么 JSONArray“列表”会重置?

【问题讨论】:

  • 您正在访问的值尚不可用,因为 AsyncTask 仍在处理中。我想你想要的就在这个链接上stackoverflow.com/a/7423631/706833
  • 当然。这是有道理的

标签: android arrays


【解决方案1】:

我应该在发布这个问题之前完成我的研究。

修复很简单。

要填充数组,只需使用

item = new JSONArray(new HttpAsyncTask().execute("REST-LINK").get());

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多