I am using a webservice to retrieve a JSON and convert it to a string.But i am getting the string as null.
The MainActivity class is:
package com.example.webserviceeg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnshowdata;
TextView txtdata;
String URL="http://www.footballultimate.com/fifa/index.php/api/matchShedule/";
ProgressBar pb;
HttpResponse response;
String result;
HttpEntity entity;
InputStream is;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowdata=(Button) findViewById(R.id.btnshowdata);
txtdata=(TextView) findViewById(R.id.txtdata);
pb=(ProgressBar) findViewById(R.id.progressBar1);
btnshowdata.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Retrievevalues().execute();
}
});
}
#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;
}
public class Retrievevalues extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
// TimeZone tz = TimeZone.getDefault();
// Date now = new Date();
// int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
pairs.add(new BasicNameValuePair("time_offset","19800"));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// txtdata.setText(result);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
pb.setVisibility(View.INVISIBLE);
}
}
}
I am using a second class containing static methods to convert the response object to a string:
responsetostring.java
package com.example.webserviceeg;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;
public class responsetostring {
// Json Response Processing
// Json Response Processing
public static String getResponseBody(HttpResponse response) {
// TODO Auto-generated method stub
String response_text = null;
HttpEntity entity = null;
try {
entity = response.getEntity();
try {
response_text = _getResponseBody(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return response_text;
}
public static String _getResponseBody(final HttpEntity entity) throws IOException,
ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static String getContentCharSet(final HttpEntity entity)
throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
}
But the string result in MainActivity , i am getting it as null.Please help
Change to this:
if (instream != null) {
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();
return sb.toString();
}
else
{
return "";
}
Related
I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format. Despite everything my AsyncTask doesn't seem to actually be executing. Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code. Hoping someone can help! Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CatImages req = new CatImages();
req.execute();
}
class CatImages extends AsyncTask<String, Integer, String> {
ArrayList<String> ids = new ArrayList<String>();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
ids.add(id);
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String fromDoInBackground) {
super.onPostExecute(fromDoInBackground);
}
}
}
Try changing !=null to ==null in your second while loop.
Also you just need while(on) in your first while loop.
Let me know if anything changes.
Hi every one I have a problem
i want to get data from site with json and show it in my android list view
but in my program i can only see the first result of json and dont
show me the all result of the json.
please help me.
this is my code
mainactivity code:
package com.example.delta.travel;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.3/upload/travel.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();
}
class travel extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET");
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
JSONObject c=s.getJSONObject(i);
String companyname=c.getString("companyname");
String cod=c.getString("cod");
String bign=c.getString("bign");
String stop=c.getString("stop");
String date=c.getString("date");
String time=c.getString("time");
String price=c.getString("price");
HashMap<String,String>map=new HashMap<String,String>();
map.put("companyname",companyname);
map.put("cod",cod);
map.put("bign",bign);
map.put("stop",stop);
map.put("date",date);
map.put("time",time);
map.put("price",price);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"},
new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
setListAdapter(adapter);
}
});
}
}
}
and my json parser code:
package com.example.delta.travel;
import android.net.http.HttpResponseCache;
import android.util.Log;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.List;
/**
* Created by delta on 5/28/2016.
*/
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 urlString, String method) {
if(method.equals("POST")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if(method.equals("GET")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
and my php code:
<?php
$con=mysqli_connect("localhost","root","","travels");
mysqli_set_charset($con,"utf8");
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["date"]=$row["date"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
$response["travel"]=array();
array_push($response["travel"],$temp);
$response["t"]=1;
echo json_encode($response);
}
}
else{
$response["t"]=0;
$response["message"]="Not Found";
echo json_encode($response);
}
?>
I have created local DAtabase, with MongoDB and NODEJS, and now i want to parse databse data with my android app, i think i write java code right , but it doesn not work, please help.
Thanks
Here is my Java code.
package com.example.hakobm.buttonparsing;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://localhost:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to PostExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
finally {
if(connection !=null) {
connection.disconnect();
}
try {
if(reader !=null) {
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
I am new to Java and Android.
I have been getting this error in my program length cannot be resolved or is not a field I just don't understand how to solve this.
Here's the code
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
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 android.os.AsyncTask;
import android.os.Environment;
public class DownloadImages extends AsyncTask {
protected Object doInBackground(Object... params) {
System.out.println("External Storage State = " + Environment.getExternalStorageState());
File directory=new File(Environment.getExternalStorageDirectory(), "/Images");
if (directory.exists()==false)
{
directory.mkdir();
}
for(int i = 0; i <URLS.length; i++) {
try {
File firstFile=new File(directory+"/" +i+ ".jpeg");
if(firstFile.exists()==false)
{
HttpClient httpClient =new DefaultHttpClient();
HttpGet httpGet =new HttpGet(URLS[i]);
HttpResponse resp = httpClient.execute(httpGet);
System.out.println("Status Code = " +resp.getStatusLine().getStatusCode());
if(resp.getStatusLine().getStatusCode()==200)
{
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
Boolean status = firstFile.createNewFile();
FileOutputStream foutS = new FileOutputStream(firstFile);
byte[] buffer = new byte[1024];
long total = 0;
int count;
while((count = is.read(buffer)) != -1){
total += count;
foutS.write(buffer, 0, count);
}
foutS.close();
is.close();
publishProgress(i);
}
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#SuppressWarnings("unchecked")
protected void onProgressUpdate(Object... values){
super.onProgressUpdate(values);
}
}
Getting Error in For Statement Line
for(int i = 0; i <URLS.length; i++) {
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity{
private static final String[] URLS = {
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2851.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImages().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
make URLS as public
public static final String[] URLS = {
and use it as
for(int i = 0; i <MainActivity.URLS.length; i++) {
Try it..,.
An inner class is a class declared inside another class. Try putting DownloadImages inside MainActivity.
I'm building my first android app - something that will display my tweets in a list.
I managed to get the app working earlier, but the tweets would sometimes take a long time to download, and the app would become unresponsive or crash.
I decided to add a thread to the app so the it wouldn't become unresponsive, but now it doesn't work at all :/
Does anyone know what's wrong? It's only my third day of learning java, and I can't seem to figure out what the problem is here.
Here's the code:
package com.app.first;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class Twitter extends ListActivity {
public ProgressDialog pd = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
new LoadTwitterFeed().execute();
}
public class LoadTwitterFeed extends AsyncTask<String, Integer, String> {
String tweets[] = new String[9];
public String readTwitterFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jjmpsp&include_rts=false&count=10");
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(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
tweets[i] = jsonObject.getString("text").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));
return null;
}
#Override
protected void onPostExecute(String result) {
// what to do when the task ends.
pd.hide();
}
}
}
set this code in onPostExecute
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));