Timeout error on real android device with volley? - java

I am beginner in android. i have a problem in volley request using xamp server for request when i use real device then it give me timeout error and added retry policy but still timeout error.
public class MainActivity extends AppCompatActivity {
private TextView serverResponse;
private Button requestBtn;
private String url = "http://192.168.3.104/helloworld.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverResponse = findViewById(R.id.serverResponse);
requestBtn = findViewById(R.id.serverBtn);
final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
serverResponse.setText(response);
Log.e("Volley MainActivity " , response.toString());
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley MainActivity " , error.toString());
serverResponse.setText(error.toString());
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
3000,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
);
requestQueue.add(stringRequest);
}
});
}
}
E/Volley MainActivity: com.android.volley.TimeoutError

Related

Cant get json from my link with Volley in android studio

Here my code to parse json from my link http://192.168.1.9/androidwebservice/getdata.php in MainActivity.java
public class MainActivity extends Activity {
String urlGetData = "http://192.168.1.9/androidwebservice/getdata.php";
String url = "http://my-json-feed";
String convertedResponse = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData(urlGetData);
}
private void GetData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "LOOIVVVVV", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
}
}
when i run the app with this link , it works. but when i do it with my link http://192.168.1.9/androidwebservice/getdata.php it dont work.(This link i get data from database MySQl and parse to json) And when i check, it's the same.
Here my php file:
<?php
$connect = mysqli_connect("localhost","root","","sinhvien");
mysqli_query($connect,"SET NAMES ");
$query ="SELECT * from student";
$data = mysqli_query($connect,$query);
class SinhVien{
function SinhVien($id,$hoten,$namsinh,$diachi){
$this->ID=$id;
$this->HoTen=$hoten;
$this->NamSinh=$namsinh;
$this->DiaChi=$diachi;
}
}
$mangSV=array();
while($row=mysqli_fetch_assoc($data)){
array_push($mangSV, new SinhVien($row['id'],$row['hoten'],$row['namsinh'],$row['diachi']));
}
echo json_encode($mangSV);
?>

How to call WooCommerce API from android studio using Volley library?

I am new to Android and I am using JAVA and Android studio. I have to use the WooCommerce API to get the list of all orders:
wp-json/wc/v2/orders
Is this possible using the volley library and if yes, how can I call this and get the response (I have my client_id and client_secret)?
Here is my activity page:
public class YourOrders extends AppCompatActivity {
private TextView textViewback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_orders);
getSupportActionBar().hide();
textViewback = (TextView) findViewById(R.id.textViewback);
textViewback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}}
String url = "https://www.example.com/wp-json/wc/v2/orders?consumer_key=123&consumer_secret=abc";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
textViewback.setText("Response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);

how to retrive reponse of volly responserListner outside the volly class

I am having a project for my university. My android app needs to communicate with a server to sent a command and receive some data. I am able to sent and receive data. Problem is when i want to print that data out side the volly class there is no received data available.
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
commandStatus.setText("SERVER DOWN");
error.printStackTrace();
requestQueue.stop();
}
});
requestQueue.add(stringRequest);
commandStatus.setText(returnFromServer);//there is no value here out side the volly class
}
I have to compare the returned value form server for further uses.
Create a ResponseListener object in your class like this:
Response.Listener<String> response = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
};
and then pass the listener to volley:
public void yourMethod(){
....
callApi(response)
....
}
public void callAPI(Response.Listener<String> response) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
response,
new Response.ErrorListener(){...}
}
Implement
public class MainActivity extends Activity{
Response.Listener<String> response = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
returnFromServer =response.toString();
requestQueue.stop();
}
};
private void callAPI(Response.Listener<String> respone) {
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, server_url += "/?data="+ enteredUsername.getText().toString()+","+ enteredPassword.getText().toString()+","+enteredSiteId.getText().toString(),
response,
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
commandStatus.setText("SERVER DOWN");
error.printStackTrace();
requestQueue.stop();
}
});
requestQueue.add(stringRequest);
commandStatus.setText(returnFromServer);//there is no value here out side the volly class
}
}
}
just call the callAPI method everywhere you want, and pass response as a parameter. if the response received from the server, onResponse method in MainActivity called.
another simple way in implemented Response.Listener in the same class you call API and set response parameter in the volley to this.

Expression expected error on Volley requests

I am getting an error called expression expected inside the bracket in this line. Volley.newRequestQueue(MainActivity); . This class is on another activity other than my MainActivity. Here is the snippet of my code:
public void youFunctionForVolleyRequest(final ServerCallbackJava callback) {
RequestQueue queue = Volley.newRequestQueue(MainActivity);
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=22.2913,113.947&destinations=WanChai&mode=driving&key="REMOVED";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(response); // call call back function here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("Volley error json object ", "Error: " + error.getMessage());
}
})
{
#Override
public String getBodyContentType ()
{
return "application/json";
}
};
// Adding request to request queue
queue.add(jsonObjReq);
}
}
As you have created a class inside a activity/fragment, while calling the class you must pass the context of the activity and same pass to this function and replace the RequestQueue queue = Volley.newRequestQueue(MainActivity); with RequestQueue queue = Volley.newRequestQueue(mContext); the declared context inside your class.
You can do it with the help of following code snippet :
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request r = new request(Main2Activity.this);
r.youFunctionForVolleyRequest();
}
});
}
class request{
Context ctx;
public request(Context mContext) {
ctx = mContext;
}
public void youFunctionForVolleyRequest() {
RequestQueue queue = Volley.newRequestQueue(ctx);
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=22.2913,113.947&destinations=WanChai&mode=driving&key=";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// callback.onSuccess(response); // call call back function here
System.out.println("success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("Volley error json object ", "Error: " + error.getMessage());
System.out.println("failed");
}
})
{
#Override
public String getBodyContentType ()
{
return "application/json";
}
};
// Adding request to request queue
queue.add(jsonObjReq);
}
}
}
If your code in Activity.class:
RequestQueue queue = Volley.newRequestQueue(this);//or
RequestQueue queue = Volley.newRequestQueue(Activity.this);//or
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
If your code in Fragment.class:
RequestQueue queue = Volley.newRequestQueue(getContext());//or
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());//or
RequestQueue queue = Volley.newRequestQueue(Fragment.this.getContext());//or
RequestQueue queue = Volley.newRequestQueue(Fragment.this.getApplicationContext());
make global variable in class VolleyRequests
Context context;
and initialize it on constructor
public VolleyRequests(Context mcontext) { this.context= mcontext; }
then use this
RequestQueue queue = Volley.newRequestQueue(context);
when you call it in MainActivity use :
VolleyRequests volleyrequests = new VolleyRequests (this);
Inside that new class constructor, pass the context so that you use it with volley.
public class ClassWithVolley{
private Context context;
public ClassWithVolley(Context context){
this.context = context;
}
// continue

Want to move GET method inside POST, Volley

I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}

Categories

Resources