I'm working on a web service application, I display the data in a listview
At the beginning everything works but when I changed my api nothing is displayed and no error appears , I did not find the problem please !! how can I display my data !!
it's the part of the code !!
private class GetHttpResponse extends AsyncTask<String, Void,
ArrayList<subjects>>
{
public Context context;
String ResultHolder;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected ArrayList<subjects> doInBackground(String... arg0)
{
HttpServicesClass httpServiceObject = new HttpServicesClass(arg0[0]);
ArrayList<subjects> subjectsList = new ArrayList<subjects>();
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
for(int i=0; i<jsonArray.length(); i++)
{
subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
if(valueInteger == jsonObject.getInt("tache_id") )
{
// subjects.nom=jsonObject.getString("nom");
subjects.SubjectName =
jsonObject.getDouble("tarif");
subjects.technicien_id =
jsonObject.getString("technicien_id");
subjectsList.add(subjects);
}}}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}}}
catch (Exception e)
{
// TODO Auto-generated catch block
Log.e("Tech", "exception", e);
}
return subjectsList;
}
and this is my json
[
{
"tache_id": "2",
"technicien_id": "2",
"tarif": "100"
},
{
"tache_id": "3",
"technicien_id": "3",
"tarif": "200"
}]
Most probably there is an exception but your are catching it.Start removing your catch statements one by one until you find the error or put log messages in the catch statements.
When you changed your Api your response structure may be changed.So, Ensure the following steps:
Step1 - Save the response of your Api
Step2 - Your Api's JSON response contain Arrays and Objects.Write your code according to the response.
Related
I am working on a small project using an android for the frontend and laravel for the backend. I have a listview linked to a mysql database. Initially it all worked well. However, when I changed to a new URL, nothing is displayed whatever I do and no error is displayed. How can I fix this? This is my code:
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected ArrayList<subjects> doInBackground(String... arg0)
{
HttpServicesClass httpServiceObject = new
HttpServicesClass(arg0[0]);
ArrayList<subjects> subjectsList = new ArrayList<subjects>();
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
for(int i=0; i<jsonArray.length(); i++)
{
subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
if(valueInteger ==
jsonObject.getInt("tache_id") )
{
subjects.avis =
jsonObject.getDouble("avg_avis_intervention");
subjects.nom=jsonObject.getString("nom");
subjects.SubjectName =
jsonObject.getDouble("tarif");
// subjects.technicien_id =
jsonObject.getString("technicien_id");
subjectsList.add(subjects);
}}}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
catch (Exception e)
{
}
return subjectsList;
}
and my new JSON output
[
{
"nom": "teck",
"tache_id": 2,
"tarif": 100,
"avg_avis_interventions": null
}
]
I am trying to create an Android library which provides AsyncTask operations. I created my AsyncTask as below. However, I don't know how to access library's resources. The context field is set by the activity who uses that library. I used to access the resources by calling getActivity().getResources(). But this AsyncTask's context comes from the project that uses it and I don't know how to access the library's resources. How can I achieve that?
public class CheckBalanceAsyncTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
String json;
JSONObject jsonObject,jsonObjResult;
JSONArray jsonArray;
String message,balance;
ProgressDialog progress;
public CheckBalanceAsyncTask (Context context){
mContext = context;
//progress = new ProgressDialog(mContext);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// progress.setCancelable(false);
// progress.setMessage("please wait");//getString(R.string.pleasewait));
// progress.setTitle("waiting");//getString(R.string.loading));
// progress.setIcon(R.drawable.ic);
// progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// progress.setProgress(0);
// progress.setMax(100);
// progress.show();
}
#Override
protected Void doInBackground(Void... params) {
String aliasNo = "";
PackageInfo pinfo = null;
try {
pinfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String versionName = pinfo.versionName;
String cardServiceUrl = "blabla";
Log.e("LOGGGGG", cardServiceUrl);
try {
json = JSONParser.getJSONFromUrl(cardServiceUrl);
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser",
"Error creating json object" + e.toString());
}
jsonArray = jsonObject.getJSONArray("cardlist");
jsonObjResult = jsonObject.getJSONObject("result");
message = jsonObjResult.get("message").toString();
Log.e("MESSAGE", "" + message);
JSONObject row = jsonArray.getJSONObject(0);
balance = row.optString("balance");
}
catch (JSONException e) {
Log.e("json", "doInBackground2");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//progress.dismiss();
try {
if (jsonObjResult.get("message").toString()
.equalsIgnoreCase("ok")) {
Toast.makeText(mContext, balance+" TL", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ressources are automatically merged with the main application then, no need to do something specific to access string, drawable, layout, etc...
getActivity().getResources() will work fine.
i have to implement json data in my application. but i can't get it how to fetch data from server. i am using ION library.
{
"search": [{
"id": "5454003",
"description": "Larger Than Life",
"url": "http://audiojungle.net/item/larger-than-life/5454003",
"type": "item",
"sales": "1469",
"rating": "5",
"item_info": {
"id": "5454003",
"item": "Larger Than Life",
"url": "http://audiojungle.net/item/larger-than-life/5454003",
"user": "pinkzebra",
"thumbnail": "https://0.s3.envato.com/files/67162834/upbeatsongwinner2.jpg",
"sales": "1469",
"rating": "5",
"rating_decimal": "4.96",
"cost": "18.00",
"preview_type": "audio",
"preview_url": "https://0.s3.envato.com/files/94250640/preview.mp3",
"length": "2:35"
}
} ] }
this is my json data. i want to display in my application data like "cost" , "user" ect. but i didn't get it. ion code is here,
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asJsonObject().setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception arg0, JsonObject data) {
// TODO Auto-generated method stub
}
});
so if anybody knows then please help me. thank you in advance.
EDIT: The first info that you posted was has some misleading information, i checked the answer that you posted and i have a working code for you,
code:
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
parseJson(new JSONObject(result));
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
To parse the response data:
private void parseJson(JSONObject result) {
try {
JSONArray jsonArray = result.getJSONArray("search");
for(int a=0;a<jsonArray.length();a++){
System.out.println(jsonArray.getJSONObject(a).getString("id"));
System.out.println(jsonArray.getJSONObject(a).getString("description"));
System.out.println(jsonArray.getJSONObject(a).getString("url"));
System.out.println(jsonArray.getJSONObject(a).getString("type"));
System.out.println(jsonArray.getJSONObject(a).getString("sales"));
System.out.println(jsonArray.getJSONObject(a).getString("rating"));
// JSON data with in JSONObject "item_info"
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("id"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("item"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("url"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("user"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("thumbnail"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("sales"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("rating"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("rating_decimal"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("cost"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("preview_type"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("preview_url"));
System.out.println(jsonArray.getJSONObject(a).getJSONObject("item_info").getString("length"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Remember to use JSONArray(org.json.JSONArray) and JSONObject(org.json.JSONObject) form the org.json libary not JsonArray(com.google.gson.JsonArray;) or JsonObject(com.google.gson.JsonObject) from the com.google.gson library, it get things mess up;
To make things easy paste response here http://json.parser.online.fr/ to see which one is a jsonobject or array
Process :
JsonArray searchArray = getJsonArray("search");
JsonObject index_0_Object= searchArray.getJsonObject("index_0");
JsonObject infoObject = index_0_Object.getJsonObject("item_info");
String id = infoObject.getString("id");
System.out.pritnln(id);
Edited :
first : you have to find "search" array , after it use indexing to get its object , so now you have JsonObject , from it get "item_info" object , from there you can find "id" object .
> yes i got it...
Ion.with(this)
.load("http://marketplace.envato.com/api/edge/search:audiojungle,,happy.json")
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception arg0, String data) {
// TODO Auto-generated method stub
try {
JSONObject jObject = new JSONObject(data);
JSONArray jArray = jObject.getJSONArray("search");
for ( int i = 0 ; i < jArray.size() ; i++ )
{
JSONObject jObject_0 = jArray.getJSONObject(i);
JSONObject jObj = jObject_0.getJSONObject("id");
Log.e("id : ",id+"");
}
//JSONObject jObject_0 = jArray.getJSONObject(1);
//JSONObject jObj = jObject_0.getJSONObject("item_info");
//cost.setText(jObj.getString("cost"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
> but this returns only one value. i want to multiple value according to array list.
check your logs .
I am trying to pass a string array to my adapter. My problem is i initialized globally and try to create string array in my asynchronous task below. But i am getting as null. Below is my code. Actually in this example they taking it from resource folders bu i want it from my json response. Any help is appreciated.
String[] mString;
public ActionsAdapter(Context context) {
mInflater = LayoutInflater.from(context);
session = new SessionManager(context);
final Resources res = context.getResources();
new ConnectAppMenu(context).execute();
// mTitles = res.getStringArray(R.array.actions_names);
// mUrls = res.getStringArray(R.array.actions_links);
// mIcons = res.obtainTypedArray(R.array.actions_icons);
System.out.println("Menus"+ mString);
}
public class ConnectAppMenu extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
private final Context context;
public ConnectAppMenu(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// UI work allowed here
dialog = new ProgressDialog(context);
// setup your dialog here
dialog.setMessage("Connecting....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
String returnConnect = doConnectAppMenu();
return returnConnect;
}
public String doConnectAppMenu() {
HashMap<String, String> user = session.getUserDetails();
String client_url = user.get(SessionManager.KEY_CLIENT);
// if(connection) {
HttpParams connectionParameters = new BasicHttpParams();
int timeoutConnection = 8000;
HttpConnectionParams.setConnectionTimeout(connectionParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(connectionParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(connectionParameters);
HttpPost httpPost = new HttpPost(client_url+"/api/common/app_menu");
JSONObject json = new JSONObject();
try{
json.put("data", 1);
json.put("versionid", 1);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
//Execute HTTP post request
appmenu_res = httpClient.execute(httpPost);
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
appmenu_result = appmenu_obj.toString();
}
catch(JSONException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return appmenu_result;
}
#Override
public void onPostExecute(String result) {
int status_code = appmenu_res.getStatusLine().getStatusCode();
if (status_code == 200) {
dialog.dismiss();
try {
menuObject = new JSONObject(result);
JSONArray names= menuObject.names();
JSONArray values = menuObject.toJSONArray(names);
for (int i = 0; i< values.length(); i++) {
JSONObject json2 = (JSONObject) values.get(i);
int menu_id = json2.getInt("menu_id");
if (menu_id > 0) {
if (json2.has("menu_name")) {
menu_list = json2.get("menu_name").toString();
mString = new String[] { menu_list };
//mUrls = menu_list.length();
}
}
}
System.out.println("Json Menu" + Arrays.toString(mString));
/*Iterator<String> iter = menuObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = menuObject.get(key);
//System.out.println("Hai" +value);
System.out.println("Post Execute" + value);
} catch (JSONException e) {
// Something went wrong!
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//dialog.dismiss();
}
}
}
well first of all if you're looking for the JSON object as a String don't do what you did here:
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
I'd suggest doing the following:
String Json = EntityUtils.toString(appmenu_res.getEntity());
return Json;
Now if you want to do the processing of your JSON on the UI thread (as you seem to want to based on the return type being a string) this should work. However this method is not recommended since the Json will need to be processed into objects which will take time and clog the UI thread.
A better solution would be to serialize your Json on the background thread and then pass the serialized object back to the main thread to update the UI.
If you have many types I would suggest using generics. I've already built a Loader which can do what you want if you want here. You will need touse the GSON library and build appropriate seralizers. Also working with the loader class is different to working with the AsyncTaskClass so please read the documentation here
Edit
Ok so what you want to do if you want get the Activity to have a callback from the AsyncTask is to do something along the lines of:
public class MyActivity extends Activity implements AsyncTaskCallback
where AsyncTaskCallback looks something like :
public interface AsyncTaskCallback
{
public processData(Object responseObject);
}
now in your onPostExecute code you'll need to do somehting like:
#Override
protected void onPostExecute(Object r){
if (r != null) {
l.processData(data);
}
}
and add the following function to your async task
public void addAsyncTaskListener (final AsyncTaskListener l){
mCallback = l;
}
and then finally add the listner and process the data as required in the Activity in the function processData function that the interface forces your activity to implement.
Instead of using String[] you can use ArrayList for Setting list in adaptor.
After a few weeks of trying numerous examples found here and it seems throughout the web, I'm stumped. I can retrieve the desired search results from Google Shopping just fine:
{ "items": [ { "product": {
"title": "The Doctor's BrushPicks Toothpicks 250 Pack",
"brand": "The Doctor's" } } ] }
My problem is that I have the data sitting in a string, how do I extract the two values (title,brand) in order to use them elsewhere in the program?
Here is the class in question:
public class HttpExample extends Activity {
TextView httpStuff;
DefaultHttpClient client;
JSONObject json;
final static String URL = "https://www.googleapis.com/shopping/search...";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("items");
}
public JSONObject products(String upc) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(upc);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject timeline = new JSONObject(data);
return timeline;
} else {
Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String upc = ExportMenuActivity.upc;
json = products(upc);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
httpStuff.setText(result);
}
}
}
The output of httpStuff.setText(result):
[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}]
A solution that'd work on all versions of Android would look something like this:
JSONObject products = products(jsonStr);
JSONArray itemArray = products.getJSONArray("items");
for(int i=0; i<itemArray.length(); i++) {
if(itemArray.isNull(i) == false) {
JSONObject item = itemArray.getJSONObject(i);
String title = item.getString("title");
String brand = item.getString("brand");
}
}
JsonReader is nice, but is only available in API 10 and up. So it might or might not work for you.
You should use a JsonReader for reading the json string. Its very easy and well documented with very good sample.. here