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);
Related
im new here, sorry if i doing something idiot question,
for the Issues
i already create an app like that below, and all the value in the spinner obtained by JSON in this link
and this happens when the application running,
Spinner
but i want to set if someone choose "ardie halim" the 2nd spinner just show "mobile developer", and if someone choose "indah" the 2nd spinner showing "database oracle", and so on
i tried to find the tutorial from go*gle, but i dunno what the right keyword to find out,
FYI about my code MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
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.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
ArrayList<String> listItems2=new ArrayList<>();
ArrayAdapter<String> adapter2;
Spinner sp2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
sp2=(Spinner)findViewById(R.id.spinner2);
adapter= new ArrayAdapter<>(this, R.layout.spinner_layout, R.id.txt, listItems);
adapter2= new ArrayAdapter<>(this, R.layout.spinner_layout, R.id.txt, listItems2);
sp.setAdapter(adapter);
sp2.setAdapter(adapter2);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
ArrayList<String> list2;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
list2=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://zxccvvv.netne.net/dosen.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("nama_dosen"));
list2.add(jsonObject.getString("mat_kul"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
listItems2.addAll(list2);
adapter.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
}
}
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(list.get(position).equals("ardie halim")){
listItems2.clear();
listItems2.add("mobile developer");
adapter2.notifyDataSetChanged();
}
else if(list.get(position).equals("indah")){
listItems2.clear();
listItems2.add("database oracle");
adapter2.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
The Below Code is For Set Json Data to Spinner
try {
Gson gson = new Gson();
String json = gson.toJson(response.body());
JSONObject jsonObject = new JSONObject(json);
Log.d("check", "jsonData : " + json);
List<String> allGoverNames = new ArrayList<String>();
allGoverNames.add(0, "Select Governorate");
JSONArray cast = jsonObject.getJSONArray("governorate");
for (int i = 0; i < cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
governorateNamenameString = actor.getString("governorate_name");
allGoverNames.add(governorateNamenameString);
}
GoverdataAdapter = new ArrayAdapter<String>
(context, android.R.layout.simple_spinner_item, allGoverNames);
GoverdataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
GovernorateSpinner.setAdapter(GoverdataAdapter);
} catch (JSONException e)
{
e.printStackTrace();
}
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
I wrote this code to read and write data from webserver (mysql databse) and then all the data will be show on my andriod application.
In this regard I used PHP services for reading and writing the data from web server. Everything is working fine it gets data from web server correctly but when it reaches at this line:
int success = jsonObject.getInt(TAG_SUCCESS);
It shows a null pointer exception I don't know why but it actually made me insane.
Code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.commons.collections.*;
//import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.*;
public class MiddleActivity extends Activity {
Button btnMiddleDB;
ProgressDialog pDialog ;
JSONParser jsonParser = new JSONParser();
JSONArray places = null;
private static final String URL = "http://192.168.1.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_middle);
new LoadGettingFromDatabase().execute();
btnMiddleDB = (Button) findViewById(R.id.button1);
btnMiddleDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
}
running background thread for getting data from webserver
class LoadGettingFromDatabase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MiddleActivity.this);
pDialog.setMessage("Getting from database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
**after getting data from webserver parse it to json and store it into string**
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("Seen","seen1");
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
Log.d("String","JSON 2");
//Log.d("All entries","Entries" + jsonObject.toString());
try{
Log.d("Seen","seen2");
ACTUALLY THE PROBLEM IS HERE
int success = jsonObject.getInt(TAG_SUCCESS);
Log.d("Seen","seen5");
if(success == 1){
//Entries found
Log.d("Seen","seen6");
places = jsonObject.getJSONArray(TAG_PRODUCTS);
for(int i=0;i<places.length();i++){
JSONObject temp = places.getJSONObject(i);
String id = temp.getString(TAG_PID);
String name = temp.getString(TAG_NAME);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TAG_PID, id);
hashMap.put(TAG_NAME, name);
placesList.add(hashMap);
}
}
} catch (Exception e) {
Log.e("success","success status " + e);
}
return null;
}
public void onProExecute(String file_url){
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter listAdapter = new SimpleAdapter(MiddleActivity.this, placesList, R.layout.list_item, new String[]{
TAG_PID, TAG_NAME},new int[]{R.id.ID, R.id.Name});
ListView listView = (ListView) findViewById(R.layout.list_item);
listView.setAdapter(listAdapter);
};
});
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_middle, menu);
return true;
}
}
**and log cat is**
05-07 00:29:54.419: D/Seen(30282): seen1
05-07 00:29:54.569: D/Seen(30282): seen3
05-07 00:29:54.909: D/Seen(30282): seen4
05-07 00:29:54.979: D/String(30282): JSON get_all_products.php
05-07 00:29:54.979: D/String(30282): db_connect.php
05-07 00:29:54.979: D/String(30282): db_config.php
05-07 00:29:54.979: D/String(30282): {"success":0,"message":"No products found
05-07 00:29:55.300: D/String(30282): JSON 1
05-07 00:29:55.300: D/String(30282): JSON 2
05-07 00:29:55.310: D/Seen(30282): seen2
**05-07 00:29:55.310: E/success(30282): success status
java.lang.NullPointerException**
and here is my jsonparser class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
Your jsonObject is null, debug the app by setting breakpoint at line->
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
And check value of jsonObject.
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.
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.