JSON mplimentation on ListView - java

I have the following JSON response:
{
"success":1,
"message":"Post Available!",
"posts":[
{
"id":"1",
"name":"hi",
"phone":"123",
"department":"and",
"days":"1",
"reason":"SICK"
},
{
"id":"2",
"name":"at",
"phone":"0000000",
"department":"android",
"days":"60",
"reason":"sick"
},
{
"id":"3",
"name":"as",
"phone":"21",
"department":"as",
"days":"3",
"reason":"git"
},
{
"id":"4",
"name":"abcd",
"phone":"123",
"department":"abcd",
"days":"1",
"reason":"abcd"
}
]
}
How can I implement this on list view?
My JSONParser class as:
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
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;
}
And my Main activity code (activity_main) contains only a listview (extends ListActivity).
Do I have to add any layout file, or do I have to change the JSONparse class?
Thanks in advance.

Yes Atif, You have to use custom adapter to show data in ListView. You have to create your own layout for listview & it will inflate in your custom adapter. You can refer below link for this:
Listview Adapter

First of all Add following lines to build.gradle (Module:app)
compile 'com.google.code.gson:gson:2.2.4'
After that create a layout of what u want to show in ListView:I have jsut shown name, phone from your json:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
<TextView
android:id="#+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
Then create an adapter class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
private final JsonResponseDTO data;
private final Context ctx;
private final LayoutInflater inflater;
View v;
public ListViewAdapter(Context ctx, JsonResponseDTO response) {
this.data = response;
this.ctx = ctx;
inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (data.posts.size() > 0) {
return data.posts.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return data.posts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
UserDetDTO dto = data.posts.get(position);
ViewHolder vh = new ViewHolder();
if (convertView == null) {
v = inflater.inflate(R.layout.row, null);
}
vh.tvName = (TextView) v.findViewById(R.id.name);
vh.tvPhone = (TextView) v.findViewById(R.id.phone);
vh.tvName.setText(dto.name);
vh.tvPhone.setText(dto.phone);
return v;
}
private static class ViewHolder {
public TextView tvName, tvPhone;
}
}
After that call this from Activity class and set adapter in Listview like:
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ListView lv = (ListView) findViewById(R.id.lv);
JSONObject json = /* JSON u recieved from server*/;
JsonResponseDTO jsonRes = new GsonBuilder().create().fromJson(json.toString(), JsonResponseDTO.class);
if (jsonRes != null) {
ListViewAdapter adapter = new ListViewAdapter(ListActivity.this, jsonRes);
lv.setAdapter(adapter);
}
}
}

This may help you:
1) Create a model class with getters and setters for storing the JSON data.
2) Parse JSON and store in an ArrayList<>. // You can use Gson for parsing.
3) Create a layout.xml for displaying list items.
5) Create an adapter class extending BaseAdapter and set the data using layout.xml.
4) Populate data in the list.

Related

Displaying database records in android using JAVA RESTful webservice

I am trying to display database record using java restful web service. I have able to create a login form using it but I cannot display the records on the database. I tried this code but its not working at all. When button is pressed nothing happens. Heres my code.
DriverDetails.java
class Details extends Activity {
TextView name1;
TextView plate1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://192.168.254.108:8080/taxisafe/display/taxidetails";
//JSON Node Names
private static final String TAG_USER = "taxi";
private static final String TAG_NAME = "taxi_name";
private static final String TAG_EMAIL = "taxi_plate_no";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
plate1 = (TextView)findViewById(R.id.plate);
}
#Override
protected JSONObject doInBackground(String... args) {
HttpConnection jParser = new HttpConnection();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
name1.setText(name);
plate1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
HttpConnection.java
public class HttpConnection {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public HttpConnection() {
}
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;
}
}
I suggest adding Volley to your project
https://developer.android.com/training/volley/index.html
and following the example here https://developer.android.com/training/volley/request.html#request-json
You will not need to create your own HTTP request. Let Volley handle the network request using JSONObjectRequest

ERROR parsing data value of type org.json.JSONArray cannot be converted to JSONObject

