I am using RecyclerView to display data fetched from DB. It's not working.
GETTING AN ERROR E/Volley: [33049] BasicNetwork.performRequest: Unexpected response code 404.
Need to parse below Response:-
[
{
"code":"23232",
"desc":"ddddjdkdkcn",
"price":[
"price"
]
},
{
"code":"de33fd",
"desc":"ddds",
"price":[
"price"
]
}
]
public class Background {
String url = "http://192.168.0.103/android_fetch.php";
Context context;
ArrayList<Data> arrayList = new ArrayList<>();
public Background(Context context) {
this.context = context;
}
public ArrayList<Data> getList() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
arrayList.add(data);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return arrayList;
}
}
First check your request in Postman . There is some error at back-end php side. After that your parsing method is also wrong .
There is mistake in this line i think .
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
here you try to get all as jsonObject but last price is JSONArray .
Try this way .
#Override
public void onResponse(JSONArray jsonresponse) {
try {
Log.i("get response", "get response" + jsonresponse);
for (int i = 0; i < jsonresponse.length(); i++) {
JSONObject response = jsonresponse.getJSONObject(i);
String code = response.getString("code");
String desc = response.getString("desc");
if (response.getJSONArray("price") != null && response.getJSONArray("price").length() > 0) {
JSONArray priceArray = response.getJSONArray("price");
final int numberOfItemsInResp = priceArray.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
String price = priceArray.getString(j);
}
}
}
} catch (Exception e) {
Common.ProgressDialogDismiss();
e.printStackTrace();
}
}
Related
I am using Volley in my project for handling network requests. Here is a sample JSON my server returns when it has data then fatch otherwise give error
{
"message_status": true,
"data": [
{
"message_id": "88",
"message_text": "hi,",
"message_link": "0",
},
}
{
"message_status": false,
"message": "Message not available!"
}
this is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_msg,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data") && !jsonObject.isNull("data")) {
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("true")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
}
setupListview();
} else {
// get message using error key
String error = "Response : " + success + " = " + message;
Toast.makeText(ChatActivity.this, error, Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(ChatActivity.this, "data not available", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
when data have no value then show no item message but its give server error
Try this:
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray != null || jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
//loading.setVisibility(View.GONE);
}
setupListview();
} else {
// get message using error key
Toast.makeText(ChatActivity.this, "error 1" + message + success, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
I tried doing it multiple times using Volley library.
Link for JSON values: here
My android code to parse the values: here
public class GetUSGSjson extends AppCompatActivity
{
GridView jsonGridView;
ListView jsonListView;
Button jsonGetBtn;
RequestQueue USGSrequestqueue;
String USGSurl = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10";
ArrayList<String> mArrayList;
ArrayList<String>FK;
JsonObjectRequest USGSjsonObjectReq;
JSONObject _properties_;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.json_data);
jsonGridView = (GridView) findViewById(R.id.jsonGridView);
jsonGetBtn = (Button) findViewById(R.id.jsonGetBtn);
USGSrequestqueue = Volley.newRequestQueue(this);
mArrayList = new ArrayList<>();
FK = new ArrayList<>();
jsonGridView.setVisibility(View.GONE);
}
OnCllick of the button
public void USGSgetData(View view)
{
jsonGridView.setVisibility(View.VISIBLE);
USGSjsonObjectReq = new JsonObjectRequest(Request.Method.GET,USGSurl,null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONObject _features_ = response.getJSONObject("features");
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
mArrayList.add(String.valueOf(mag));
mArrayList.add(String.valueOf(time));
mArrayList.add(place);
ArrayAdapter VarrayAdapter = new ArrayAdapter<>(GetUSGSjson.this
,android.R.layout.simple_list_item_1, mArrayList);
jsonGridView.setAdapter(VarrayAdapter);
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(GetUSGSjson.this, "Exception: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(GetUSGSjson.this, "onErrorResponse: "+error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
USGSrequestqueue.add(USGSjsonObjectReq);
}
}
Try this,
try {
JSONArray arr_features=response.getJSONArray("features");
for(int i=0;i<arr_features.length();i++)
{
JSONObject obj=arr_features.getJSONObject(i);
String type=obj.getString("type");
JSONObject obj_properties=obj.getJSONObject("properties");
String mag=obj_properties.getString("mag");
String place=obj_properties.getString("place");
String time=obj_properties.getString("time");
String updated=obj_properties.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
I found this way to solve my own problem
Remember that the "mag" is in double form "place" & "type" are in String form & "time" is a Unix time it's in long form.
try {
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
String type = _properties_.getString("type");
// To add this on to ArrayList.
mArrayList.add("Place: "+place+"\n");
mArrayList.add("\nMagnitude: " + String.valueOf(mag)+"\n");
mArrayList.add("\nTime: " + String.valueOf(newTime)+"\n");
mArrayList.add("\nType: " + type+"\n");
}
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 need execute a Volley request and wait for the response to parse it and return it, but have no idea on how to achieve this.
Can someone help?
here is my code :
public void getWord(){
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (lesMots.get(key) instanceof JSONObject) {
JSONObject obj = (JSONObject) lesMots.get(key);
//Récupération des deux mots, anglais et français
String wordToFind = obj.getString("wordFrench").toUpperCase();
String wordEnglish = obj.getString("wordEnglish").toUpperCase();
//Mots mis dans un array respectif
listOfWordEnglish.add(wordEnglish);
listOfWordFrench.add(wordToFind);
container.removeAllViews();
}
numberOfWord++;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error + "", Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
There is 7 word in each array but when i'm trying to get acess into my initGame function, it said they are empty, i guess it's because volley request is not this fast !
if someone can explain me how to do that
here is my initGame function
`public void initGame() {
win = false;
found = 0;
typed_word.setText("");
image.setBackgroundResource(R.drawable.first);
listOfLetters = new ArrayList<>();
listOfWordFrench = new ArrayList<>();
listOfWordEnglish = new ArrayList<>();
getWord();
for (int i = 0; i < listOfWordEnglish.size(); i++){
System.out.println(i);
String wordEnglish = listOfWordEnglish.get(i);
wordEnglishPendu.setText(wordEnglish);
word = listOfWordFrench.get(i);
for (int x = 0; x < word.length(); x++) {
TextView oneLetter = (TextView) getLayoutInflater().inflate(R.layout.textview, null);
container.addView(oneLetter);
}
}
}`
Since Volley is asynchronous, so the for loop below getWord() will be called before onResponse of your Volley request.
The solution for your issue is to move that for loop into onResponse, there you can place it after the while loop.
Hope it helps!
I can't write class variable from AJAX-JSON callback. It show right info inside callback but when a Query callback finishes, it is set to null. Why?
This is code:
public void asyncJson() {
String url = "myurl";
aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status
{
if (json != null) {
jsonToString(json);
} else {
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
private void jsonToString(JSONObject data) {
JSONArray array = null;
try {
array = data.getJSONArray("listResp");
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);
c.setDate_creation(json_data.getString("date_creation"));
c.setName_user(json_data.getString("name_user"));
list.add(c);//linkedlist
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The variable listContest when callback finishes is null.