how to fix com.android.volley.ClientError in android studio - android

when i click login button, that alert will show up, i use com.android.volley:volley:1.1.1
and for api, i use restframework from python
this is my mainactivity.java code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
username = etUsername.getText().toString();
password = etPassword.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
String urlLogin = "http://10.0.3.2/api/accounts";
StringRequest stringRequest = new StringRequest(Request.Method.POST, urlLogin, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
boolean validasiLogin = jsonObject.getBoolean("success");
Toast.makeText(MainActivity.this, validasiLogin+"", Toast.LENGTH_SHORT).show();
if (validasiLogin) {
String jsonUsername = jsonObject.getString("username");
Toast.makeText(MainActivity.this, "Username : "+jsonUsername, Toast.LENGTH_LONG).show();
Intent bukaIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(bukaIntent);
}else {
Toast.makeText(MainActivity.this, "Username / Password Salah", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0){
Toast.makeText(MainActivity.this, arg0+"", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
}
how to fix it? can u show what wrong with my code pliss?

Try to debug and see if arg0 in public void onErrorResponse(VolleyError arg0) contains any useful information. Or you can try to log error response body like here: https://stackoverflow.com/a/30722575/5148282

maybe it will help you
fun onErrorResponse(error: VolleyError?) {
if (error == null || error.networkResponse == null) {
return
}
val body: String
//get status code here
val statusCode: String = java.lang.String.valueOf(error.networkResponse.statusCode)
//get response body and parse with appropriate encoding
try {
val UTF_8: Charset = Charset.forName("UTF-8")
body = String(error.networkResponse.data, UTF_8)
} catch (e: UnsupportedEncodingException) {
// exception
}
//do stuff with the body
}

Related

android volley double request when I use proxy

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);
}
});
}

how to login from json object in json error

public class Login extends AppCompatActivity {
private static String LOGIN_URL = "http://172.26.154.132:75";
private EditText username;
private EditText password;
private Button buttonLogin;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.input_email1);
password = (EditText) findViewById(R.id.input_password);
buttonLogin = (Button) findViewById(R.id.btn_login);
loading = findViewById(R.id.loading);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = username.getText().toString().trim();
String mPass = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()){
Login1(mEmail, mPass);
} else {
username.setError("Please insert email");
password.setError("Please insert password");
}
}
});
}
private void Login1(final String username, final String password) {
loading.setVisibility(View.VISIBLE);
buttonLogin.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("data");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("data")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
The response:
{
"status": true,
"message": "User login successful.",
"data": [
{
"sno": "165",
"username": "khushboo.iit#gmail.com",
"user_id_generate": "khushbu#Paswan2018782",
"password": "25f9e794323b453885f5181f1b624d0b",
"is_verified": "1",
"hash": "",
"user_type": "icb_user",
"user_role": "admin"
}
]
}
If your API successfully return data then the problem is JSON parsing. JSON data not parsed successfully. Because "data" contains an array not a single String value.
Try this
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("status");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
I didnt understood question properly but i think i know what you meant.
As there are two functions one is for success and one is for failure you can handle cases like this..
Use JSONObjectRequest instead of string request, It will return you a JSONObject string instead of a string response. Or You can convert the string into a JSONObject like this
JSONObject response = new JSONObject(response)
and then you can parse the jsonObject like this.
if(respose.optString("status")==true)
//success
else
//failed
If you want to print the error msg which is coming from server... do it like this:
error.networkResponse.statusCode
error.networkResponse.message

How to apply setText() to onclicked item in Recyclerview android

I wanna upadate recyclerview child item when itself clicked.It takes the data from server and updates it self. kindly provide any solution for this scenario.Here i have tried as i know but it is not updating.
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
SQLiteHandler db = new SQLiteHandler(context);
HashMap<String, String> user = db.getUserDetails();
String tag_string_req = "req_login";
final String uid = user.get("uid");
Log.d("hello", uid);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.Upvote, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String upvote_no = jObj.getString("upcount");
String text = "Upvoted " + upvote_no;
((TextView) v).setText(text);
//Log.d("resp", upvote);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(context, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("qries_user_id", uid);
params.put("qries_answer_id", answered_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
});
In the above code i am trying to taking response from Json and updating to self child item as ((TextView) v).setText(text); but it is not updating.Thanks in Advance!
Try to cast your clicked view in TextView
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).setText("something");
}
});

Android Volley Unexpected Response Code 400 with body x-www-form-urlencoded

I want to make a POST request to a rest api with body x-www-form-urlencoded parameters. I have tried the following code but I am getting error code 400.
I have been trying to debug this from hours but getting same response. Any help will be appreciated.
public class LoginFragment extends Fragment {
private static final String TAG = "LoginFragment";
EditText mUsername, mPassword;
Button mLogin;
String url = "abc";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login, container, false);
mUsername = (EditText) rootView.findViewById(R.id.login_name_edit_text);
mPassword = (EditText) rootView.findViewById(R.id.login_password_edit_text);
mLogin = (Button) rootView.findViewById(R.id.login_button);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = mUsername.toString();
String password = mPassword.toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
checkLogin(username, password);
} else {
Toast.makeText(getContext(), "Please enter the credentials!", Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
private void checkLogin(final String username, final String password) {
// Tag used to cancel the request
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Launch main activity
Intent intent = new Intent(getActivity(),
MainActivity.class);
startActivity(intent);
getActivity().finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MySingleton.getInstance(getContext()).addToRequestQueue(strReq);
}
}
it was a silly mistake
I wrote mUsername.toString() instead of mUsername.getText()

How to convert String to JSONObject?

I have an obstacle by changing the data string into a jsonobject, is his org.json.JSONException script error: Value
This coding I am trying
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = inputUser.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (username.trim().length() > 0 && password.trim().length() > 0) {
Map<String,String> params = new HashMap<>();
params.put("username", inputUser.getText().toString());
params.put("password", inputPassword.getText().toString());
sendPostRequest(params);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
.show();
}
}
});
public void sendPostRequest(Map<String, String> params) {
showDialog();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.chris-chris.webege.com/login.php";
mCustomRequest = new CustomRequest(Request.Method.POST,
url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(Login.this,
Coba.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
hidepDialog();
Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
}
});
mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mCustomRequest);
}
There are two conditions to convert a string to JSONObject :
1 . The string should be in proper Json format .
2 . Put code in try catch block .
Example:
String jsonString = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar#gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"
Now convert this string to JSONObject
try{
JSONObject jsonResponse = new JSONObject(result);
}catch(Exception e){
e.printStackTrace();
}
Try this,
If you call your service and try to paste that code inside your isSucsess part
JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");
tvTitle.setText(jObject.getString("your string name"));

Categories

Resources