Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I parsed JSON response using Volley library as done in this video. But I am getting an error. The error is:
E/VOLLEY: ERROR
Can somebody help me, please? I don't know what the problem is.
EDIT: Added code
package com.example.hello.Project;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Activity1 extends Activity {
Button start;
TextView textView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
start = (Button) findViewById(R.id.btn);
textView = (TextView) findViewById(R.id.textView2);
requestQueue = Volley.newRequestQueue(this);
start.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://example.com/abc.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("abc");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject student = jsonArray.getJSONObject(i);
String a= student.getString("a");
String b= student.getString("b");
String c= student.getString("c");
String d= student.getString("d");
textView.append(a+" \n"+b+" \n"+c+" \n "+d+" \n");
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
});
}
}
This is the code.
This isn't going to fix your problem, but it will tell you what's going wrong.
Change
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
to
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}
This way it will actually say what the error is, not just "ERROR".
The conclusion was that the sample JSON was invalid and therefore not being read in correctly.
Further to #TJ_'s answer you also need to add comma's between each attribute.
You had (which is invalid):
{
"buli1617sp": [
{
name: "Embolo"
vereine: "Von Basel zu Schalke"
geld: "29 Mio Euro"
datum: "01.08.2016"
},
{
name: "Coke"
vereine: "Von Sevilla zu Schalke"
geld: "4 Mio Euro"
datum: "02.08.2016"
},
{
name: "Bentaleb"
vereine: "Von Basel zu Schalke"
geld: "Leihe mit Kaufoption über 19 Mio Euro"
datum: "03.08.2016"
}
]
}
The correct JSON:
{
"buli1617sp": [
{
"name": "Embolo",
"vereine": "Von Basel zu Schalke",
"geld": "29 Mio Euro",
"datum": "01.08.2016"
},
{
"name": "Coke",
"vereine": "Von Sevilla zu Schalke",
"geld": "4 Mio Euro",
"datum": "02.08.2016"
},
{
"name": "Bentaleb",
"vereine": "Von Basel zu Schalke",
"geld": "Leihe mit Kaufoption über 19 Mio Euro",
"datum": "03.08.2016"
}
]
}
When working with JSON I suggest using an online JSON parser such as this to verify the JSON is correctly formatted.
Related
I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");
I want to get the results about imei adresses after my inquiry on the inquiry site. The site has token input during the query and I can get this token as follows. But when i run the second volley queue i soppose the token changes and the result doesn't come. How can I solve this problem. The site that i questioned the imei adress and my codes are below.
package com.myapp.query;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
public class imeiSorgulama extends AppCompatActivity {
StringRequest stringRequest;
RequestQueue queue;
String token, tag, value, tag2, value2, result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei_sorgulama);
queue = Volley.newRequestQueue(this);
final String url = "https://www.turkiye.gov.tr/imei-sorgulama";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tag = "<input type=\"hidden\" name=\"token\" value=\"";
value = response.substring(response.indexOf(tag) + tag.length());
token = value.substring(0, value.indexOf("\""));
try {
token = URLEncoder.encode(token,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
imeiQuery();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
}
private void imeiQuery() {
final String url = "https://www.turkiye.gov.tr/imei-sorgulama?submit";
stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
tag2 = "<dl class=\"compact\">";
value2 = response.substring(response.indexOf(tag2) + tag2.length());
result = value2.substring(0, value2.indexOf("</dl>"));
Toast.makeText(imeiSorgulama.this, result+"", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtImei", "545454545454545");
params.put("token=", token);
return params;
}
};
queue.add(stringRequest);
}
}
I have a serious problem.
I have a small app for a restaurant to manage the creation of orders, update, and so. Waiters use an android tablet to serve to the customers.
The thing is that since a week or so, I realized that tickets tend to duplicate items. After some research and diving into the logs, I realized that many times, when I call an AsyncTask to make a request to the server, it doesn't send ONE request, it sends several requests instead.
For that reason, if I call the "addItemToOrder" service four times, it will add four items instead of just one.
Here is my code. This is a "generic GET Async Task" that I call. It has an url, it may or not has some parameters, and it just creates a volley request that sends to the server. As you can see, it has 0 retries and, before you can ask, I just made sure that this AT is not being called more than once:
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.FunctionsHelper;
abstract class GenericGetAsyncTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "DEBUG GenericGetAT";
Handler h;
WeakReference<Context> context;
String auxURL;
HashMap<String, String> postParams;
String query;
GenericGetAsyncTask(WeakReference<Context> context, Handler h) {
this.auxURL = "";
this.context = context;
this.h = h;
this.postParams = new HashMap<>();
this.query = "";
}
#Override
protected Void doInBackground(final Void... params) {
if (!FunctionsHelper.isConnected(context.get())) {
h.sendEmptyMessage(ErrorHelper.HANDLER_NO_INTERNET_ERROR);
Bugfender.d(TAG, "No internet connection");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_NO_INTERNET_ERROR, TAG);
return null;
}
String urlParcial = Constants.getUrl(context.get());
if (urlParcial.equals("")) {
h.sendEmptyMessage(ErrorHelper.HANDLER_FALTA_URL);
Bugfender.d(TAG, "Falta url");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_URL_INCORRECTA, TAG);
return null;
}
int metodo;
String url;
if (query == null || query.equals("")) {
url = urlParcial + this.auxURL;
metodo = Request.Method.POST;
} else {
url = urlParcial + this.auxURL + "?" + this.query;
metodo = Request.Method.GET;
}
Bugfender.d(TAG, "url -> " + url);
final RequestQueue queue = Volley.newRequestQueue(context.get());
final StringRequest request = new StringRequest(metodo, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
onResultRetrieved(response);
} catch (JSONException e) {
Bugfender.d(TAG, "Hubo un error de json en onResponse -> " + e.toString());
h.sendEmptyMessage(ErrorHelper.HANDLER_RESPUESTA_INCORRECTA);
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_JSON, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Bugfender.d(TAG, "Error recibido del servidor -> " + error.toString());
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_RESPUESTA_INCORRECTA, TAG);
Toast.makeText(context.get(), "Error realizando llamada http -> " + error.toString(), Toast.LENGTH_SHORT).show();
h.sendEmptyMessage(ErrorHelper.HANDLER_ERROR);
}
}) {
#Override
protected Map<String, String> getParams() {
return postParams;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(2000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
return null;
}
protected abstract void onResultRetrieved(String result) throws JSONException;
}
After that, then I just have to inherit from this generic AT with just some bit of code to make a simple request, just as you can see here in this "UpdateTicketAT":
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.Handler;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.Functions;
public class UpdateTicketAsyncTask extends GenericGetAsyncTask {
private static final String TAG = "DEBUG UpdateTicketAT";
public UpdateTicketAsyncTask(WeakReference<Context> context, Handler h, String json) {
super(context, h);
this.auxURL = "actualizar_ticket.php";
this.postParams.put("ticket", json);
Bugfender.d(TAG, "Ticket que vamos a enviar -> " + json);
}
#Override
protected void onResultRetrieved(String response) throws JSONException {
Bugfender.d(TAG, "Respuesta obtenida del servidor -> " + response);
JSONObject result = new JSONObject(response);
int codigo = result.getInt("codigo");
if (codigo == 0) {
h.sendEmptyMessage(Constants.handlerOk);
Bugfender.d(TAG, "Ticket actualizado correctamente");
} else {
h.sendEmptyMessage(Constants.handlerError);
ErrorHelper.mostrarError(context.get(), codigo, TAG);
}
}
}
I can't find out what is happening here. Am I doing something wrong?
One important thing is that the calls to the server may not be all made in a row. I mean, I make a request, I get the response, and maybe a minute or two later, the request is made again!
I just can be aware of this by looking into the server logs..
I don't know what's happening here..
Anyway, thanks in advance!
I can see two ways to answer your question or not:
First: i don`t like your "0" in your DefaultRetryPolicy line, try to put some like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
The first parameter is timeout, second is max retries (yes i know, you know that but check that is 1) and the last one is DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ( again i know, blah blah, but check that is 1.0f) or put literal.
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
1, 1.0f));
Second: Can you only set more time in your time out.
I hope this help you.
I am new to the android studio and I am trying to make my simple app get JSON data from URL i.e fetch JSON data from the server with Volley in Android Studio. When I debug on my device, it works fine but don't show any data and I am sure there is something wrong
my code:
package imo.meteoiraq;
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView nameText,descriptionText,fbUrlText,youtubeUrlTxt;
int humidity;
int wind_speed;
int temperature;
String url="/stationlookupstation=I1410&units=metric&v=2.0&format=json";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq= Volley.newRequestQueue(this);
nameText= (TextView) findViewById(R.id.tempText);
descriptionText = (TextView) findViewById(R.id.wind_speed);
fbUrlText = (TextView) findViewById(R.id.humidity);
sendjsonrequest();
}
public void sendjsonrequest(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
temperature = response.getInt("temperature");
wind_speed= response.getInt("wind_speed");
humidity= response.getInt("type");
nameText.setText(temperature);
descriptionText.setText(humidity);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
}
my data json:
{
"stations": {
"I1410": {
"updated": 1499668936,
"ageh": 0,
"agem": 0,
"ages": 58,
"type": "PWS",
"wind_dir_degrees": 315,
"wind_speed": 6.1,
"wind_gust_speed": 11.1,
"humidity": 10,
"temperature": 40.5,
"precip_rate": null,
"precip_today": 0,
"pressure": 1002.26,
"dewpoint": null,
"windchill": null
}
}
}
first get JsonObject stations and I1410 , then use ages = I1410JO.getInt("ages");
JSONObject stationsJO = response.getJSONObject("stations");
JSONObject I1410JO = stationsJO.getJSONObject("I1410");
int ages = I1410JO.getInt("ages");
There are 2 issues in the program.
1st issue already explained by Rasoul Miri about accessing stationsJO JSON object and then I1410JO JSON object.
2nd issue is that temperature is not of integer format but of double format and so you need to use I1410JO.getDouble("temperature") to get it.
There is error in your Url and you have not parsed response correctly.Send Correct Url with proper(GET or POST) method.
I use the JSONObject forecast = new JSONObject(response.body().string()) to get the weather information, but android monitor always show "org.json.JSONException: End of input at character 0 of ".
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Debug;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isconnected()){
String url = "https://api.forecast.io/forecast/2d0f15adaeff2c8e1343201418843890/37.8267,-122.423";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.d(TAG, response.body().string());
String a=response.body().string();
try {
JSONObject forecast = new JSONObject(a);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
alertUserAboutError();
}
}
});
}
else{
Toast.makeText(MainActivity.this,"LOST CONNECTION",Toast.LENGTH_SHORT).show();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private boolean isconnected() {
ConnectivityManager cm =
(ConnectivityManager)MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getSupportFragmentManager(), "error");
}
}
I use the Log.d(TAG, response.body().string()) to test it is a string, but when in JSONObject forecast = new JSONObject(response.body().string()), it will not work.
For some weird reason if you use .string() >1 time, response turns out to be empty. Try to use it only once when parsing Retrofit response.
Someone, who knows why it happens like this, please improve my answer.
Answer : Response object should of Generic type - ResponseBody.
See below Correct code for reference.
Now response.body() method will return object ResponseBody
i.e.
ResponseBody rb = response.body();
rb.string();
Here ResponseBody have method string() which returns String object but internally string() method calls Util.closeQuietly(source); which makes response empty once method string() gets called.
Just remove Log.d(TAG, response.body().string()); and follow below code.
Reference - okhttp3.ResponseBody.java
error : org.json.JSONException: End of input at character 0
Correct code :
#Override
public void onResponse(Call call, Response<ResponseBody> response) throws IOException {
if (response.isSuccessful()) {
String remoteResponse=response.body().string();
Log.d(TAG, remoteResponse);
try {
JSONObject forecast = new JSONObject(remoteResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Sometimes the probleme is th URL, if your website forces HTTPS, you have to make sure that you are using an HTTPS URL in your APP, and vice-versa if your website doesn't support HTTPS, you have to use an HTTP URL.
I have solved this problem after moving the "String a=response.body().string()" before "if (response.isSuccessful())".