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);
Related
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);
?>
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
i'm trying to get the data from the database to fill the activity with them but i'm not getting anything this is the db code i have 2 Textvies 1 image view i'm trying to fill with the data i'm new to mobile programming so need help:
public void gettypedet(final int tid, final TextView ttitle, final ImageView timg, final TextView desc) {
String url = "http://192.168.0.114/mobileshop/product_typrbyid.php?id="+tid;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a json response from the provided URL.
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject prt) {
try {
String type=prt.getString("type");
int imgname=Integer.parseInt(prt.getString("imagename"));
String des=prt.getString("description");
ttitle.setText(type);
timg.setImageResource(imgname);
desc.setText(des);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(jsonRequest);
}
this is my php code i tested it and it's working so shouldn't be the problem:
<?php
require_once("connection.php");
$id=$_GET["id"];
$q="Select * from product_type where id='$id'";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_assoc($res)){
$types[]=$row;
}
echo (json_encode($types));
mysqli_free_result($res);
?>
this is the activity code here not sure if i did something wrong:
public class ptype_detail extends Activity {
int kposition,tposition,id;
TextView ttitle,tdes;
ImageView timg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptype_detail);
tposition=(Integer)getIntent().getExtras().get("tpos");
kposition=(Integer)getIntent().getExtras().get("kpos");
if (kposition==0)
id=tposition+5;
else if(kposition==1)
id=tposition+18;
else if (kposition==2)
id=tposition+20;
else
id=tposition;
ttitle=(TextView)findViewById(R.id.title) ;
tdes=(TextView)findViewById(R.id.typedes);
timg=(ImageView)findViewById(R.id.titleimage);
shop db=new shop(this);
db.gettypedet(id,ttitle,timg,tdes);
}
}
Well, I get Validation:com.android.volley.ParseError: org.json.JSONException:value false of type java.jang.Boolean cannot be converted to JSONObject error whenever I try to receive a boolean value, that is sent by a REST web service, in my android app using volley's JSONObjectRequest format.
I know that using StringRequest will be the easy way to solve this but I really wonder if there's another way to solve this.
My guess is that the primitive boolean value is the problem because it is not equevalent to a json object. so the exeption is thrown in the onResponse(JSONObject response) volley method.
here's the java REST web service:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Boolean validate(CreditCard card) {
//instructions
if(/* some conditions */) {
cardList.put(card.getId(), card);
return true;
}
return false;
}
and the android app code:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_id = findViewById(R.id.id);
et_num = findViewById(R.id.number);
et_type = findViewById(R.id.type);
et_ctrlnb = findViewById(R.id.ctrlnum);
et_expd = findViewById(R.id.expdate);
b_validate = findViewById(R.id.validate);
b_validate.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == b_validate) {
String request_url = "http://192.168.191.1:8080/RESTCardValidator/rest/cardvalidator";
JSONObject cardDetails = new JSONObject();
try {
cardDetails.put("controlNumber", Integer.parseInt(et_ctrlnb.getText().toString()));
cardDetails.put("expiryDate", et_expd.getText().toString());
cardDetails.put("id", Long.parseLong(et_id.getText().toString()));
cardDetails.put("number", et_num.getText().toString());
cardDetails.put("type", et_type.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, request_url, cardDetails,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, "Validation:" + response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Validation:" + error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(request);
}
}
as you see in the image the value true/false is received
First Screenshot-
Second Screenshot -
I Followed some tutorials for connecting phpMyAdmin(WAMP) to my android studio. I Followed the tutorial well and still getting this error.
what am i doing wrong? I'm using my Device(Lollipop 5.0) and Android Studio 1.0.
10-07 00:27:03.719 25314-25616/com.example.galvez.php E/Volley﹕ [11353] BasicNetwork.performRequest: Unexpected response code 403 for http://192.16*.**.**/poi/showData.php
Heres my android code:
public class MainActivity extends Activity {
EditText POI,POILongLat,POIType,POIAddress,POIZipCode;
Button insertVal,showVal;
TextView textResult;
RequestQueue requestQueue;
String insertUrl="http://192.168.**.**/poi/insertData.php";
String showUrl="http://192.168.**.**/poi/showData.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
POI = (EditText) findViewById(R.id.txtPOI);
POILongLat=(EditText) findViewById(R.id.txtPOILongLat);
POIType = (EditText) findViewById(R.id.txtPOIType);
POIAddress = (EditText) findViewById(R.id.txtPOIAddress);
POIZipCode = (EditText) findViewById(R.id.txtPOIZipCode);
insertVal = (Button) findViewById(R.id.btnInsert);
showVal = (Button) findViewById(R.id.btnView);
textResult = (TextView) findViewById(R.id.txtResult);
requestQueue = Volley.newRequestQueue(getApplicationContext());
showVal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl,new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
try {
JSONArray pois = response.getJSONArray("stud");
for(int i=0;i<pois.length();i++){
JSONObject pointOfInterest = pois.getJSONObject(i);
String strPOI = pointOfInterest.getString("POI");
String strPOILongLat = pointOfInterest.getString("POILongLat");
String strPOIType = pointOfInterest.getString("POILongLat");
String strPOIAddress = pointOfInterest.getString("POIAddress");
String strPOIZipCode = pointOfInterest.getString("POIZipCode");
textResult.append(strPOI+" "+strPOILongLat+" "+strPOIType+" "+strPOIAddress+" "+strPOIZipCode);
Log.v("",strPOI+" "+strPOILongLat+" "+strPOIType+" "+strPOIAddress+" "+strPOIZipCode);
}
textResult.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
});
}
If you look at the error message:
Unexpected response code 403
and how you make the request:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl,new Response.Listener<JSONObject>()
It's logical to jump to the conclusion that your server is creating a 403 forbidden response due to CSRF protection. You can confirm that this is indeed the case by looking at the webserver log file.
You have two choices, switch off CSRF protection for that url if you do not have any critical data or make a get request to the same url so that cookies are set properly.