Can get information from JSON API - android

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

Related

Android Json unicode parsin

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.

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
}

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

async task issue in json format

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");

Categories

Resources