async task issue in json format - android

i have a problem while im get the data from the server in text i can't converted into json object can not be converted into json array i just get the title and author from the database and show in list view
{"document":[{"id":"1","title":"complete refrence of android",
"author":"parag vyas","description":"lnvkzxhbkgbovdghognsdkhogjhlldnglj"}]}
plz help me
public class showalbooks extends Activity {
ArrayList<String> mylist = new ArrayList<String>();
String returnString="";
ListView listView ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalbooks);
listView = (ListView) findViewById(R.id.mylist);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);
}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONArray jArray = new JSONArray(var);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
listView.setFilterText(returnString);
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View listview,
int documentid, long documenttitle) {
// TODO Auto-generated method stub
}
});
}
}}}

The JSON array is enclosed by a JSON object, and has the id "document".
instead of:
JSONArray jArray = new JSONArray(var);
You should have:
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");

Related

Android - retrieving json via HTTPS

I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
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> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}

How to put data in listview which received using AsyncTask?

I am successfully retrieving but unable to put data into listview. how to update ui thread
after retrieving data.
here is the class of asynctask that retrieves data
I tried to update in onPostExecute but couldn't succeed.
class GetJson extends AsyncTask<String, Integer, ArrayList<RowItem>> {
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
//ArrayList<ArrayList<String>> fullscreens = new ArrayList<ArrayList<String>>() ;
public AsyncResponse delegate = null;
private CustomListViewAdapter arrayadapter;
private ProgressDialog pDialog;
private Context Mycontext;
private ArrayList<String> alist;
private ListView listView;
public GetJson(Context cnxt,ArrayList<String> alist, CustomListViewAdapter adapt,ListView listView) {
Mycontext = cnxt ;
//this.rowItems = rowItems;
this.alist = alist;
this.listView = listView;
}
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
this.pDialog = new ProgressDialog(Mycontext);
this.pDialog.setMessage("Please wait..");
this.pDialog.setIndeterminate(true);
this.pDialog.setCancelable(false);
this.pDialog.show();
//alist.add("fifa");
}
#Override
protected ArrayList<RowItem> doInBackground(String... passing) {
here i am recieving data
return rowItems;
}
#Override
protected void onPostExecute(ArrayList<RowItem> Items) {
super.onPostExecute(Items);
this.pDialog.dismiss();
}
}
I laso tried runuithread in doinBackgroung method
there also i am getting runtime errors
here is my code
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
InputStream is = null;
JSONObject json_data=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray ja = new JSONArray();
List<NameValuePair> params = new LinkedList<NameValuePair>();
for(String s : alist)
{
Log.d("s",s);
params.add(new BasicNameValuePair("list[]",s));
}
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
// 2. make POST request to the given URL
HttpGet httpPost = new HttpGet("http://10.0.3.2/infogamma/getapps.php?"+paramString);
// 4. convert JSONObject to JSON to String
String json = ja.toString();
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
is.close();
result = stringbuilder.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
//get json data
try{
//JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
Log.d("app_lentgh", Integer.toString(jArray.length()));
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
// this.donnees.add("title: "+ json_data.getString("title") + " appid: " + json_data.getString("appid") );
try{
//commmand http
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://10.0.3.2/infogamma/getAppDetails.php?appid="+json_data.getString("appid"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
ArrayList<String> screenitem = new ArrayList<String>();
try{
JSONObject j = new JSONObject(result);
screenitem.add(j.getString("scr1"));
screenitem.add(j.getString("scr2"));
screenitem.add(j.getString("scr3"));
// this.fullscreens.add(screenitem);
// RowItem(ImageView imageId, String title, String desc,String catgs,String downloads,String rating,String discription)
RowItem item = new RowItem(j.getString("coverimage"), j.getString("title"), j.getString("category"),j.getString("downloads"),j.getString("rating"),
j.getString("scr1"),j.getString("scr2"),j.getString("scr3"),j.getString("discription"),j.getString("developer"),j.getString("price")
,json_data.getString("appid"));
rowItems.add(item);
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
//SharedPreferences.Editor editor = ((Activity) Mycontext).getPreferences(Mycontext.MODE_PRIVATE).edit();
//editor.;
//editor.commit();
//Log.i("title",json_data.getString("title"));
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars",""+e.toString());
}
adapt = new CustomListViewAdapter(getApplicationContext(),
R.layout.list_item, rowItems);
listView.setAdapter(adapt);
}});
return (null);
}
You can populate the list view from doInBackground by this code
runOnUiThread(new Runnable() {
public void run() {
//set listview Adapter here
}
});
this thing is not preferable. One more thing you can do is create a class which can hold the data you want to show on the item of a list and pass the array of that class object to onPostExecute method from where you can handle the UI thread.
Do it in onPostExecute() or if you want to add them from doInBackground() instantly, do it using runOnUiThread().
Edit:
After reading your comments, You are using CustomListViewAdapter, do you have a constructor with Context,int,ArrayList<String> as parameters in your adapter class?

