recently i've made a program that can upload image to mysql database via php, and now i'm gonna put that image to my circleImageView, but i've encountered some issue, if i do image update, the image won't refresh until i close the apps and run it again.
here is my code for displaying the image and others from mysql database
public void putAllUserData(final String username){
StringRequest stringRequest = new StringRequest(Request.Method.POST, databaseURL.viewUserData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i = 0; i < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
setUsername.setText(username);
setFullName.setText(object.getString("nama"));
setCountry.setText(object.getString("asal_negara"));
setGender.setText(object.getString("jenis_kelamin"));
prfImage = object.getString("image_path");
if(prfImage.isEmpty()){
Toast.makeText(profileActivity.this, "", Toast.LENGTH_SHORT).show();
}
else {
Picasso.get().load(prfImage).into(profileImage);
}
}
} catch (JSONException e) {
Toast.makeText(profileActivity.this, "Error " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(profileActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
Related
i am trying to authenticate using an api.am getting an error on response, my api returns the following response and am getting the following error.
value of type java.lang.String cannot be converted to JSONArray.
kindly help, am a newbie.
this is what my api returns:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
this is my code;
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
int i = 0;
while (i < jArray.length()) {
JSONObject json_data = jArray.getJSONObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
I was change JSONArray jArray = new JSONArray(response); to JSONObject jObject = new JSONObject(response); and JSONObject json_data = jArray.getJSONObject(i); to String json_data = jObject(i);. Try it, please.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
int i = 0;
while (i < jArray.length()) {
String json_data = jObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
Is your API returning
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
or
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
?
If the first, then you should extract the JSON string from the XML answer before invoking "JSONArray jArray = new JSONArray(response);", and then do something like "JSONArray jArray = new JSONArray(json_part_of_the_response);".
I think your JSON array is inside XML so you have to parse your XML first using dom parser
I tried MYSQL, PHP JSON and VOlley request to log in to the user but when I do without toasting the final response user is not get logged in but when I use toast user gets logged in? why is it so
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
/////////////////////THIS TOAST I AM TALKING ABOUT
Toast.makeText(getApplicationContext(), jsonObject+"", Toast.LENGTH_LONG).show();
if (!jsonObject.getBoolean("error")) {
startActivity(new Intent(LoginActivity.this, MainActivity.class);
}
if(jsonObject.getBoolean("error")){
if(jsonObject.getString("message").equals("ERROR")){
startActivity(new Intent(LoginActivity.this, Verify.class);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", username);
params.put("password", password);
return params;
}
};
stringRequest.setShouldCache(false);
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
I am trying to get the response from the server based on the data I send it, I am able to get a response from the server, but the server doesn't seem to be receiving the values in the getParams().
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);
The method I would suggest in this case is to pass the parameters in the URL of your code and remove the getParams() method.
So, your modified code looks like;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
Hopefully, this will work. Good Luck :)
I am able to consume api via volley library which use normal get post method but my php team just changed my api which accept json . i know there is is JsonObjectrequest in volley but i don't know how to put parameters in `JsonObjectRequest. Any help is appriciated.
PHP API
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$data_back = json_decode(file_get_contents('php://input'));
header("Content-type: application/json");
require "conn.php";
$id = $data_back->{"id"};
$address = $data_back->{"address"};
$pincode = $data_back->{"pincode"};
$name = $data_back->{"name"};
$mobile = $data_back->{"mobile"};
$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE id = $id";
if(mysqli_query($conn,$sql)){
echo 'Address Book Updated Successfully';
}
else{
echo 'Could Not Update Your Address Book';
}
}
?>
Volley Request
StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show();
list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(),
etName.getText().toString(),
etAddress.getText().toString(),
etPinCode.getText().toString(),
etPhone.getText().toString(),
bookModel.getDefAddress()));
d.dismiss();
progress.dismiss();
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map=new HashMap<String, String>();
map.put("id",bookModel.getId());
map.put("name",etName.getText().toString());
map.put("address",etAddress.getText().toString());
map.put("pincode",etPinCode.getText().toString());
map.put("phone",etPhone.getText().toString());
return checkParams(map);
}
private Map<String, String> checkParams(Map<String, String> map){
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
if(pairs.getValue()==null){
map.put(pairs.getKey(), "");
}
}
return map;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
Easy cheesy lemon squeezy!
Some code
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", "300");
params.put("address", "Mars");
params.put("pincode", "***");
params.put("name", "Jon Skeet");
params.put("mobile", "911");
JsonObjectRequest request = new JsonObjectRequest(
/*URL*/,
new JSONObject(params),
new Response.Listener<JSONObject>(){/*...*/});
First Create your JsonObject like
JSONObject js = new JSONObject();
try {
js.put("email", "adasda");
js.put("address", "adasd");
js.put("pincode", "adadasd");
}catch (JSONException e) {
e.printStackTrace();
}
Then your JSON request, take a careful look at get headers.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
private void getWalletDetails(){
final ProgressDialog pDialog; // = new ProgressDialog(mcontext);
StringRequest stringRequest;
pDialog = GifDialog.ctor(mcontext);
pDialog.show();
stringRequest = new StringRequest(Request.Method.POST, place your url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
pDialog.dismiss();
//Showing toast message of the response
try {
JSONObject jsonObject = new JSONObject(s);
totbal.setText("\u20B9 "+jsonObject.getString("avail_balance"));
JSONArray jsonArray = jsonObject.getJSONArray("tx_detail");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
mode = new Model_Wallet_Transaction();
mode.setStr1(object.getString("date"));
mode.setStr4(object.getString("insert_time"));
mode.setStr2(object.getString("name"));
mode.setStr3(object.getString("transaction_id_no"));
mode.setAmount(object.getString("amount"));
mode.setTxtype(object.getString("tx_type"));
modlist.add(mode);
}
// Collections.sort(modlist, new StringDateComparator());
adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist);
list.setAdapter(adp);
} catch (Exception e) {
Log.e("Error", e.toString());
}
// Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
pDialog.dismiss();
//Showing toast
//Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put("user_id", UserId);
params.put("deviceId", DeviceId);
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
This wants to send JsonObject in key Json. So please tell how to send it using volley.
json={"product":"magie"}
How to send this data in Volley, I have add the asyncTask code below for hit api with that type of data.
enter code here
protected void onPreExecute() {
if (progress)
GlobalAlerts.showProgressDialog(context);
}
#Override
protected String doInBackground(String... params) {
String resp = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product","magie");
} catch (JSONException e) {
e.printStackTrace();
}
String data = "json=" + jsonObject.toString();
String url ="http://anc.php";
resp = new JsonCall().executeHttpPostRequest(url, data);
return resp;
}
protected void onPostExecute(String resp) {
if (progress)
GlobalAlerts.hideProgressDialog();
if (resp != null) {
callback.onTaskComplete(resp);
} else {
GlobalAlerts.singleAlert((Activity) context, context.getString(R.string.warning), "Error", false);
}
}
Answer for that is like put data in jsonObject and then pass jsonObject in hashmap with key json.
enter code here
String url = "http://anc.php";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product", "magie");
} catch (JSONException e) {
e.printStackTrace();
}
final HashMap<String,String> hashMap2 = new HashMap<>();
hashMap2.put("json",jsonObject.toString());
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("order_list", response);
GlobalAlerts.hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Error: " + error.getMessage());
GlobalAlerts.hideProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
/*Map<String,String> params = new HashMap<>();
params.put("employee_id"," 1");*/
return hashMap2;
}
};
Application.getInstance().addToRequestQueue(strReq, "order_list");