While Running the code (given after the error msg) throws the error as
Coding follows:
public class Slide extends ActionBarActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> detailsList; //Creating a Arraylist
private static String URL = "URL to my php page";
private static final String TAG_DETAILS = "details";
private static final String TAG_TITLE = "title";
JSONArray details = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
new onlineload().execute();
}
class onlineload extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Slide.this);
pDialog.setMessage("Fetching Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String title = "";
TextView tvTitle = (TextView)findViewById(R.id.Title);
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
Log.d("All Products:",json.toString());
try {
details = json.getJSONArray(TAG_DETAILS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
title = title + c.getString(TAG_TITLE)+"\n";
tvTitle.setText(title);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Shown above is my java code..
Function of this code is to fetch Book title (more than 10 books title is available in database)from the online database and view it in an scroll view activity ..
my php code is working am getting the output only the problem is in displaying it in android activity !!
Looking for some help!!
JSON CODE:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONArray 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
Log.d("Entered Get", "Get SUccess"+url+method);
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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Agree with #ρяσѕρєя K
There was cast exception occurred that means you need to use JSON Array. Coz you are using JSON Object where actually JSON Array is required.
If you are confused within response which is receiving is JSONArray or JSONObject then you can go for get() method which return data in Object manner.
example : Object c = details.get(i);
So after that you can check for
If(c instanceOf JSONArray){
/// perform as array operation
}
If(c instanceOf JSONObject){
// perform json object retrieving operation
}

Error when parsing json result from http post on android app

I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].

how to do Json Parsing in android

http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
This is web Url
[{"id":1,"title":"Tom B","description":"4006","url":"www.Norway.com"},
{"id":2,"title":"Tom c","description":"4007","url":"www.NorwayC.com"},
{"id":3,"title":"Tom D","description":"4008","url":"www.NorwayD.com"},
{"id":4,"title":"TomE","description":"www.google.com","url":"url"}]
and this format of data i want parse and Print it Title in Listview But i am Unable to Parse it plz check where is the Problem. here is my code:
package com.example.andjsonparin;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private static String url="http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "title";
private static final String TAG_EMAIL = "description";
private static final String TAG_USER = "url";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
// JSONObject json = jParser.getJSONFromUrl(url);
// Log.e("JSON Parser", "Error parsing data " + json);
JSONArray json = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + json);
//Parse the values as below.
for(int i = 0; i < json.length(); ++i) {
JSONObject mobj = json.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url-mobj.getString("url");
}
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
}
}
Json Parser class:
package com.example.andjsonparin;
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 String 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 json;
}
}
when i Run this code then it throw NullPointException in Jsonparser class please tell me how i will do so that i can Out i dont know where am doing mistake
Here
jObj = new JSONObject(json); <<<
you are getting JSONArray instead of JSONObject from webservice. so do following changes in getJSONFromUrl method :
1. Change method return type to JSONArray instead of JSONObject
2. Create JSONArray instead of JSONObject from webservice response string as:
JSONArray jsonarr = new JSONArray(json);
also use AsyncTask or Handler to avoid network operation on main UI Thread
JSONArray array=new JSONArray(jsonString_Returned_From_Server);
int len = array.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = array.getJSONObject(i);
String id = obj.getString("id");
String title = obj.getString("title");
etc...
}
As you are getting the JSONArray in your response then you will have to parse your response using JSONArray not JSONObject
Try out as below:
JSONArray json = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + json);
//Parse the values as below.
for(int i = 0; i < json.length(); ++i) {
JSONObject mobj = json.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url-mobj.getString("url");
}
EDITED:
In Your parser class you just need to return the String instead of JSONObject.
In your JSONParser class write your method as below:
public static String getJSONFromUrl(String p_url) {
String m_response = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpget = new HttpPost(PeakAboo.BaseUrl + p_url);
HttpResponse response;
try {
response = client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader bf = new BufferedReader(
new InputStreamReader(in));
while ((line = bf.readLine()) != null) {
sb.append(line);
}
m_response = sb.toString();
System.err.println("JSON Response--->" + m_response);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return m_response;
}
Here is your updated code of your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
// JSONObject json = jParser.getJSONFromUrl(url);
// Log.e("JSON Parser", "Error parsing data " + json);
user = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + user);
//Parse the values as below.
for(int i = 0; i < user.length(); ++i) {
JSONObject mobj = user.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url=mobj.getString("url");
}
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
}
}
Change your method like below,
public String 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();
return json;
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
}
and replace MainActivity like below,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetResponseData().execute();
}
class GetResponseData extends AsyncTask<String, String, Boolean> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(MainActivity.this, "", "Loading",
false);
}
#Override
protected Boolean doInBackground(String... params) {
try {
JSONParser jParser = new JSONParser();
titleList = new ArrayList<String>();
String json_response = jParser.getJSONFromUrl(url);
if (json_response!=null) {
JSONArray jsonArray = new JSONArray(json_response);
for (int i = 0; i < jsonArray.length(); i++) {
titleList
.add(jsonArray.getJSONObject(i).getString("title"));
}
return true;
}
else
return false;
} catch (Exception exception) {
exception.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if(result)
{
//do your stuff with titleList
}
}
}
// Here is the code of how to Request API from android Code:
JsonObject response = WebAPIRequest.makeJsonObjHttpRequest(URLS.USER_REGISTRATION, "POST", params);
// Now accessing class
public static JSONObject makeJsonObjHttpRequest(String url, String method,
List<NameValuePair> params) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
if (method == "POST") {
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") {
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;
}