Sending a json Http request with parameters from Android

After reading some tutorials i can take a list of orders from MySql database with php and show in my Android app. I need to have this list filtered by userId (the useid is saved in preferences).
I have to send http request with parameter "userId" but i dont know how.
The code that i have now :
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
For orders list:
public class Masuratori extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", e.getString("clie"));
map.put("magnitude", e.getString("userid"));
map.put("adresa", e.getString("adr"));
map.put("detalii", e.getString("det"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_masuratori,
new String[] { "name", "adresa","detalii","magnitude"},
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3 });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Masuratori.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
I receive the userid value from preferences:
public class Calculator extends Activity {
TextView prefEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
prefEditText= (TextView)findViewById(R.id.textUser);
loadPref();
prefEditText= (TextView)findViewById(R.id.prefEditText);
loadPref();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.calculator, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
//super.onActivityResult(requestCode, resultCode, data);
loadPref();
}
private void loadPref(){
SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String my_edittext_preference = mySharedPreferences.getString("edittext_preference", "");
prefEditText.setText(my_edittext_preference);
}
}
Before you execute() your HttpPost, you can add parameters with the following code:
// Add userId parameter
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("userId", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Since you are only sending only one parameter, Why don't you send it in the Query String.
String userId = getUserId();
JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php?userId=" + userId);
Then you retrive it in php
$userId = $_GET['userId']

Can get information from JSON API

im trying to get some information from a site BayFiles.net using their API.
The call URL is: http://api.bayfiles.net/v1/account/files?session=SESSION-ID
The error i get is:
07-04 13:54:39.525: E/log_tag(588): Error parsing data org.json.JSONException: Value at error of type java.lang.String cannot be converted to JSONArray
The JSON output when correct sessionID is something like this:
{
"error": "",
"S8tf": {
"infoToken": "wCfhXe",
"deleteToken": "gzHTfGcF",
"size": 122484,
"sha1": "8c4e2bbc0794d2bd4f901a36627e555c068a94e6",
"filename": "Screen_Shot_2013-07-02_at_3.52.23_PM.png"
},
"S29N": {
"infoToken": "joRm6p",
"deleteToken": "IL5STLhq",
"size": 129332,
"sha1": "b4a03897121d0320b82059c36f7a10a8ef4c113d",
"filename": "Stockholmsyndromet.docx"
}
}
however i cant get to catch the respons and show it in a listview.
This is my activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("error");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
//map.put("video_location", "" + e.getString("video_location"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
and my JSONfunctions:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}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());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Any help is much appreciated!
As 'error' is not JSONArray it is giving you parsing error.
JSONArray shows = object.getJSONArray("error");
Change you line to
String shows = object.getString("error");
You can refer to these link for JSON Parsing.
https://stackoverflow.com/a/16938507/1441666

in AsyncTask i want the data in list view

hi friends i just want the data show in a list view i using async task and i complete get the data in json and filtering it by id and title now i show id and title in a listview can you help me thanks in advance
public class runActivity extends Activity implements OnClickListener {
String returnString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
ListView listView = (ListView) findViewById(R.id.mylist);
listView.setFilterText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
You will need to build an Array to use with ListAdapter.
Here is a guide from Google: http://developer.android.com/resources/tutorials/views/hello-listview.html
I think the best solution would be to create a Handler in your activity. You can then send a message to the handler and get the data and put it in the ListView.
In doInBackground "for" loop just either create the array of your data or put data in Array list of object (then need to write custom adapter)
for
1- option
http://www.java-samples.com/showtutorial.php?tutorialid=1516
http://www.ezzylearning.com/tutorial.aspx?tid=1659127&q=binding-android-listview-with-string-array-using-arrayadapter
For
2- option
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

Categories

Resources