Populate list view - android

I am developing a final year project and I am stuck at a point. I have to retrieve names of doctors from my database (MySQL database) and show it in a list view. I was able to establish a connection with the server and retrieve values, but when I tried to show the values in a list view, the application crashed!
I tried the same example given in [Hello, Views, List View][4].
It works for a predefined array like
private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
but for a string array retrieved from the database it shows a run time exception. Is there any way I can achieve this?
package com.proj;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.*;
import android.app.ListActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class proj extends ListActivity {
/** Called when the activity is first created. */
public int n=0;
public int t=0;
public int i=0;
public String name[]=new String[30];
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
TextView txt=(TextView)findViewById(R.id.tv);;
//Call the method to run the data retrieval
getServerData(KEY_121);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, name));
}
public static final String KEY_121 = "http://10.0.2.2/doc.php"; //I use my real IP address here.
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());
}
//Parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
n=jArray.length();
name[i]=json_data.getString("name");
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
e.printStackTrace();
}
return returnString;
}
}

You are using
1.)
android:id="#+id/list"
inside the ListView, but if your extend an activity by ListActivity you have to use
android:id = "#android:id/list"
2.)
You return a String[] here, not String
private String[] getServerData(String returnString) {
.......
JSONArray jArray = new JSONArray(result);
name = new String[jArray.length()];
for(i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
name[i]=json_data.getString("name");
}
return name;
}
And in ArrayAdapter, do it like this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getServerData(KEY_121));
setListAdapter(adapter);

