简体   繁体   English

AsyncTask错误Android App崩溃

[英]AsyncTask error Android App crashes

My oncreate code: 我的创建代码:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.board);
    ArrayList<String> passing = new ArrayList<String>();
  new AsyncTaskParseJson().execute();


}

Here is my code: 这是我的代码:

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";
    String yourJsonStringUrl = "my url here";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @SuppressWarnings("null")
    @Override
     public String doInBackground(String... arg0) {

        final String[] values = null;
         try {

             // instantiate our json parser
             JsonParser jParser = new JsonParser();

             // get json string from url
             JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

             // get the array of users
             dataJsonArr = json.getJSONArray("response");

             // loop through all users
             for (int i = 1; i < dataJsonArr.length(); i++) {

                 JSONObject c = dataJsonArr.getJSONObject(i);
                 String text = c.getString("text");
                values[i]=text;
             }
          //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
          //   list1.setAdapter(adapter);


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


         return null;
     }

     @Override
     protected void onPostExecute(String strFromDoInBg) {}



 }

So, it's starts activity when I comment the section values[i] like this: 所以,当我像这样评论部分值[i]时,它会启动活动:

      //values[i]=text;

BUT when it's not commented, app just crashes. 但是当它没有被评论时,app就崩溃了。 I want to doInBackground to return String[] array, how I do that? 我想doInBackground返回String []数组,我是怎么做到的?

you have re declare it again before the for loop 你在for循环之前再次声明它

values = new String[dataJsonArr.length()];
for (int i = 1; i < dataJsonArr.length(); i++) {

             JSONObject c = dataJsonArr.getJSONObject(i);
             String text = c.getString("text");
            values[i]=text;
         }

you need to reserve its size in the memory by declaring new 你需要通过声明new来保留其在内存中的大小

You need to have 你需要拥有

 values = new String[dataJsonArr.length()]; 

Also note the commented lines are in doInbackground . 另请注意,注释行位于doInbackground But you can't update ui from a background thread. 但是你无法从后台线程更新ui。 So the below should go to onPostExecute . 所以下面应该转到onPostExecute

 //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
 //   list1.setAdapter(adapter);

Instead of using a String array it is better to use a ArrayList<String> 不使用String数组,最好使用ArrayList<String>

You need to change the args type also 您还需要更改args类型

public class AsyncTaskParseJson extends AsyncTask<String, String, ArrayList<String>> {

Then 然后

 @Override
 public  ArrayList<String> doInBackground(String... arg0) {

    ArrayList<String> values = new ArrayList<String>();
     try {

         // instantiate our json parser
         JsonParser jParser = new JsonParser();

         // get json string from url
         JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

         // get the array of users
         dataJsonArr = json.getJSONArray("response");

         // loop through all users
         for (int i = 1; i < dataJsonArr.length(); i++) {

             JSONObject c = dataJsonArr.getJSONObject(i);
             String text = c.getString("text");
             values.add(text); 
         }
     }  
     catch (JSONException e) {
         e.printStackTrace();
     }

     return values;
 }

Then 然后

 @Override
 protected void onPostExecute(ArrayList<String> result) {
  super.onPostExecute(result);
   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, result);
   list1.setAdapter(adapter);
 }

Also make sure list1 is initialized before you setAdapter to it coz i do not see the code where list1 is initialized. 还要确保在setAdapter之前初始化list1 ,因为我没有看到list1初始化的代码。

Just declare String[] array at class level like below, 只需在类级别声明String []数组,如下所示,

private static String[] array = null;


public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";
    String yourJsonStringUrl = "my url here";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @SuppressWarnings("null")
    @Override
     public String doInBackground(String... arg0) {

        //  final String[] values = null;          
         try {

             // instantiate our json parser
             JsonParser jParser = new JsonParser();

             // get json string from url
             JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

             // get the array of users
             dataJsonArr = json.getJSONArray("response");

             // loop through all users
             for (int i = 1; i < dataJsonArr.length(); i++) {

                 JSONObject c = dataJsonArr.getJSONObject(i);
                 String text = c.getString("text");
                values[i]=text;
             }
          //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
          //   list1.setAdapter(adapter);


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


         return null;
     }

     @Override
     protected void onPostExecute(String strFromDoInBg) {}
}

Here, you are creating an Array object with to major problem... 在这里,您正在创建一个带有主要问题的Array对象...

  1. creating Array object without defining it's size. 创建Array对象而不定义它的大小。
  2. defining as final which will not allow you to add new element to that object. 定义为final ,不允许您向该对象添加新元素。

You declaring an Array which is null and you defining it as final . 您声明一个为nullArray ,并将其定义为final When you declare an Array as final then you can't change that Array . Array声明为final则无法更改该Array That's why you can't insert new value to that Array , as a result, when you are going to access that Array its returning null value. 这就是为什么你不能向该Array插入新值,因此,当你要访问该Array它返回的null值。 It's the cause to crash your app. 这是导致应用程序崩溃的原因。

So, what you have to do is, define the values array with a fixed size and don't make it final . 因此,您需要做的是,使用固定大小定义values数组,而不是将其设置为final These will solve your all problem. 这些将解决您的所有问题。

Now, replace the following line... 现在,替换以下行...

final String[] values = null;

with these... 用这些...

String[] values;
values = new String[dataJsonArr.length()];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM