JSON parsing using AsynTask - android

i have done JSON parsing without using async task, it is working fine in gingerbread(2.3)
but when i am running the same project on ICS(ice cream sandwich) application is crashing, i heard somewhere that i will have to do the parsing in asynctask but i am new to android and unable to do that can someone help me ............
here's my JSON class :-
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;
}
}
and here's my MAinActivity which is using JSON class :-
public class MainActivity extends ListActivity {
Context context;
ArrayList<String> contentList,slugList;
ArrayList<HashMap<String, String>> mylist;
JSONObject json;
JSONArray latest;
ImageView bck;
String shareUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
bck = (ImageView) findViewById(R.id.bckbtn);
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
context=this;
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_latest_tab,
new String[] { "name"},
new int[] { R.id.item_title});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position); */
//Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(context,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
plz help me to get this working using AsyncTask .......

Change your code Using AsyncTask as for Getting data from server :
private class LongOperation extends AsyncTask<String, Void,
ArrayList<HashMap<String, String>>> {
ArrayList<String> contentList,slugList;
ArrayList<HashMap<String, String>> mylist;
JSONObject json;
JSONArray latest;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>>
doInBackground(String... params) {
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com"+
"/wp/?json=get_category_posts&slug=latest");
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return mylist;
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(this, result ,
R.layout.activity_latest_tab,
new String[] { "name"},
new int[] { R.id.item_title});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
and execute AsyncTask from onCreate of Activity as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
bck = (ImageView) findViewById(R.id.bckbtn);
new LongOperation().execute(""); // execute here
// your code here.....
finally you must read about AsyncTask for next use from here
http://developer.android.com/reference/android/os/AsyncTask.html

The problem is not with parsing of json data. The problem here is that you've been trying to make network connection on the Main thread. Network connections are long tasks and should be run in a separate thread. What you have to do here is basically put your
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
line in the AsyncTask
I hope this helps!

First of all, consider to post Logcat output whenever you are facing issue/getting exceptions in Android.
Now, your current exception is NetworkOnMainThreadException, which is just because of you are making a web call directly on Main Thread.
From Android 3.0, Android has announced you can't do it directly on Main Thread.
To resolve this issue, you can either implement AsyncTask or write down the below code before making a web call:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Read more: Android StrictMode – NetworkOnMainThreadException

yes finally i have done it thanks for all the ideas ......
I have created another class for asynctask like this :-
class MyAsyncTask extends AsyncTask> > {
ArrayList> mylist = new ArrayList>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// TODO Auto-generated method stub
mylist = new ArrayList<HashMap<String, String>>();
contentList=new ArrayList<String>();
slugList=new ArrayList<String>();
json = JSONfunctions.getJSONfromURL("http://madhuridixit-nene.com/wp/?json=get_category_posts&slug=latest");
try{
latest = json.getJSONArray("posts");
for(int i=0;i<latest.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = latest.getJSONObject(i);
String name = e.getString("title_plain");
String content = e.getString("content");
contentList.add(content);
String chng = "–";
String fnl_Str = name.replace(chng, "");
String slug = e.getString("slug");
slugList.add(slug);
map.put("id", String.valueOf(i));
map.put("name", fnl_Str);
map.put("date", e.getString("date"));
shareUrl ="http://madhuridixit-nene.com/latest/post/";
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
showProgress.setVisibility(View.VISIBLE);
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(LAtestTab.this, result , R.layout.activity_latest_tab,
new String[] { "name" },
new int[] { R.id.item_title});
LAtestTab.this.setListAdapter(adapter);// If Activity extends ListActivity
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
showProgress.setVisibility(View.GONE);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(context,WebViewActivity.class);
intent.putExtra("content", contentList.get(position));
intent.putExtra("shareUrl", shareUrl+slugList.get(position));
intent.putExtra("tab_value", 1);
startActivity(intent);
}
});
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgress.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
showProgress.setVisibility(View.VISIBLE);
}
}

Related

Button click action not working in android listview

