wrong in json parsing - android

please help me to find the error in this code.
I want to get some data from remote server (php & mysql) by json then parsing it
the problem is that result returns null but it is supposed to return name at this link :
http://codeincloud.tk/json_android_example.php
package com.shadatv.shada;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;
import android.widget.Toast;
public class canticlesActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeincloud.tk/json_android_example.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ahmed .. " + result, Toast.LENGTH_LONG).show();
httpStuff.setText(result);
}
}
}

parse current json String as :
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
// convert data to json object
JSONObject last =new JSONObject(data);
because current webservice retuning an JSONObject only instead of JSONArray

Your URL provides the following data:
{"name":"Froyo","version":"Android 2.2"}
The chunk of code parsing the JSON is the following:
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
That makes the assumption that the JSON document you're reading is an Array instead of an Object. (Either is valid JSON, but the document you're fetching is quite clearly an Object). Web service calls may not always be returning one or the other so you'll have to take care that you're parsing against the correct type.

copy and past now it is working.
i changed JSONObject last =new JSONObject(data);
because http://codeincloud.tk/json_android_example.php retuning an JSONObject
package com.shadatv.shada;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;
import android.widget.Toast;
public class canticlesActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeincloud.tk/json_android_example.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
return last;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ahmed .. " + result, Toast.LENGTH_LONG).show();
httpStuff.setText(result);
}
}
}

Better to use GSON Library which is much simpler then doing manual parsing.
Link for the library is : http://code.google.com/p/google-gson/

Related

How to pass a variable from JSONArray

I have code that receives a variable from an external JSON array
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Toast;
public class ListviewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json_str = getJsonData();
try{
JSONArray jArray = new JSONArray(json_str);
JSONObject json = null;
json = jArray.getJSONObject(0);
String date=json.getString("data");
Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
}
private String getJsonData(){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("url_php_file_with_JSON");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//comparison variable (from String date=json.getString("data")) with an other static variable
How to correctly display variable String date = json.getString ( "data") for comparison in other functions?
While it is displayed in the function receiving a variable using Toast.makeText, and I have to work with it in other areas of the java file
You need to make your String a global variable, like follows:
public class ListviewActivity extends Activity {
private String date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json_str = getJsonData();
try{
JSONArray jArray = new JSONArray(json_str);
JSONObject json = null;
json = jArray.getJSONObject(0);
date=json.getString("data");
Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
}
// The rest of your code
}
That way, you can use it freely anywhere in your class.

want to send listview data to another activity in android

package com.example.selflistview;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost/listview.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String year=obj.getString("year");
String age=obj.getString("age");
Log.e("STRING", name);
r.add(name);
//r.add(year);
//r.add(age);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
//final String item = (String) arg0.getItemAtPosition(arg2);
Toast.makeText(getBaseContext(), "arg2 : "+arg2, Toast.LENGTH_SHORT).show();
Intent view_det = new Intent(getBaseContext(),ViewDetail.class);
view_det.putExtra("position",arg2);
startActivity(view_det);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
I want to send Year, name and age to another activity, i am able to get the positions at intent but not the other values. please help...
I am able to see those values in list., but not able to call at intent section.
Your help will be appreciated..
This might help
Public class MainActivity extends Activity {
TextView text;
List<String> r; //define list here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
r = new ArrayList<String>();
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost/listview.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String year=obj.getString("year");
String age=obj.getString("age");
Log.e("STRING", name);
r.add(name);
//r.add(year);
//r.add(age);
}
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
//final String item = (String) arg0.getItemAtPosition(arg2);
Toast.makeText(getBaseContext(), "arg2 : "+arg2, Toast.LENGTH_SHORT).show();
Intent view_det = new Intent(getBaseContext(),ViewDetail.class);
view_det.putExtra("position",arg2);
String name = r.get(arg2);//add this line to get name from the arraylist of that position
JSONObject obj=json.getJSONObject(arg2); //you can get other two values from json object
String year=obj.getString("year");
String age=obj.getString("age");
view_det.putExtra("name",name); //add this
view_det.putExtra("year",year); //add this
view_det.putExtra("age",age); //add this
startActivity(view_det);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
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.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

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.

Not getting the output

I'm trying to get the data from the database for which I created a php file. It returns the name as the reply to the call. the website it Ensignweb
the program code goes like this.
The php file is like this
<?php
$connect = mysql_connect("localhost","databasename","password");
mysql_select_db("ews_app");
$query = mysql_query("select name from comment");
if(!empty($query)){
if(mysql_num_rows($query)>0){
WHILE($row=mysql_fetch_array($query)):
$comment = array();
$comment["name"] = $row['name'];
echo "$comment<br>";
echo json_encode($comment);
echo "<br>";
endwhile;
}
}
?>
The java code goes like this:
import java.io.IOException;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://www.ensignweb.com/sandbox/app/comment11.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.data);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();//return 200 if execution is success
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG);
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
But It is not displaying the json reply. I'm stucked in it from past few days.
Please help me out of it. I really need it.

Categories

Resources