I'm trying to create a window which will display a listbox populated with an array parsed from JSON.
The listview is populated and created in the OnCreate
method in my MainActivity
. In the main activity I'm also calling an AsyncTask
to parse the JSON array from a website.
The task is shown below:
public class JSONParse extends AsyncTask<String, String, String[]> {
@Override
protected String[] doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream IStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(IStream));
StringBuffer buffer = new StringBuffer();
String recievedLine = "";
while ((recievedLine = reader.readLine()) != null) {
buffer.append(recievedLine);
}
String full = buffer.toString();
JSONObject JSONParent = new JSONObject(full);
JSONArray j_Puzzles = JSONParent.getJSONArray("PuzzleIndex");
int arraySize = j_Puzzles.length();
String[] s_Puzzles = new String[arraySize];
StringBuffer endString = new StringBuffer();
for (int i = 0; i < j_Puzzles.length(); i++) {
s_Puzzles[i] = j_Puzzles.toString(i);
endString.append(s_Puzzles[i] + "\n");
}
MainActivity.Waiting = true;
return s_Puzzles;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
What is the best way to get s_Puzzles
out of the background thread and into my OnCreate
so it can be used like this:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONParse().execute("http://www.hull.ac.uk/php/349628/08309/acw/index.json");
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, s_Puzzles);
listView.setAdapter(arrayAdapter);
}
}
Furthermore, am I going to have to pause the OnCreate
method until the background worker is done in order to prevent the listview updating with nothing due to the worker thread not finishing.
Any help appreciated. Thanks