I am just starting to learn java and Android , Ia m trying to parse json data and apply the data to recyclerview but i am not able to do it. here is my code
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
And here is my JSON Response
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
Please someone give a brief explanation of the correct code. it would be very helpful. Thanks
rvAdapter = new RvAdapter(getActivity());
recyclerview.setAdapter(rvAdapterHScode);
rvAdapter.set(responce.getcodes());
recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 3));
then in adapter
accept the set values
or
call your response inside the recyclerview adapter
like this way
your jsonArray should be in following way:
{
"jArray": [{
"id": "118",
"garment_color": "Blue",
"garment_name": "skjhkds",
"garment_price": "232"
},
{
"id": "119",
"garment_color": "hjsadjjs",
"garment_name": "sdasd",
"garment_price": "23478"
}
]
}
then read that json like this way:
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("jArray");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
try {
GetDataAdapter2.setImageTitleNamee(c.getString("garment_name"));
GetDataAdapter2.setMrp_price(c.getString("garment_price"));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
Related
I have this URL with a JSON in it I would like to make a JSONObject of it and store the value in a variable named previousID.
[ { "id": "179" } ]
How can I create that JSONObject and get that int value out of it?
I can't make it work with the JSONObject so I tried it with a JSONArray but for some reason I always get the value 0 as return value.
private int getPreviousID(Context context){
RequestQueue queue = Volley.newRequestQueue(context);
final int[] info = new int[1];
JsonArrayRequest totalListRequest = new JsonArrayRequest(Request.Method.GET, GET_LAST_URL,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length(); ++i) {
JSONObject o = null;
info[0] = 0;
try {
info[0] += response.getJSONObject(i).getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Unable to communicate with the server", Toast.LENGTH_LONG).show();
}
});
queue.add(totalListRequest);
return info[0];
}
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.
JSON format:
[
{
"nsrId": "1018038",
"koordinatLatLng": [
59.6908,
9.04228
],
"navn": "Gransherad barnehage",
"fylkesnummer": "08",
"kommunenummer": "0807",
"alder": "1 - 5",
"eierform": "Kommunal",
"antallBarn": 26
},
{
"nsrId": "1012983",
"koordinatLatLng": [
59.5763,
9.19806
],
"navn": "Trolldalen Gårdsbarnehage",
"fylkesnummer": "08",
"kommunenummer": "0807",
"alder": "1 - 5",
"eierform": "Privat",
"antallBarn": 24
},
etc...
My code:
spinner = findViewById(R.id.barneHage_Spinner);
hentJSON();
}
private void hentJSON() {
showSimplProgressDialog(this, "loading...", "Henter Json", false);
StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
barnehageArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("navn");
for (int i = 0; i < dataArray.length(); i++) {
Barnehage model = new Barnehage();
JSONObject dataobj = dataArray.getJSONObject(i);
model.setNavn(dataobj.getString("navn"));
// model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));
barnehageArrayList.add(model);
}
for (int i = 0; i < barnehageArrayList.size(); i++) {
names.add(barnehageArrayList.get(i).getNavn());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
spinner.setAdapter(spinnerArrayAdapter);
removeSimpleProgressDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
I expect the output to be a spinner with the only values showing
1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..
etc
I think you were wrong when getting JSON array by JSONArray dataArray = obj.getJSONArray("navn").
Let try using this code:
#Override
public void onResponse (String response) {
try {
JSONArray dataArray = new JSONArray(response);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataobj = dataArray.getJSONObject(i);
You have to add an item at zero position of your list
barnehageArrayList.add(0,new MODELCLASS("Select option"))
And add below code to populate your Spinner
SPINNER_NAME.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != 0) {
} else {
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
here is main activity code .
and when i open app sometime it shows data and sometimes not. and it i found that arraylist list null sometime .
here is main activity code .
and when i open app sometime it shows data and sometimes not. and it i found that arraylist list null sometime .
volley
StringRequest r = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("code",response);
JSONObject obj = null;
try {
obj = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray gallary = null;
try {
gallary = obj.getJSONArray("arr");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < gallary.length(); i++) {
JSONObject a = null;
try {
a = gallary.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
String PostId = null;
try {
PostId = a.getString("Name");
list.add(new dataclass("mmmmm"));
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("List", String.valueOf(list));
goahed();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
}
});
RequestQueue queue= Volley.newRequestQueue(this);
queue.add(r);
RecyclerView rv=findViewById(R.id.demolist);
list.add(new dataclass("please"));
for (Integer j=0;j < list.size();j++){
}
// Creating Adapter Object
listdemoAdpter adapter=new listdemoAdpter(this,list);
//Set layout Manager
rv.setLayoutManager(new LinearLayoutManager(this));
// set Adapter
rv.setAdapter(adapter);
i use volley library for api call
thanks in advance
if(list.isempty()){
RecyclerView rv=findViewById(R.id.demolist);
list.add(new dataclass("please"));
for (Integer j=0;j < list.size();j++){
}
// Creating Adapter Object
listdemoAdpter adapter=new listdemoAdpter(this,list);
//Set layout Manager
rv.setLayoutManager(new LinearLayoutManager(this));
// set Adapter
rv.setAdapter(adapter);
}else{
//logic when list is empty and request again in volly
}
I'm trying to handle this null exception in RecyclerView from PHP URL. I want it to show a Toast message if a null exception occurs: No Result Found.
null exception:
Code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
EDIT
Create one method to validate your JSONObject
public boolean isJSONValid(String jsonStr) {
try {
new JSONObject(jsonStr);
} catch (JSONException ex) {
return false;
}
return true;
}
Try to edit following code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (isJSONValid(response)) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
// your Toast Message
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
Returning early ordinary is way to go ...
therefore I'd compare to the known String value of null, in case of no results,
before checking if it possibly could be valid JSON (which can already be out-ruled):
if(! response.equals("null")) {
try ...
}
or improve statement e.printStackTrace() and handle that JSONException accordingly:
try {
...
} catch(JSONException e) {
if(response.equals("null")) {
/* assume no results */
} else {
e.printStackTrace();
}
}
While having access to the PHP code ...better always return a parse-able JSON response:
header("Content-Type: application/json");
die(json_encode((object) array(
"success" => false,
"error" => "no results"
)));
... when the client expects application/json instead of text/plain.
I keep trying to look up and find a solution for my problem.
I am populating a Spinner with json data from a URL, the Json data is nameless and I'm trying to get the data into an ArrayList so I can populate the Spinner.
Whenever I debug I can see that it skips my onResponse() method after making either StringRequest or JSONArrayRequest, Please look at my code and see what am I doing wrong
yearsp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(ySelect)
{
selectedYear = yearsp.getSelectedItem().toString();
URL1 = URL + "/" + selectedYear;
loadSpinnerDataMake();
adapterMake.clear();
adapterMake.addAll(makesName);
}
else
ySelect = true;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
here is my json data from URL1
[{"make":"Acura"},{"make":"Aston Martin"},{"make":"Audi"},{"make":"Bentley"},{"make":"BMW"},{"make":"Bugatti"},{"make":"Buick"},{"make":"Cadillac"},{"make":"Chevrolet"},{"make":"Chrysler"}]
Try below function and let me know.
private void parseJSONDataMAke() {
try {
JSONArray dataMakeArray = new JSONArray("[{\"make\":\"Acura\"},{\"make\":\"Aston Martin\"},{\"make\":\"Audi\"},{\"make\":\"Bentley\"},{\"make\":\"BMW\"},{\"make\":\"Bugatti\"},{\"make\":\"Buick\"},{\"make\":\"Cadillac\"},{\"make\":\"Chevrolet\"},{\"make\":\"Chrysler\"}]");
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < dataMakeArray.length(); i++) {
JSONObject jsonObject = dataMakeArray.getJSONObject(i);
stringArrayList.add(jsonObject.getString("make"));
}
//Please set "stringArrayList" array into spinner
} catch (JSONException e) {
e.printStackTrace();
}
}
Your request is async hence you need to notify your spinner adapter when you get response like this.
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
makesName.clear(); //To avoid duplication of data
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
adapterMake.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
You are not notifying adapter that's why you didn't get your result.
I fixed my issue thank you everyone who has helped but i figured it out by removing where im adding the arraylist to the adapter and placing it in the OnResponse
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = response;
for (int x = 0; x < jsonArray.length(); x++) {
JSONObject obMake = jsonArray.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
adapterMake.clear();
adapterMake.addAll(makesName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}