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']
Related
my sql server collation is utf8 unicode
my php works fine
my android project is working fine with normal characters but in case of arabic char it display error "Error parsing json" line 233 in the activity listed below
I've tried my sql and php on other project its works but here I dont know whats the error json must be utf8 by defult
public class DealsListActivity extends Activity {
private String id;
// Progress Dialog
private ProgressDialog pDialog;
// creating JSON Parser object
JSONParser jParser = new JSONParser();
private static String url = "http://xxxxxxxxxxxx.get_all_deals_by_id.php";
// JSON Node names
private static final String TAG_DEALS = "deals";
private static final String TAG_ID = "id";
private static final String TAG_DEALNAME = "dealName";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_RESTID = "restID";
private static final String TAG_RESTNAME = "restName";
private static final String TAG_RESTTYPE = "restType";
private static final String TAG_LAT = "restLat";
private static final String TAG_LNG = "restLng";
private static final String TAG_SUCCESS = "success";
private JSONObject json;
JSONArray restaurantDealsData = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> restaurantDealsList = new ArrayList<HashMap<String, String>>();
ListView myList;
private String[] dealID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deals_list);
id = getIntent().getStringExtra("id");
myList = (ListView) findViewById(R.id. restDealListView);
new LoadDeals().execute();
}
/**
* Background Async Task to Load all deals by making
* HTTP Request
* */
class LoadDeals extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DealsListActivity.this);
pDialog.setMessage("Loading Restaurant Deals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.v("id", id);
params.add(new BasicNameValuePair("id", id));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
// check log cat for JSON string from URL
Log.v("restaurantDealsJSON: ", json.toString());
// return json as string to using in the user interface
return json.toString();
}
#Override
protected void onPostExecute(final String jsonStr) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into listview
* */
try {
json = new JSONObject(jsonStr);
} catch (JSONException e1) {
// print error message to log
e1.printStackTrace();
error("There are no Deals");
}
try {
// Checking for SUCCES TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// restaurant found
// Getting Array of restaurant
restaurantDealsData = json.getJSONArray(TAG_DEALS);
displayDeals(restaurantDealsData.toString());
} else {
error("There is no Deals available!");
}
} catch (JSONException e) {
error("There has been an error please try again!");
e.printStackTrace();
}
}
});
}
}
public void error(String error) {
// Log.v("ERROR", "2");
AlertDialog.Builder builder = new AlertDialog.Builder(
DealsListActivity.this);
// Log.v("ERROR", "3");
builder.setTitle("Error");
builder.setMessage(error);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Log.v("TEST", "1");
Intent i = new Intent(getApplicationContext(),
TabsViewPagerFragmentActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void displayDeals(String result) {
JSONArray restaurantDealsData = null;
try {
restaurantDealsList.clear();
restaurantDealsData = new JSONArray(result);
dealID = new String[restaurantDealsData.length()];
// looping through all technical data
for (int i = 0; i < restaurantDealsData.length(); i++) {
JSONObject td = restaurantDealsData.getJSONObject(i);
// Storing each json item in variable
String id = td.getString(TAG_ID);
dealID[i] = id;
String name = td.getString(TAG_DEALNAME);
String price = td.getString(TAG_PRICE);
String description = td.getString(TAG_DESCRIPTION);
String restaurantID = td.getString(TAG_RESTID);
String restaurantName = td.getString(TAG_RESTNAME);
String restaurantType = td.getString(TAG_RESTTYPE);
String lat = td.getString(TAG_LAT);
String lng = td.getString(TAG_LNG);
Log.v("lat", lat);
Log.v("lng", lng);
// Creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_DEALNAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_RESTID, restaurantID);
map.put(TAG_RESTNAME, restaurantName);
map.put(TAG_RESTTYPE, restaurantType);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
// adding HashMap to ArrayList
restaurantDealsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
error("Error parsing json");
}
// add to list view
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
restaurantDealsList, R.layout.deals_list_item, new String[] {
TAG_DEALNAME, TAG_RESTNAME, TAG_RESTTYPE }, new int[] {
R.id.dealName, R.id.restaurantName, R.id.type });
// updating listview
myList.setAdapter(adapter);
//handling user click list item
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//start the next activity - Restaurant Details
Intent i = new Intent(getApplicationContext(), DealDetails.class);
i.putExtra("ID", dealID[arg2]);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
}
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 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;
}
}
You should read the input stream using the charset UTF-8 like this:
replace
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
by
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8));
I use this to decode json with japanese inside.
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?
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
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);
}
}
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");