Web-Services Android Java - java

now i have a button called activities that when u press on it it gets from database activity name and which class in school did this activity and the images of this activity so am doing something like in server side java part am getting all activites of class a in an arraylist and of class b in an arraylist and class c in an arraylist then i added these 3 arraylists in an arraylist!..and this big arraylist i converted to json but when i receive it in android part there is an error :(
Server side:
public static String constructJS(String tag, boolean status,ArrayList<ArrayList<Activities>> f) {
JSONObject obj = new JSONObject();
try {
for(int i=0;i<f.size();i++){
obj.put("tag", tag);
obj.put("status", new Boolean(status));
String json = new Gson().toJson(f);
obj.put("data",json);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
}
return obj.toString();
}
and here when i print the obj.toString i get the json!!
in android part when i receive it :
Client Side
public void onSuccess(String response) {
// Hide Progress Dialog
// prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
String j = obj.get("data").toString();
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
JSONArray data = new JSONArray(j);
Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < data.length(); i++) {
JSONObject busName = data.getJSONObject(i);
String busPhone = busName.getString("activityname");
String busPhon = busName.getString("activityclass");
Toast.makeText(getApplicationContext(), busPhon, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
i get the error when i debug in this line : JSONArray data = new JSONArray(j);

there is no need to create object of jsonarray
i.e. JSONArray data = new JSONArray(j);
just assign the jsonarray value to JSONArray reference
public void onSuccess(String response) {
// Hide Progress Dialog
// prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
//String j = obj.get("data").toString();
// dont't need to do this
Toast.makeText(getApplicationContext(), j, Toast.LENGTH_LONG).show();
//JSONArray data = new JSONArray(j);
JSONArray data = obj.getJSONArray("data"); //add this line
Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < data.length(); i++) {
JSONObject busName = data.getJSONObject(i);
String busPhone = busName.getString("activityname");
String busPhon = busName.getString("activityclass");
Toast.makeText(getApplicationContext(), busPhon, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}

Related

Populating spinner with custom object .how to set spinner hint in custom object

I am developing one application where one spinner are there I am parsing JSON in the spinner and setting an adapter with the custom object. now I am getting an issue unable to set hint . as in image first country coming to Afghanistan but it should come like " Select Country " as a hint. please help me I am stuck in this from 2 days. thanks in advance.
List mCountryList ;
private void getCountry() {
ApiService countryApi = RetrofitClient.getApiService();
Call<JsonElement> call = countryApi.getCountry();
mCountryList = new ArrayList<>();
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response.isSuccessful()) {
try {
JSONObject object = new JSONObject(response.body().toString());
JSONObject jsonObj = new JSONObject(object.toString());
JSONArray jsonArray = jsonObj.getJSONArray("data");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Country countryList = new Country();
countryList.setId(jsonObject.getInt("id"));
countryList.setName(jsonObject.getString("name"));
countryList.setCode(jsonObject.getString("code"));
mCountryList.add(countryList);
}
ArrayAdapter<Country> arrayAdapter = new ArrayAdapter<Country>(getApplicationContext(),R.layout.spinner_layout, mCountryList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerCountry.setAdapter(arrayAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (response.code() == 401 || response.code() == 500) {
Toast.makeText(CreateAccountActivity.this, "Session Expired", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CreateAccountActivity.this, "Something Went Wrong..!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(CreateAccountActivity.this, "Something Went Wrong..!", Toast.LENGTH_SHORT).show();
}
});
}[enter image description here][1]
One easy way is to create a dummy Country object at beginning and add to array whose name is Select Country and fill other dummy details which you might be needing and while tapping on any form button (assuming you have one) you can check the current selected index and if it is 0 then no country is selected. In that case you can show a Toast.
For example here is your updated try catch block:
try {
JSONObject object = new JSONObject(response.body().toString());
JSONObject jsonObj = new JSONObject(object.toString());
JSONArray jsonArray = jsonObj.getJSONArray("data");
if (jsonArray.length() > 0) {
Country country = new Country();
country.setId(0);
country.setName("Select Country");
country.setCode(0);
mCountryList.add(country);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Country country = new Country();
country.setId(jsonObject.getInt("id"));
country.setName(jsonObject.getString("name"));
country.setCode(jsonObject.getString("code"));
mCountryList.add(country);
}
ArrayAdapter < Country > arrayAdapter = new ArrayAdapter < Country > (getApplicationContext(), R.layout.spinner_layout, country);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerCountry.setAdapter(arrayAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
1st element is your hint and make sure you check the index when you are actually want to take any action i.e. if index is 0 show user a Toast to select a Country.

I have a JSON response and I'm stuck on using it

My json is:
{"status":"ok","result":
{"provider":"instagram","title":"lovely_songs_14u","link":
[{"link_name":"Download
Video","video_link":"https:\/\/scontent.cdninstagram.com\/v\/t50.2886-
16\/71650124_386743795596239_6119869649307488549_n.mp4?_nc_ht=scontent.cdninstagram.com&_nc_cat=111&oe=5D907D5B&oh=36ad5ad325cce7926307dfb730583b70"}]}}
Android Side:
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject obj = new JSONObject(response);
categoryGetSet temp;
JSONArray ja_video = obj.getJSONArray("link");
for (int i = 0; i < ja_video.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_title = jo_data.getString("title");
String txt_link_name = jo_data.getString("link_name");
String txt_image = jo_data.getString("img_link");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_image);
temp.setVideo(txt_video);
categoryGetSets.add(temp);
Log.e("dwnld", txt_link_name);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
But it goes everytime into catch case, please let me know where i am doing it wrong
Your JSON is valid.
Use below code to parse your JSON.
try {
JSONObject obj = new JSONObject(json);
categoryGetSet temp;
JSONObject resultObject = (JSONObject) obj.get("result");
String txt_title = resultObject.getString("title");
String txt_provider = resultObject.getString("provider");
JSONArray ja_video = resultObject.getJSONArray("link");
for (int i = 0; i < ja_video.length(); ++i) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_link_name = jo_data.getString("link_name");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_provider);
temp.setVideo(txt_video);
Log.e("jsonResponse: ", "txt_title" + txt_title);
Log.e("jsonResponse: ", "txt_link_name" + txt_link_name);
Log.e("jsonResponse: ", "txt_provider" + txt_provider);
Log.e("jsonResponse: ", "txt_video" + txt_video);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", e.getLocalizedMessage());
}
Because link array is inside result object but you are trying to get from outer object.so you are getting exception.
Try to parse like this
JSONObject obj = new JSONObject(response);
JSONObject resultObj=obj.getJSONObject("result");
JSONArray ja_video = resultObj.getJSONArray("link");
It's going in catch because you are trying to parse in the wrong way,
You need to pass every JSON object and array sequence by sequence, Bellow is your structure
Main Json Object
result Object
link Array
Sub Object with Data
And another wrong thing is you are trying some key which is not exist
Try Bellow code it will help you
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject mainObject = new JSONObject(response);
JSONObject resultObj=mainObject.getJSONObject("result");
JSONArray linkJsonArrya = resultObj.getJSONArray("link");
categoryGetSet temp;
for (int i = 0; i < linkJsonArrya.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = linkJsonArrya.getJSONObject(i);
if(jo_data.has("title")){
temp.setTitle(jo_data.getString("title"));
}else {
temp.setTitle(jo_data.getString(""));
}
if(jo_data.has("link_name")){
temp.setLinkName(jo_data.getString("link_name"));
}else {
temp.setLinkName(jo_data.getString(""));
}
if(jo_data.has("img_link")){
temp.setImage(jo_data.getString("img_link"));
}else {
temp.setImage(jo_data.getString(""));
}
if(jo_data.has("video_link")){
temp.setVideo(jo_data.getString("video_link"));
}else {
temp.setVideo(jo_data.getString(""));
}
categoryGetSets.add(temp);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}

Issue with a for loop over JSON

I seem to be having an issue looping through a JSONObject
The following loop is within a try catch. I am trying to loop through returned JSON, but it skips
try {
JSONObject jsonObject = new JSONObject(result);
// Extract data from json and store into ArrayList as class objects
for(int i = 0; i < jsonObject.length(); i++){
JSONObject jD = jsonObject.getJSONObject(i).;
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
Response JSON
{"count": 30, "recipes": [{"publisher": "Closet Cooking", "f2f_url": "http://food2fork.com/view/35382", "title": "Jalapeno Popper Grilled Cheese Sandwich", "source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html", "recipe_id": "35382", "image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg", "social_rank": 100.0, "publisher_url": "http://closetcooking.com"}, {"publisher": "The Pioneer Woman",
Code within the onPostExecute.
even with the changes still ignores the inners and moves straight to the catch.
#Override
protected void onPostExecute(String result) {
List<DataRecipes> data = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayRecipe = jsonObject.getJSONArray("recipes");
for(int i = 0; i < jsonArrayRecipe.length(); i++){
JSONObject jD = jsonArrayRecipe.getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
// Setup and Handover data to recyclerview
mRVRecipePrice = findViewById(R.id.jsonText);
mAdapter = new AdapterRecipe(Main_Food.this, data);
mRVRecipePrice.setAdapter(mAdapter);
mRVRecipePrice.setLayoutManager(new LinearLayoutManager(Main_Food.this));
}
You need to access the recipe array first
Try this
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayrecipe = jsonObject .getJSONArray("recipes");
for(int i = 0; i < jsonArrayrecipe .length(); i++){
JSONObject jD = jsonArrayrecipe .getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}

How to get the attribute from jsonarray in json url and display in textview

Hi i am trying to get the json response which has attribute with jsonarray
like (ex: {A:one,B:[{a:one,b:two},{a:two,b:one}]}) i have trying to get
the a:one and b:two values only. But my logcat says error:
RecyclerView: No adapter attached; skipping layout
Json parsing error: Value custom_attributes of type java.lang.String cannot be converted to JSONArray
i want to get this values in textview for my product detail view...
My Coding is :
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
dialog_pro = new ProgressDialog(Product_Detail_Activity.this);
dialog_pro.setMessage("Please wait...");
dialog_pro.setCancelable(false);
dialog_pro.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(BaseURL);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
name = jsonObj.getString("name");
JSONArray items = new JSONArray("custom_attributes");
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String atrr = c.getString("attribute_code");
if(atrr.equalsIgnoreCase("short_description")) {
des = c.getString("value");
}
}
}catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
// pro_name.setText("Json error:" + e.getMessage());
}
});
}
} else {
//Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
// AppController.getPermission().addToRequestQueue(jsonObj);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if (dialog_pro.isShowing())
dialog_pro.dismiss();
pro_name.setText(name);
short_desc.setText(des);
}
}
Being based on your JSON
try {
JSONObject responseObject = new JSONObject(response);
String A= responseObject.getString("A");
JSONArray bArray= responseObject.getJSONArray("B");
for(int i=0;i<bArray.length();i++){
JSONObject innerObject=bArray.getJSONObject(i);
String a= innerObject.getString("a");
String b= innerObject.getString("b");
}
} catch (Exception e) {
e.printStackTrace();
}
In your code you have JSONArray items = new JSONArray("custom_attributes"); should be changed. You should get your custom_attributes array from the jsonObj object using object.getJSONArray().
For your first problem-RecyclerView: No adapter attached; skipping layout->
Just set an empty adapter first, update it as soon as you have the data (this is what works for me)
For your second problem-Json parsing error: Value custom_attributes of type java.lang.String cannot be converted to JSONArray->
The e.g json that you have posted "{A:one,B:[{a:one,b:two},{a:two,b:one}]}"
it is not in valid json format

How extract JSONObject from JSONArray in android

I want to read only the "value" object from this jsonarray
"body":{"und":[{"value":"hi friends!!!","summary":null,"format":null}]}
This is my code:
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONArray("body");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
JSONObject result is the response from the rest server.
body is not array its object, you need to get und out of body as JSONArray first
protected void onPostExecute(final JSONObject result) {
try {
TextView lst2 = (TextView) findViewById(R.id.View2);
JSONArray cast = result.getJSONObject("body").getJSONArray("und");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("value");
lst2.setText(name);
}
} catch (Exception e2) {
Log.v("Error adding article", e2.getMessage());
}
}
Hope it helps

Categories