How can i parse a TwitterFeed (JSON) to a custom listview?

I have got a code from a tutorial How to parse JSON data into a Custom Listview
Here is the code from the tutorial with a couple of modifications:
public class TwitterParseHandler extends Activity {
ArrayList<TwitterFeed> arrayOfWebData = new ArrayList<TwitterFeed>();
class TwitterFeed {
public String text;
public String created_at;
}
FancyAdapter aa=null;
static ArrayList<String> resultRow;
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_parse_handler);
String result = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=3FMNu&count=20&exclude_replies=True");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
webs.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error in converting result "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for (int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
TwitterFeed resultRow = new TwitterFeed();
resultRow.text = json_data.getString("text");
resultRow.created_at = json_data.getString("created_at");
arrayOfWebData.add(resultRow);
}
}catch(JSONException e){
Log.e("log_tag", "Error in parsing data "+e.toString());
}
ListView myListView = (ListView)findViewById(R.id.list);
aa=new FancyAdapter();
myListView.setAdapter(aa);
}
catch(Exception e){
Log.e("ERROR", "ERROR IN CODE: "+e.toString());
e.printStackTrace();
}
}
class FancyAdapter extends ArrayAdapter<TwitterFeed> {
FancyAdapter() {
super(TwitterParseHandler.this, android.R.layout.simple_list_item_1, arrayOfWebData);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null) {
LayoutInflater inflater=getLayoutInflater();
convertView=inflater.inflate(R.layout.twitterlist, null);
holder=new ViewHolder(convertView);
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.populateFrom(arrayOfWebData.get(position));
return(convertView);
}
}
class ViewHolder {
public TextView name=null;
public TextView birthday=null;
ViewHolder(View row) {
name=(TextView)row.findViewById(R.id.TwitterText);
birthday=(TextView)row.findViewById(R.id.TwitterDatum);
}
void populateFrom(TwitterFeed r) {
name.setText(r.text);
birthday.setText(r.created_at);
}
}
}
I have replaced the JSON from the tutorial (that was working fine) with my twitterfeed: https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=3FMNu&count=20&exclude_replies=True
and changed the attributes from name and birthday to text and created_at, now when I debug it I get the following error:
08-04 12:36:40.539: E/log_tag(4599): Error in parsing data org.json.JSON
Exception: Value
{ "error": "This method requires a GET.",
"request":"\/1\/statuses\/user_timeline.json?include_entities=true&include_rts=true&screen_name=3FMNu&count=20&exclude_replies=True"
} of type org.json.JSONObject cannot be converted to JSONArray
Why does this happen and how do I fix it?
Try:
HttpGet httpGet = new HttpGet(https://api.twitter.com/1/statuses/user_timeline.json);
with parameters:
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("include_entities", true));
...
Try also How to add parameters to a HTTP GET request in Android?

Categories