I'm new to Android. I was wondering if anyone had any suggestions. It's basically an AsyncTask
to get a remote JSON array and put it into a native array.
Would be very grateful for suggestions.
package com.example.test2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private String strCategoryJsonUrl = "http://www.mydomain.com/categories.json";
getCategories myCategories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCategories = new getCategories();
myCategories.execute();
}//onCreate
private class getCategories extends AsyncTask<Integer, Integer, String>{
@Override
protected String doInBackground(Integer... intMyGuessLevel) {
String strJson = "";
try {
URL url = new URL(strCategoryJsonUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
strJson = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return strJson;
} //doInBackground
private String readStream(InputStream in) {
BufferedReader reader = null;
String strContent = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
strContent = strContent + line;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} //finally
return strContent;
} //readStream
protected void onPostExecute(String strResult) {
int i = 0;
String strValue = "";
TextView txtDebug = (TextView) findViewById(R.id.txtdebug);
String arrCategories[] = new String[1];
//parse JSON data
try{
JSONArray jArray = new JSONArray(strResult);
//JSONObject menu = jObject.getJSONObject("menu");
arrCategories = new String[jArray.length()];
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = new JSONObject(jArray.get(i).toString());
strValue = jObject.getString("name");
//put value into array
arrCategories[i] = strValue;
}
//debug output the array
txtDebug.setText(Arrays.toString(arrCategories));
} catch (JSONException e) {
e.printStackTrace();
txtDebug.append("Error in categories json file \n");
txtDebug.append(String.valueOf(e));
} // catch
} //onPostExecute
} //getJsonContent
}