public String name[];
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
TextView txt=(TextView)findViewById(R.id.tv);;
...
...
try {
JSONArray jArray = new JSONArray(result);
name[]=new String[jArray.length()];
for(i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
n=jArray.length();
name[i]=json_data.getString("name");
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
e.printStackTrace();
}
It seems that initializing name[] with a size of 30 may be too small.

Related

Trying to fetch mysql data in android listview

Hello everyone I am trying to fetch data from mysql database in android ListView,
Following code is throwing java.lang.StringIndexOutOfBoundsException
I am new to Android Development, If anybody could guide me through this it will be much help.
Thank You.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
public class Main_catagory_one extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<Product> records;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
context=this;
records=new ArrayList<Product>();
listProduct=(ListView)findViewById(R.id.listView1);
adapter=new CustomAdapter(context, R.layout.list_view,R.id.textView3,
records);
listProduct.setAdapter(adapter);
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void>{
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/fetch_item/getproducts.php");
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),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("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
// Remove unexpected characters that might be added to beginning of the string
result=result.substring(result.indexOf("["));
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data =jArray.getJSONObject(i);
Product p=new Product();
p.setpName(json_data.getString("Item_name"));
p.setuPrice(json_data.getString("Item_price"));
p.setpQauntity(json_data.getString("Item_quantity"));
p.setpImage(json_data.getString("Item_img"));
records.add(p);
}
}
catch(Exception e){
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result){
if(pd!=null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
IndexOutOfBoundsException - if beginIndex is negative or larger than
the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing length of the string before and after doing substring.
For example...
String testing = "Hello World";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);

JSON Parser Error : http client failure [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Im learning the JSON Parser. I follow the androidhive tutorial and copy its code, but sadly, i cannot. It does not display anything and has these type of errors:
11-22 17:27:12.132: E/AndroidRuntime(1938): Caused by: android.os.NetworkOnMainThreadException
Can anyone help me with this problem? Thanks.
JSONPaser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
MainActivity
import android.view.Menu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity{
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<uses-permission android:name="android.permission.INTERNET" /> is use in Manifest
How can i use AsyncTask or Thread with Handler to solve the error ?? do i need to delete my JSON Parser class ??
things i tried so far:
i switched i target SDK version to fit my emulator but it still
doesn't work
i run the project on my phone (Samsung) and emulator (Genymotion)
it show the same error
i tried to test another method without JSON Array
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
try{ //try1 start
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is our TextView element, obtained by id from our XML layout
TextView myListView = (TextView)findViewById(R.id.netResult);
//lets try to connect
try{ //try2 start
//create a new client object
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ephemeraltech.com/demo/android_tutorial20.php");
//execute the post and get the response object
HttpResponse response = httpclient.execute(httppost);
//get the message from the response
HttpEntity entity = response.getEntity();
//get the content of the message
InputStream webs = entity.getContent();
//convert response to string
try{ //try3 start
BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"utf-8"),8);
//read one line of the response
myListView.setText(reader.readLine());
//slow our inputStream
webs.close();
}//try3 end
catch (Exception e){//catch 3 start
Log.e("log_result", "Error converting result "+e.toString());
}//catch 3 end
} //try2 end
catch (Exception e){//catch 2 start
Log.e("log_connect", "Error in http connection "+e.toString());
}
}//try1 end
catch (Exception e){ //catch 1 start
//this is the lie of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE: "+e.toString());
e.printStackTrace();
}//catch 1 end
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
in this code the LogCat catch my second try and print log_connect, Error in http connection
You have a NetworkOnMainThreadException error.
That means you have directly run your code on onCreate method:
But you can't update your data directly on MainUI thread.
For that you have to use AsyncTask or Thread with Handler or update your UI with runOnUiThread()
You can go with this:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
Did you read the stack trace at all?
Caused by: android.os.NetworkOnMainThreadException
If you had even googled with "NetworkOnMainThreadException" you would have got the answer.
In short, the reason is you are performing an HTTP request on the main thread which is a bad practise actually. Android recently has become more restrictive and throws an exception.
What you need is something like this:
new AsyncTask<CustomParamClass, Void, String>() {
#Override
protected String doInBackground(final CustomerParamClass... params) {
//use params to get the data and make an HHTP Request.
}
#Override
protected void onPostExecute(final String params) {
// This is invoked on the main thread. Communicate here.
}
}.execute(<pass some params here>);

JSON parsing error - not parse in google API 4.1 jelly bean

i am working on an app using json parsing...in this parsing is done by json of the given url.
As i run my project on emulator having target = "Google APIs (Google Inc.) - API level 10"
then it runs properly and shows needed results from the target url.
but when run my project on emulator having target = "Google APIs (Google Inc.) - API level 16"
then it shows error and it never parse the given url data and get force close.
i want to make app which run on every API level.
please help...
here's my code:
json parser class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
static String req = "POST";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, String method) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
if(method == req) {
HttpPost httpC = new HttpPost(url);
httpResponse = httpClient.execute(httpC);
}else {
HttpGet httpC = new HttpGet(url);
httpResponse = httpClient.execute(httpC);
}
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Another class using json parser class snd fetch data:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class showData extends ListActivity{
public static String url = "http://something/something/";
public static final String TAG_A = "a";
public static final String TAG_B = "b";
public static final String TAG_C = "c";
public static final String TAG_D = "d";
public static final String TAG_E = "e";
public static final String TAG_F = "f";
public static final String GET = "get";
JSONArray Data1 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
EditText editext_text = (EditText) findViewById(R.id.et);
String urlnew = url + editext_text.getText().toString();
Log.d("url", urlnew);
JSONParser jParser = new JSONParser();
// getting JSON string from URL
area1 = jParser.getJSONFromUrl(urlnew, GET);
Log.d("Json String", area1.toString());
try {
for(int i = 0; i < area1.length(); i++){
JSONObject c = area1.getJSONObject(i);
// Storing each json item in variable
String a = c.getString(TAG_A);
String b = c.getString(TAG_B);
String c = c.getString(TAG_C);
String d = c.getString(TAG_D);
String e = c.getString(TAG_E);
HashMap<String,String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_A, a);
map.put(TAG_B, b);
map.put(TAG_C, c);
map.put(TAG_D, d);
map.put(TAG_E, e);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item_area,
new String[] { TAG_B, TAG_A, TAG_C, TAG_D, TAG_E }, new int[] {
R.id.b, R.id.a, R.id.c, R.id.d, R.id.e });
setListAdapter(adapter);
}
}
You are getting a NetworkOnMainThreadException because as the name is self-explaining, you are doing network request on UI Thread that will make your application laggy and create an horrible experience.
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged. See the document Designing for Responsiveness.
You should use Threads or AsyncTask, do you need some explanations on how to use them?
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//DO YOUR STUFF
}
#Override
protected void onPostExecute(String result) {
//Update UI
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
This is Network On Main Thread Exception, You have to use Thread for network connection, because the main thread is UI thread will not give any response for Network connection. Use separate thread for network connection

passing json data to a custom object - android

I'm having trouble with my application. I'm trying to pass json data from my database in a custom class in android, and then display this in a list. When i run my app nothing happens, no errors, no list displayed. if anyone can help i would be very grateful!! :)
All the network stuff is done in async, and im trying to return the an array of objects so i suspect that this could be the problem is here or else when i am converting the string from the httphandler class into a JSONArray.
this is my main activity
package com.example.test1;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class clubpage extends Activity {
class Programme {
public String name;
public String event;
public String price;
}
String clubphp = "http://10.0.2.2/corkgaa/Nemo.php";
String progString;
ArrayList<Programme> Programmedata = new ArrayList<Programme>();
ListView clublistview = (ListView)findViewById(R.id.listview1);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.clubpage);
new Dbhandler().execute(clubphp);
ArrayAdapter<Programme> adapter = new ArrayAdapter<Programme>(this,
android.R.layout.simple_list_item_1, Programmedata);
clublistview.setAdapter(adapter);
}
public class Dbhandler extends AsyncTask<String, Void, ArrayList<Programme>> {
protected ArrayList<Programme> doInBackground(String... arg0) {
ArrayList<Programme> arraydata = new ArrayList<Programme>();
progString = httphandler.HttpGetExec(clubphp);
try{
JSONArray jArray = new JSONArray(progString);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Programme Progresult = new Programme();
Progresult.name = json_data.getString("Name");
Progresult.event = json_data.getString("Event");
Progresult.price = json_data.getString("Price");
arraydata.add(Progresult);
}
}
catch(JSONException e1){
}
catch (ParseException e1) {
e1.printStackTrace();
}
return arraydata;
}
#Override
protected void onPostExecute(ArrayList<Programme> result) {
Programmedata = result;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
httphandler class here:
package com.example.test1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class httphandler {
//Main Dev setup
public static String HttpGetExec (String URI) {
// TODO Auto-generated method stub
String result = "no response";
InputStream is = null;
StringBuilder sb = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/corkgaa/Nemo.php");
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
return result;
//aa=new ArrayAdapter<String>(clubpage.this, R.layout.listrow, R.id.title, result);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listrow, R.id.title, result);
//listview.setAdapter(aa);
}
}
Move this line to your onCreate after setContentView
clublistview = (ListView)findViewById(R.id.listview1);
And move the following lines to onPostExecute in your async task:
ArrayAdapter<Programme> adapter = new ArrayAdapter<Programme>(this,
android.R.layout.simple_list_item_1, Programmedata);
clublistview.setAdapter(adapter);
While your async task is executing, consider showing some kind of progress indicator.

OutOfMemoryException when parsing large JSON responses

I am doing a project where I need to parse JSON from a URL through HttpClient. My code works fine for JSON object responses with a small amount of data. But when I use the same code to get a response with a huge amount of data (more than 3MB), I have a problem.
Here is my code:
JSONfunctions.java (function for json parsing)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
//import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
//import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
//import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
#SuppressWarnings("unused")
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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();
// Toast.makeText(getBaseContext, result, Toast.LENGTH_LONG).
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
ListJson.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
//import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ListJson extends ListActivity {
public static JSONObject json;
public static JSONArray data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list1);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// String semail = "partha#excoflare.com";
// String spassword = "partha123";
// Toast.makeText(getApplicationContext(), JSONExample2.strEmail, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), JSONExample2.strPwd, Toast.LENGTH_LONG).show();
//
json = JSONfunctions.getJSONfromURL("url here");
try{
data = json.getJSONArray("server_list");
for(int i=0;i<data.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = data.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("ServUser"));
map.put("email", "" + e.getString("ServURL"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
// try {
// JSONObject newObject=json.getJSONObject("subscription");
// JSONArray data1 = newObject.getJSONArray("cust_product");
//
// Toast.makeText(getApplicationContext(), data1.toString(), Toast.LENGTH_LONG).show();
//
// for(int i=0;i<data1.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
// JSONObject e = data.getJSONObject(i);
//
// map1.put("id", String.valueOf(i));
// map1.put("name", "" + e.getString("ServUser"));
// map1.put("email", "" + e.getString("ServURL"));
// mylist.add(map1);
// }
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.item_list,
new String[] { "name", "email" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//#SuppressWarnings("unchecked")
//HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
// Toast.makeText(ListJson.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), parent.getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
// String a= parent.getItemAtPosition(position).toString();
Intent intent2= new Intent(ListJson.this, ListJson2.class);
startActivity(intent2);
}
});
}
I am getting an OutOfMemoryException. I changed heap_size to 192MB and ram size to 32MB, but with no luck. How can I fix this?
Big amounts of data of JSON must be cut to smaller pieces. For example you have a 50000 products on your database. Then it's wise to paginate API requests - get this huge amount of products by 100-500 records on one query. That will solve your problem.
This approach solves one problem more - errors caused by internet and gprs connection loss etc.
If API is yours then you can change this. If not, then this is a big failure of API design and you can send change request.
EDIT:
Did a little reading and found that highly recommended for parsing huge load of JSON data is http://jackson.codehaus.org/ (Jackson Processor). Haven't tried it, so cannot comment about this library. Also recommend you to save this JSON stream into the file (don't load it to memory) and then parse it by chunks.

Categories

Resources