My app supposedly to send a source and a destination as parameters to get the fastest bus route and then send them back as an array.
I want to make a list from a json array using volley. Here is an example of my array output.
{
"arrayrute":[
"Halte LIK",
"Halte Kampoeng Semarang",
"Halte Kaligawe 2",
"Halte Pasar Kobong",
"Halte Kota Lama"
]
}
How am I supposedly to make a list from it? Usually a json array from a database would have it's row name before the variable so I just have to use list.set_id(jsonobject.getString("id")) or list.set_id(jsonobject.optString("id"))
Here's my java code to get the array
private void getData() {
//Creating a string request
asal = spin_dari.getSelectedItem().toString().trim();
tujuan = spin_ke.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIRECTION_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
results = j.getJSONArray("arrayrute");
//Calling method getStudents to get the students from the JSON Array
getdireksi(results);
//dirlist.add(results .toString());
} catch (JSONException e) {
e.printStackTrace();
}
adaptdir.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ASAL,asal);
params.put(KEY_TUJUAN,tujuan);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
dirlist.add(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Please Try with this way. Below is DEMO
String url = "{ \n" +
" \"arrayrute\":[ \n" +
" \"Halte LIK\",\n" +
" \"Halte Kampoeng Semarang\",\n" +
" \"Halte Kaligawe 2\",\n" +
" \"Halte Pasar Kobong\",\n" +
" \"Halte Kota Lama\"\n" +
" ]\n" +
"}";
try {
JSONObject jobject= new JSONObject(url);
JSONArray jarray=jobject.getJSONArray("arrayrute");
for(int k=0;k<jarray.length();k++)
{
String getValue=(jarray.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
Final
private void getdireksi(JSONArray j)
{
//Traversing through all the items in the json array
for(int k=0;k<j.length();k++)
try {
String getValue=(j.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Your getdireksi() method is wrong. Put following code instead of yours.
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
String json = j.getString(i);
//Adding the name of the student to array list
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Related
I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
I am getting data on splash. I have almost 7k data that I am getting from the server. While getting data from the server I am saving it in the local database but the problem is the process is too slow. It almost takes 5 minutes. I want to resolve the problem. Please help.
Code to get data from server and save it into database:
private void productsDetailsApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.PRODUCTS_DETAILS_URL;
pBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("product_response", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.close();
ArrayList<ModelProductDetail> modelProductCodeList = dbHelper.getProductsArticleCode();
Log.e("TAG", "ModelProductDetail:art " + modelProductCodeList.size());
shopDetailsApi();
} catch (Exception e) {
e.printStackTrace();
}
//pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
// pBar.setVisibility(View.GONE);
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Databse Insert Query
//add products data
public void addProductsDetails(ModelProductDetail modelProductDetail) {
SQLiteDatabase productsDb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRODUCT_ID, modelProductDetail.getProduct_id());
values.put(KEY_PRODUCT_NAME_FR, modelProductDetail.getProduct_name_fr());
values.put(KEY_PRODUCT_NAME_NL, modelProductDetail.getProduct_name_nl());
values.put(KEY_PRODUCT_DESC, modelProductDetail.getProduct_desc());
values.put(KEY_PRODUCT_ART, modelProductDetail.getArticle_code());
values.put(KEY_PRODUCT_EAN, modelProductDetail.getEan_code());
values.put(KEY_PRODUCT_MBH, modelProductDetail.getProduct_mbh());
values.put(KEY_PRODUCT_MSRP, modelProductDetail.getProduct_msrp());
values.put(KEY_PRODUCT_SOURCE, modelProductDetail.getProduct_source());
values.put(KEY_COMPANY_ID, modelProductDetail.getCompany_id());
values.put(KEY_COMPANY_NAME, modelProductDetail.getCompany_name());
values.put(KEY_FRANCO_TRADING, modelProductDetail.getFranco_trading_value());
values.put(KEY_FRANCO_PRODUCT, modelProductDetail.getFranco_product_value());
productsDb.insert(TABLE_PRODUCT_DETAILS, null, values);
productsDb.close();
}
You could try wrapping all the inserts inside a transaction e.g. :-
JSONArray jsonArray = response.getJSONArray("data");
dbHelper.getWritableDatabase.beginTransaction(); //<<<<<<<<<< ADDED
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.getWritableDatabase.setTransactionSuccessful(); //<<<<<<<<<< ADDED
dbHelper.getWritableDatabase.endTransaction(); //<<<<<<<<<< ADDED
dbHelper.close();
To use the above you would also have to remove the line
productsDb.close();
From the Insert Query
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})
I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}