I am developing an android app which functions like as follows
Admin creates the data and saves it into database then user access the same data through app when it comes down to showing the data to user i fetch the data from the database which admin has already saved i show the data in listview, and listview having buttons in each row when user click on button it dose not goes to next activity.When user will click on button in listview the activity should pass to next activity.How do i do this?
//java activity
public class MainActivity extends ActionBarActivity {
String myJSON;
SimpleAdapter adapter;
Button btn;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "sname";
private static final String TAG_PRICE = "sprice";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
// ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>();
ListView list, listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView_search);
btn = (Button) findViewById(R.id.button3_book);
personList = new ArrayList<HashMap<String, String>>();
getData();
// Listview on item click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent zoom=new Intent(parent.getContext(), Details.class);
parent.getContext().startActivity(zoom);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String sname = c.getString(TAG_NAME);
String sprice = c.getString(TAG_PRICE);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,sname);
persons.put(TAG_PRICE,sprice);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.search_item,
new String[]{TAG_NAME,TAG_PRICE},
new int[]{ R.id.textView8_sellernm, R.id.textView19_bprice}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(MainActivity.this,Details.class);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://example.com/User/reg/listview.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}

Not able to get data from Json completely

i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated.
You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/
i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this:
if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me.
this is my code :
public class MainActivity extends Activity {
// URL to get contacts JSON
private static String url = "http://abinet.org/?json=1";
// JSON Node names
private static final String TAG_POSTS = "posts";
static final String TAG_TITLE = "title";
private ProgressDialog pDialog;
JSONArray contacts = null;
TextView img_url;
ArrayList<HashMap<String, Object>> contactList;
ListView lv;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.newslist);
contactList = new ArrayList<HashMap<String, Object>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject jsonObj = jParser.getJSONFromUrl(url);
// if (jsonStr != null) {
try {
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_POSTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
// JSONObject c = contacts.getJSONObject(i);
JSONObject posts = contacts.getJSONObject(i);
String title = posts.getString(TAG_TITLE).replace("’", "'");
JSONArray attachment = posts.getJSONArray("attachments");
for (int j = 0; j< attachment.length(); j++){
JSONObject obj = attachment.getJSONObject(j);
JSONObject image = obj.getJSONObject("images");
JSONObject image_small = image.getJSONObject("thumbnail");
String imgurl = image_small.getString("url");
HashMap<String, Object> contact = new HashMap<String, Object>();
contact.put("image_url", imgurl);
contact.put(TAG_TITLE, title);
contactList.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
adapter=new LazyAdapter(MainActivity.this, contactList);
lv.setAdapter(adapter);
}
}
}
this is my JsonParser class (although its not required):
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;
}
}
and this is adapter class:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, Object>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.third_row, null);
TextView title = (TextView)vi.findViewById(R.id.headline3); // title
SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
// Setting all values in listview
title.setText((CharSequence) song.get(MainActivity.TAG_TITLE));
iv.setImageUrl((String) song.get("image_url"));
thumb_image);
return vi;
}
}
Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.
Some of the 10 (well today there are 10 ) 'titles' have no 'attachments'. Some have one and some have two. There are only 5 titles wich have one or two images. You only create a new
HashMap<String, Object> contact
if there are attachments. (The attachment are the images). You should create the 'contact' before you enter the attachments loop. Further you only need one image for each title. You can set the image null if there are no attachments. In getView if the image is null you set some image from your drawable res.

what should be the correct answer for this exception? "Android.os.NetworkOnMainThreadException"

what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});

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']

using AsyncTask to display data in ListView

I need me a little help. I need to use asynctask to display data in ListView. But I don't know how becouse I'm new in Android programming ... thank you very much for any help.
public class Main extends ListActivity {
Button buttonbg;
/** Called when the activity is first created. */
#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://10.10.10.10/data.php");
try{
JSONArray ip = json.getJSONArray("ip");
for(int i=0;i<ip.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = ip.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("data1", e.getString("date"));
map.put("data2", "Location:" + e.getString("location") + " Status:" + e.getString("status"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "data1", "data2" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}}
Try this
new MyAsyncTask.execute("http://10.10.10.10/data.php");
Declare the task as
class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(params[0]);
try {
JSONArray ip = json.getJSONArray("ip");
for (int i=0;i<ip.length();i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = ip.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("data1", e.getString("date"));
map.put("data2", "Location:" + e.getString("location") + " Status:" + e.getString("status"));
mylist.add(map);
}
return mylist
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(YourActivity.this, result , R.layout.main,
new String[] { "data1", "data2" },
new int[] { R.id.item_title, R.id.item_subtitle });
YourActivity.this.setListAdapter(adapter); // If Activity extends ListActivity
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
Hope it helps.
Do not download any data in your onCreate() - if it takes too long then you will get ANR exception (Activity Not Responding). You should use AsyncTask as in your question. For AsyncTask you have very good example on android site:
http://developer.android.com/reference/android/os/AsyncTask.html
you should put JSONfunctions.getJSONfromURL() inside doInBackground()
and all whats below in onPostExecute()

Categories

Resources