Reputation: 28284
I have this following method that connectss to db and returns a json array.
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
returnString += result.toString();
}
return returnString;
}
I then want to call this method from outside but being very new to java I am not sure how to get that sting in put it in hm object like the one thats commented out. See the code below
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView)findViewById(R.id.list);
myBooks = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hm;
hm = new HashMap<String, Object>();
List<String> list=new ArrayList<String>();
list.add(getServerData(KEY_121));
//With the help of HashMap add Key, Values of Book, like name,price and icon path
/* hm = new HashMap<String, Object>();
hm.put(BOOKKEY, "Android");
hm.put(PRICEKEY, "Price Rs: 500");
hm.put(IMGKEY, R.raw.android); //i have images in res/raw folder
myBooks.add(hm);
SimpleAdapter adapter = new SimpleAdapter(this, myBooks, R.layout.listbox,
new String[]{BOOKKEY,PRICEKEY,IMGKEY}, new int[]{R.id.text1, R.id.text2, R.id.img});
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
My object here is to get the returning string and add it to the myBooks object by using hm object just like how its done in the commented code.
Thanks
Upvotes: 0
Views: 678
Reputation: 28284
here is what I did and it works just fine
1- instead of returning the string, i returned the result as it is to the call.
2 then after that I built a string and then I was able to parse it just fine like this
returnedResult = this.getServerData(KEY_121);
try {
JSONArray jArray = new JSONArray(returnedResult);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
hm = new HashMap<String, Object>();
hm.put(IDKEY, json_data.getInt("id"));
hm.put(NAMEKEY, json_data.getString("name"));
hm.put(IMGKEY, R.raw.android);
myBooks.add(hm);
}
Hope that helps to someone here thanks
Upvotes: 0
Reputation: 57685
Since getServerData()
is going to take a while to execute (it contains an http request), you cannot run it directly from the UI thread. (onCreate()
is directly on the UI thread, and the UI thread should never be paused).
This means you have to create an AsyncTask
and call getServerData()
from the doInBackground()
of your AsyncTask
. You can return the display JSON result in the AsyncTask
's onPostExecute()
.
This means that you want to pass a SoftReference
of where you want to show your result to the AsyncTask
. You want to make it a SoftReference
in case something happens while you're fetching the JSON (like you navigate away from the Activity).
I would suggest that you read this Android blog article and create your own project with the code from the article. Once you have that up and running, modify the that image downloader to a JSON downloader. The article should be really helpful to you, since it also uses an Adapter to show items in a List View.
Your example is different from the one in the article in several ways, but I think it's actually simpler, so if you get your head wrapped around the code in the article, then you'll be able to get your code working afterward.
References:
AsyncTask
SoftReferences
Multithreading for Performance
Working Code from the Article Above which implements something like you want but w images
Upvotes: 1