I'm trying to show a token from one website on my mobile phone. I'm using the Volley to send a GET request, but I get no response (networkResponse == null). My code is fine because I can connect f.e. to google. I found that maybe the website's response comes after the execution of a program.
How can I slow down the execution or how can I enforce waiting for the response? Or maybe can I do something else? Also, the website that I'm trying to connect works well because I can execute the request using Postman. Any ideas how to resolve it are also appreciated.
My code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.codeC);
TextView textView2 = (TextView) findViewById(R.id.blad);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://ec2-3-15-216-171.us-east-2.compute.amazonaws.com:3000/pairing";
// String url ="https://google.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: " + response.substring(0, 130));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error == null) {
textView2.setText("error1");
return;
}
if (error.networkResponse == null) {
textView2.setText("error2");
return;
}
String body;
//get status code here
final String statusCode = String.valueOf(error.networkResponse.statusCode);
//get response body and parse with appropriate encoding
try {
body = new String(error.networkResponse.data, "UTF-8");
textView2.setText(body);
} catch (UnsupportedEncodingException e) {
// exception
textView2.setText("bbb");
}
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
500000,
1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Related
I'm trying to send a simply JSON request using Volley JsonObjectRequest.
After getting the JSON response, I would like to update a value called valoreConvertito, but the JSON response is null and consequently valoreConvertito remains zero.
private void convertiREST(final Double valoreDaConvertire, String valuta){
final TextView textView = (TextView) findViewById(R.id.text);
RequestQueue queue = Volley.newRequestQueue(this);
String url =COMPLETEURL;
valoreConvertito = 0.0;
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Rest response ", response.toString());
valoreConvertito = response.getJSONObject("quotes").getDouble("valuta");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest response", error.toString());
}
});
queue.add(objectRequest);
}
I've even followed the suggestions in another post (Volley JsonObjectRequest response) but I still got JSON response null.
Using the debugger it seems that the program doesn't enter neither in onResponse nor in ErrorListener.
After adding the row queue.add(objectRequest); I notice in Logcat the HTTP traffic not permitted error and I've solved my issue following Android 8: Cleartext HTTP traffic not permitted post.
I added a progressbar as indeterminate state and put in a class extends asynctask.
In doInBackground method, i added one method (say m_one) with volley-library.
In m_one(), i have called method m_two();.
In m_two(), i have called m_three();.
Now, the problem is, progressbar only works till m_one() executes and then progressbar visibility goes invisible and remaining methods executes in background thread.
How do i keep rotating progressbar until all the methods done receiving data using volley request?
Try this code.
private static final String TAG = "LoginActivity.this";
Button button_login;
Context context;
ProgressBar progressBar;
//some variables for accepting the volley response data
DBUtils dbUtils;
Calendar calendar_2;
public SimpleDateFormat dateFormat;
public SimpleDateFormat timeformat;
Date date;
TreeSet<Integer> idSet;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
button_login = findViewById(R.id.btn_login);
context = getApplicationContext();
progressBar = findViewById(R.id.progress_id_1);
calendar_2 = Calendar.getInstance();
dbUtils = new DBUtils(this);
//clear the db tables on start of app
dbUtils.ClearTables();
date = Calendar.getInstance().getTime();
Log.e(TAG, "\n current time: " + date);
dateFormat = new SimpleDateFormat("dd-MM-yyyy");
idSet = new TreeSet<>();
//Login button click event ********************
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkNetwork();
}
});
}
private void checkNetwork() {
progressBar.setVisibility(View.VISIBLE);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
try {
if (netInfo != null) {
NetworkInfo.State state = conMgr.getActiveNetworkInfo().getState();
if (state == NetworkInfo.State.CONNECTED) {
Log.e(TAG, "nw info: " + netInfo.getExtraInfo());
Log.e(TAG, "Network Connected ");
method1();
Thread.sleep(3000);
} else {
Log.e(TAG, "Network Disconnected");
}
} else if (netInfo == null) {
Log.e(TAG, "Network Not Found !");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// ********************************************
// ********************************************
//to get the response of requested url
public void method1() {
try {
//url without api for login session
URL loginURL = new URL(your url 1);
HttpURLConnection urlconnect = (HttpURLConnection) loginURL.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
/*
Singleton_Volley is the class for volley initialize
you can skip Singleton_Volley class..its correct
*/
// Get a RequestQueue in required page
RequestQueue queue = Singleton_Volley.getInstance(this.getApplicationContext()).
getRequestQueue();
// Request a string response from the provided URL.(my case, url)
StringRequest stringRequest = new StringRequest(Request.Method.POST, "" + loginURL.toString(),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//accept the data from request and set in our views like list,text, etc...
try {
/* your response data stored in variables first and then stored in sqlite you have to consider this strictly, make sure you also have array in response to wait for a while */
method2();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//popup an error message...(Toast)
}
})
} ;
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(queue.add(stringRequest));
} catch(
IOException e)
{
e.printStackTrace();
} catch(
JSONException e)
{
e.printStackTrace();
}
}
public void method2() {
try {
url_2 = new URL(your url 2);
HttpURLConnection urlconnect = (HttpURLConnection)
url_2.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
RequestQueue contactQueue = Singleton_Volley.getInstance(this).
getRequestQueue();
// Request a string response from the provided URL.(in my case, url_2)
StringRequest stringRequest = new StringRequest(Request.Method.GET, "" + url_2.toString(),
new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(String response) {
//accept the data from request and set in our views like list,text, etc...
try {
/*
your response data stored in variables first and then stored in sqlite
you have to consider this strictly
make sure you also have array in response to wait for a while
*/
method3(); //method3() called here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//popup an error messege...(Toast)
Toast.makeText(LoginActivity.this, "" + error, Toast.LENGTH_SHORT).show();
}
})
} ;
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(contactQueue.add(stringRequest));
} catch(Exception e){
e.printStackTrace();
}
}
// ********************************************
// ********************************************
private void method3(){
try{
URL url_3=new URL(your url 3);
HttpURLConnection urlconnect=(HttpURLConnection)url_3.openConnection();
;
//http connection for webpage permission
//type of request get / post...
urlconnect.setRequestMethod("POST");
//allow the post request for user
urlconnect.setDoOutput(true);
RequestQueue stageQueue=Singleton_Volley.getInstance(this).
getRequestQueue();
// Request a string response from the provided URL.(in my case, url_3)
StringRequest stringRequest=new StringRequest(Request.Method.GET,""+url_3.toString(),
new Response.Listener<String>(){
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(String response){
//accept the data from request and set in our views like list,text, etc...
try{
progressBar.setVisibility(View.GONE);
/*
make sure you also have array in response to wait for a while
*/
}catch(Exception ex){
ex.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
//popup an error messege...(Toast)
}
})
};
// Add the request to the RequestQueue.
Singleton_Volley.getInstance(this).addToRequestQueue(stageQueue.add(stringRequest));
}catch(Exception ec){
ec.printStackTrace();
}
startActivity(new Intent(LoginActivity.this,Page2.class));
}
}
}}
Please manage the closing } and it should work.
Hello friends I have following JSON Array response from a web service and I want to read all the data row wise from the Database and display on Android Activity.
[{"id":"2","type":"0","title":"Recruitment at ADANI Port, Mundra","date":"2016-07-01"},{"id":"1","type":"1","title":"Training at DAICT, Gandhinager","date":"2016-07-04"}]
I have implemented following code in onCreate() of an Activity using Volley Library, which doesn't show output and to my knowledge it doesn't call onResponse() method.
public void getNews(){
String url = "http://www.ABCDXYZ.net/tponews.php?tponews=1";
Log.e("URL",url);
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jor = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.e("Resposne", "We have got the response");
JSONObject val = response.getJSONObject(0);
}catch (JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
}
}
);
requestQueue.add(jor);
}
The output is only URL in Log.e("URL",url); // URL: www.ABCXYZ.net/tponews.php?tponews=1
I just want to check whethere the user entered url is valid or not so far what i have tried is HTTPurl connection am getting the result but response time is very slow how to make it speed up let me post my code :
public Boolean Netwrok(String str) {
HttpURLConnection connection = null;
try {
URL myUrl = new URL(str);
connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
InputStream response = connection.getInputStream();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
connection.disconnect();
}
}
This is what am trying now am trying to make it with volley am getting response but don't know how to validate it can anybody helpmeout:
Let me post my volley code:
RequestQueue queue = Volley.newRequestQueue(getContext());
String str_url = getEditText().getText().toString();
str_url = s;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Intent intent = new Intent(getContext(), LoginActivity.class);
getContext().startActivity(intent);
// mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
setDialogMessage("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
can anybody tell any solution for my prob
Android has pre-build Patterns for WEB_URL which you can use as:-
if (Patterns.WEB_URL.matcher(serverURL).matches() == false){
//Invalid
}else{
//valid
//In here you can also put one more check by opening connection to URL and check for HTTP_RESPONSE_OK (200) then url is FINE.
}
try below way, just change code in onErrorResponse method of volley request
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//setDialogMessage("That didn't work!");
// NOT VALID URL
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse.statusCode != 200) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
//code 404: for page not found, you can read about more responce code in link below
}
}
});
more about http status code
I am beginning in my journey in Android development so might be doing this all wrong. I am trying to get a set of data using Volley and display it which is ok.
The next step I need to do is use the data to make further requests.
The first request gets a list of sports teams.
I then want to make a request for each team to get the players.
Ideally what I'd like to do is make the first request and return the JSONobject to be used with another class. I have no idea how i would do this.
teamData.getTeams(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//i want to get this out somehow
JSONObject thing = response;
}//end on response
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
}
});
I'm happy to expand on this if need be.
Volley is enqueuing the request so it fires a request after the older one has returned success or error.
So you can enqueue a new request in the success of the older.
Exemple : in your response of your team request you add a new request as you did JSONObject thing = response;
This is an exemple of mine witch imports multiple projects and then imports each project infos:
public void importProjects() {
Response.Listener<JSONArray> jsonArrayResponseListener;
String url = Globals.getApiBaseUrl() + GET_PROJECTS_URL;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
ArrayList<Project> projects = MyJsonParser.getInstance().parseProjects(response);
if (projects.size() > 0) {
for (Project p : projects) {
importProject(p); //####### HERE IS THE KEY :: this methode is the same of this one. It calls other volley request.#######//
}
}
} catch (Exception e) {
Log.e("SyncRngine", "THIS IS AN ERROR");
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = formatUrl(url, params);
Log.i("URL IMPORT PROJECTS", url);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}
And now the défénition of importProject(Project p) :
public void importProject(final Project project) {
String url = Globals.getApiBaseUrl() + GET_PROJECT_URL;
Response.Listener<JSONArray> jsonArrayResponseListener;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
useProjectInfos(response);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = url + "/" + project.getProjectID();
url = formatUrl(url, params);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}