In the strings.xml file

there is an array of resources

<string-array name="cat_names"> <item>текст</item> <item>текст2</item> <item>текст3</item> <item>текст4</item> <item>текст5</item> ...... </string-array> 

you can get a resource with

 String[] catnames = getResources().getStringArray(R.array.cat_names); 

But there are several arrays and there is a lot of text in each array. When displaying this all in the list, the application slows down a bit, like a trifle, but not pleasant.

Is it possible in Android Studio to insert this entire resource in AsyncTask?

The code that I gave below is very ugly)) but I think the idea is clear. It seems everything is logical, but the error does not work

 public class MainActivity extends AppCompatActivity { ListView listView; String[] catnames5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listView); // если раскомментировать, то работает, но нужно этот код как нибудь засунуть в AsyncTask //catnames5 = getResources().getStringArray(R.array.cat_names); // выводим MyTask mt = new MyTask(); mt.execute(); catnames5 = mt.catnames4; // используем адаптер данных ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, catnames5); listView.setAdapter(adapter); } // class MyTask extends AsyncTask<Void, Void, Void> { String title; String[] catnames2; String[] catnames4; @Override protected Void doInBackground(Void... params) { String[] catnames = null; try { catnames = getResources().getStringArray(R.array.cat_names); } catch (Resources.NotFoundException e) { e.printStackTrace(); } if (catnames!=null) catnames2 = catnames; else title = "Ошибка"; return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); catnames4 = catnames2; } } 

}

error log

 08-23 19:36:34.932 2353-2353/net.artsait.asunk E/AndroidRuntime: FATAL EXCEPTION: main Process: net.artsait.asunk, PID: 2353 java.lang.RuntimeException: Unable to start activity ComponentInfo{net.artsait.asunk/net.artsait.asunk.MainActivity}: java.lang.NullPointerException: storage == null at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: storage == null at java.util.Arrays$ArrayList.<init>(Arrays.java:38) at java.util.Arrays.asList(Arrays.java:155) at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137) at net.artsait.asunk.MainActivity.onCreate(MainActivity.java:32) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) 

Crashes here

 at net.artsait.asunk.MainActivity.onCreate(MainActivity.java:32) 

Well, or when using the adapter

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, catnames5); 

Although the adapter works if you simply insert a string into onCreate

 String[] catnames = getResources().getStringArray(R.array.cat_names); 

But how to insert this line into AsyncTask

  • Without an error message does not help you. And it is necessary to transfer the value to onPosteks and assign it there - YuriySPb
  • And on which line falls? - Yuriy SPb
  • Flies here at net.artsait.asunk.MainActivity.onCreate (MainActivity.java:32) Well or when using the adapter ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, catnames5); Although the adapter works if you simply insert the string String [] into onCreate catnames = getResources (). GetStringArray (R.array.cat_names); But how to insert this line into AsyncTask - Artsait
  • You wrote the line number, but there is no numbering of lines of code. So you didn’t say which line crashes - YuriySPb
  • I wrote, ArrayAdapter <String> crashes adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, catnames5); - Artsait

2 answers 2

AsyncTask is an asynchronous task, having started which cannot be said for sure when it will end. In your case, when you display a list based on data that is loaded from AsyncTask , the list can be initialized even when Async not finished its work. In order to display the list only when you already have the necessary data, you can make a Callback with AsyncTask . Below I will provide the code with which you can get the result from the task and with this data create a ListView . Perhaps this is not the best option in the sense that the list is displayed only when AsyncTask , it would be better to do it like this: display an empty list -> load the data in the task -> refresh the ListView with new data, but this is a completely different story.

 public class MainActivity extends AppCompatActivity { ListView listView; String[] catnames5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listView); // если раскомментировать, то работает, но нужно этот код как нибудь засунуть в AsyncTask //catnames5 = getResources().getStringArray(R.array.cat_names); // выводим MyTask mt = new MyTask(new MyCallback() { @Override public void onComplete(String[] array) { // используем адаптер данных ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array); listView.setAdapter(adapter); } @Override public void onFailed() { //тут можно обработать вариант если ошибка } }); mt.execute(); } public interface MyCallback { void onComplete(String[] array); void onFailed(); } class MyTask extends AsyncTask<Void, Void, Void> { String title; String[] catnames2; String[] catnames4; MyCallback callback; public MyTask(MyCallback callback) { this.callback = callback; } @Override protected Void doInBackground(Void... params) { String[] catnames = null; try { catnames = getResources().getStringArray(R.array.cat_names); } catch (Resources.NotFoundException e) { e.printStackTrace(); } if (callback != null) { if (catnames != null) { catnames2 = catnames; callback.onComplete(catnames); } else { title = "Ошибка"; callback.onFailed(); } } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); catnames4 = catnames2; } } } 
  • Red underlines this, android.R.layout.simple_list_item_1, array); - Artsait
  • replace with getApplicationContext () - Kirill Stoianov

Initially, the variable catnames4 null . It is initialized only after MyTask executed in the MyTask method. That is, MyTask does not have time to MyTask before creating the adapter. The adapter in the variable 'catnames5' is the value null. Create and assign an adapter in the 'onPostExecute' method, though the brakes will remain. In general, there is no point in MyTask , as long as there is no data and there is nothing to display in the list. If you need the application to start faster, and the list is loaded later. Then try to place the code in onStart or onResume

 @Override public void onStart() { String[] catnames = null; try { catnames = getResources().getStringArray(R.array.cat_names); } catch (Resources.NotFoundException e) { e.printStackTrace(); } // используем адаптер данных ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, catnames); listView.setAdapter(adapter); }