Related
I have a problem with my code that works very well for me, but when I intercept with a proxy it sends me a double request. I would like to solve that error and only send it once. I was checking the web and I found a similar question but I am new to this language and I don't know how to implement it.
Android Volley double post when have slow request
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.pwd);
final Button loginButton = findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String URL = "https://www.myurl.com/login.php";
String username = usernameEditText.getText().toString();
String pwd = passwordEditText.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject r = new JSONObject(response);
String status = r.getString("msg");
if (status.equals("OK")) {
Intent secretIntent = new Intent().setClass(LoginActivity.this, MenuActivity.class);
startActivity(secretIntent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("pwd", pwd);
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
hello I could find the answer, it was actually very simple just add a line to the code
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
here my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.pwd);
final Button loginButton = findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String URL = "https://www.myurl.com/login.php";
String username = usernameEditText.getText().toString();
String pwd = passwordEditText.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject r = new JSONObject(response);
String status = r.getString("msg");
if (status.equals("OK")) {
Intent secretIntent = new Intent().setClass(LoginActivity.this, MenuActivity.class);
startActivity(secretIntent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("pwd", pwd);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
});
}
I am using POST method and trying to Send Object as data using Android Volley Library to change the Current Password to New One but I am not Able to do it.
SettingFragment
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
/*
// JSONObject js = new JSONObject();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
// error.getMessage();
}
}) {
#Override
public String getBodyContentType() {
return "Content-Type;application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
*/
// JSONObject params = new JSONObject();
// params.put(KEY_Name, Name);
// params.put(KEY_MasterID, master_id);
// params.put(KEY_USERNAME, username);
// params.put(KEY_OldPASSWORD, oldpassword);
// params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
// headers.put(KEY_Name, Name);
// headers.put(KEY_MasterID, master_id);
// headers.put(KEY_USERNAME, username);
// headers.put(KEY_OldPASSWORD, oldpassword);
// headers.put(KEY_UserPassword, newpassword);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Backend object looks like
Users = {
NAME: vm.name,
UserName: vm.currentUserName,
oldPassword:vm.oldPassword,
UserPassword: vm.UserPassword
Users.MasterID = vm.masterID;
}
I am able to send through the POSTMan but through Code i am not able to do it.
logcat
05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID
How can this issue be Solved?
You may try this code, I have implemented the same thing as you do ... it might work for you
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put(KEY_Name, Name);
headers.put(KEY_MasterID, master_id);
headers.put(KEY_USERNAME, username);
headers.put(KEY_OldPASSWORD, oldpassword);
headers.put(KEY_UserPassword, newpassword);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
You can try this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
You should change the StringRequest to JSONObjectRequest as you are working with a JSON object in the backend. So you should pass the strings as a JSON object and then it might work.
private void makeJsonObjectRequest() throws JSONException {
JSONObject cred = new JSONObject();
cred.put("username", username.getText().toString());
cred.put("password", password.getText().toString());
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(Request.Method.POST,
urlJsonPost, cred, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
//aftererror:
try {
// Parsing json object response
// response will be a json object
token = response.getString("token");
adminName = response.getString("adminName");
jsonResponse = "";
jsonResponse += "token:" + token ;
jsonResponse += "adminName:" + adminName;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}});AppController.getInstance().addToRequestQueue(jsonObjReq);
You would also need to create a class named AppController.java and punch in the below code
import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
You can also send POST parameters as JSONObject with the StringRequest.
Try this one:
private static final String KEY_Name = "NAME"
private static final String KEY_MasterID = "MasterID"
private static final String KEY_USERNAME = "UserName"
private static final String KEY_OldPASSWORD = "oldPassword"
private static final String KEY_UserPassword= "UserPassword"
..........
..................
JSONObject params = new JSONObject();
params.put(KEY_Name, Name);
params.put(KEY_MasterID, master_id);
params.put(KEY_USERNAME, username);
params.put(KEY_OldPASSWORD, oldpassword);
params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Navigation_URL_SettingRequest, params,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
..............
...................
I have broken masterID and Send only the integer for the login, but in the changing password i want all the masterID without broken.Which is not added by me,thats the error and has to sent through the parameter section.
working code is shown below
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, "s" + master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I get an error when I make multiple volley requests.
First, I am requesting login and it works fine. After the login process, the main activity opens in the application. When I make a new request here, the request is added to the queue. But the request is not executed. what is the reason of this?
This code is login function:
private void LoginUser(final String email, final String password) {
String tag_string_req = "request_register";
pDialog.setMessage("Giriş Yapılıyor ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
int userId = user.getInt("UserId");
int uId = user.getInt("UId");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("UserId", userId);
intent.putExtra("UId", uId);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This code is get datas about user at after login function:
public void Sync(final Context context, final int uId)
{
String tag_string_req = "request_syncUser";
db1 = new Database(context);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//gelen tüm verileri local db ye at
try {
SQLiteDatabase db = db1.getWritableDatabase();
JSONObject jObj = new JSONObject(response);
JSONArray responseUser = jObj.getJSONArray("user");
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if(!error) {
for(int i=0; i<responseUser.length(); i++)
{
JSONObject user = responseUser.getJSONObject(i);
String u_name = user.getString("Name");
String u_surname = user.getString("Surname");
String u_email = user.getString("Email");
String u_password = user.getString("Password");
String u_isLogin = user.getString("isLogin");
String u_isSync = user.getString("isSync");
int u_uId = user.getInt("UId");
ContentValues cv = new ContentValues();
cv.put("Name", u_name);
cv.put("Surname", u_surname);
cv.put("Email", u_email);
cv.put("Password", u_password);
cv.put("isLogin", u_isLogin);
cv.put("isSync", u_isSync);
cv.put("UId", u_uId);
db.insertOrThrow("user", null, cv);
Toast.makeText(context, message ,Toast.LENGTH_LONG).show();
Toast.makeText(context, u_name + u_surname,Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uId", String.valueOf(uId));
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
Well we need to see your code?
That said my guess is you are not creating / accessing your queue in a singleton pattern. Complete guess. Always always always post code.
I try to open a new activity on a onResponse of Volley. But I have no idea of what parameters I can use.
Indeed my Volley request is on another class and, I think I need to pass the context of my first class on the second. But I have no idea of how I can do.
public class ConnexionActivity extends Activity{
EditText textlogin;
EditText textpassword;
Button btnConnexion;
String login;
String password;
private AllRequest req;
private PrefManager pref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connexion);
this.req = new AllRequest(getApplicationContext());
this.pref = new PrefManager(getApplicationContext());
textlogin = (EditText) findViewById(R.id.editText_login_connexion);
textpassword = (EditText) findViewById(R.id.editText_mdp_connexion);
btnConnexion = (Button) findViewById(R.id.btn_Connexion);
btnConnexion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login = textlogin.getText().toString();
password = textpassword.getText().toString();
req.TokenRequest(login, password);
}
});
}
}
And that is a part of my function that do the request Volley:
public void TokenRequest(final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(ConnexionActivity.getContext(), listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
public void TokenRequest(final Context context,final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
and in your activity change req.TokenRequest(login, password);
with req.TokenRequest(ConnexionActivity.this,login, password);
You can also create a Context variable Context context;
and then initialized it when OnCreate() is called
context=this;
So the, when the intent is being made, do this
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);
I am trying to send some data to the server using the Volley library.
private void registerUser(final String email, final String username,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
// String status = jObj.getString("status");
// User successfully stored in MySQL
// Now store the user in sqlite
String name = jObj.getString("username");
String email = jObj.getString("email");
String password = jObj.getString("password");
// String created_at = user
//.getString("created_at");
// Inserting row in users table
// db.addUser(name, email);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("username", username);
params.put("password", password);
return params;
}
Unfortunately no json is sent and I get nothing back. Here is a sample of my logcat output. After sending a request successfully to the server, I want to get response with success/fail.
Register Response: ---- YOUR DATA ----
username=xxx&email=xxx%40gmail.com&password=xxxx&-------------------
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ org.json.JSONException: Value ---- of type java.lang.String
cannot be converted to JSONObject
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
Any help please? Thanx.
private void postUsingVolley() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId = DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
final HashMap<String, String> postParams = new HashMap<String, String>();
sendFeedbackParams.put("key1", value1);
sendFeedbackParams.put("key2", value2);
sendFeedbackParams.put("key3", value3);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
ApplicationData.POST_URL, new JSONObject(postParams),
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
//Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "Thank you for your post", Toast.LENGTH_LONG).show();
if (response.getBoolean("status")) {
pDialog.dismiss();
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
if (isNetworkProblem(error)) {
Toast.makeText(mContext, "Internet Problem", Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getRequestHeaders();
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(8000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Use Volley like this,... It is working for me.
First of all you are not sending json to your server. You are sending parametrized url with post method and getting json text as response.
I think the problem is the response from the server which is supposedly json. But from your log, this text "---- YOUR DATA ----" which you get from Log.d(TAG, "Register Response: " + response.toString()); is not at all json formatted . So you need to modify your server to respond in correct json format.
This is the solution. I had to use the JsonObjectRequest class and not the StringRequest on. What JsonRequest does is that it converts your HashMap key-value pairs into a JSON Format.
private void registerUser(String email_address,String username, String
password) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId =
DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
String location = getResources().getConfiguration().locale.getCountry();
final HashMap<String, String> postParams = new HashMap<String, String>
();
postParams.put("username", username);
postParams.put("email", email_address);
postParams.put("password", password);
postParams.put("location", location);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(AppConfig.URL_REGISTER, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
Toast.makeText(getApplicationContext(),
response.getString("message"), Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Thank
you for your post", Toast.LENGTH_LONG).show();
if (response.getString("status").equals("success")){
session.setLogin(true);
pDialog.dismiss();
Intent i = new
Intent(RegisterActivity.this,Welcome.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
JSon post
public void makePostUsingVolley()
{
session = new SessionManager(getActivity().getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
final String token = user.get(SessionManager.KEY_NAME);
//Toast.makeText(getActivity().getApplicationContext(),name, Toast.LENGTH_SHORT).show();
final Map<String, String> params = new HashMap<String, String>();
//params.put("Employees",name);
String tag_json_obj = "json_obj_req";
String url = "enter your url";
final ProgressDialog pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest req = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
// final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
//"http://emservices.azurewebsites.net/Employee.asmx/CheckUserGet", new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
JSONObject json;
// Toast.makeText(getActivity().getApplicationContext(),"dfgghfhfgjhgjghjuhj", Toast.LENGTH_SHORT).show();
//Toast.makeText(getActivity().getApplicationContext(),obb.length(), Toast.LENGTH_SHORT).show();
// JSONObject data=obj.getJSONObject("Employee_Name");
ObjectOutput out = null;
try {
json = new JSONObject(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.hide();
// Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_SHORT).show();
Log.d("", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
pDialog.hide();
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username",name);
params.put("password",password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_obj);
}
requestQueue= Volley.newRequestQueue(MainActivity.this);
StringRequest request=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
Log.d("response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name.getText().toString().trim());
jsonObject.put("email", email.getText().toString().trim());
jsonObject.put("phone", phone.getText().toString().trim());
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> params = new HashMap<String, String>();
params.put("message", jsonObject.toString());
return params;
}
};
requestQueue.add(request);
[["deep","dee#gmail.com","8888999999"]]