Volley StringRequest not inserting data in Firebase - android

I am trying to insert user input in firebase and am using Volley. But nothing being inserted in firebase.Below is the code -
String url = "https://zimber-69c82.firebaseio.com/";
StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Firebase firebase = new Firebase("https://zimber-69c82.firebaseio.com/users");
if (response.equals("null")) {
firebase.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject object = new JSONObject(response);
if (!object.has(user)) {
firebase.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RegisterActivity.this, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
progressDialog.dismiss();
}
}

Related

JSONArray cannot be converted to JSONObject in Android

My Android app send request to REST API to authenticate user. Server return true with that request. But in my app run into onErrorResponse() withoud running into onResponse(). And the error I printed:
com.android.volley.ParseError: org.json.JSONException: Value [{"id":1,"username":"vuthehuyht","full_name":"Vũ Thế Huy","phone_number":"0972809817","password":"hoanglan"}] of type org.json.JSONArray cannot be converted to JSONObject
authenticateUser function
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", phoneNumber);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.53.100:3001/user/auth", jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
System.out.println(error.toString());
}
});
requestQueue.add(jsonObjectRequest);
user.controller.js
exports.auth = (req, res) => {
const phone_number = req.body.phone_number;
const password = req.body.password;
User.findAll({
where: {
phone_number: phone_number,
password: password
}
})
.then(data => {
res.send(data);
res.end();
})
.catch(err => {
res.status(500).send({
message: err.message | "Could not found user!"
});
res.end();
})
};
How can I fix it?
Just modify your Volley's request onResponse callback so accepts JSONArray as response instead of JSONObject, because that is the response type you are getting from your server:
#Override
public void onResponse(JSONArray response) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
}
if this is your response
[
{
"id":1,
"username":"vuthehuyht",
"full_name":"Vũ Thế Huy",
"phone_number":"0972809817",
"password":"hoanglan"
}
]
you may have to start with JSONArray LIKE
Try this Method
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "Url", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String Error = "";
try {
JSONArray jsonArray= new JSONArray();
for (int i = 0; i<jsonArray.length();i++){
JSONObject job = jsonArray.getJSONObject(i);
//So and So
progressDialog.dismiss();
}
} catch (JSONException e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);

How do I solve Error org.json.jsonexception.No value fo login

I'm trying to login a registered user using their email and password from the registration credentials. How do I place value for login?
This is for a new xamp server. ,
private void Login( final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++ ){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(Login.this,
"Success login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.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);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +error.toString(), Toast.LENGTH_SHORT).show();
}
})
}

E/Volley: [12083] BasicNetwork.performRequest: Unexpected response code 404

I want the user to login using database credentials:
final String link="http://166.62.29.42/sunrajadmin/login.php";
final String string_username=editText.getText().toString(),string_password=editText1.getText().toString();
if(string_username=="")
{
editText.setError("please enter username");
editText.requestFocus();
}
else if(string_password=="")
{
editText1.setError("please enter password");
editText1.requestFocus();
}
else
{
RequestQueue queue1= Volley.newRequestQueue(button.getContext());
String url= Uri.parse(link).buildUpon()
.appendQueryParameter("username",string_username)
.appendQueryParameter("password",string_password).build().toString();
StringRequest request1=new StringRequest( url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
if(response.contains("0 results"))
{
Toast.makeText(button.getContext(),"username/password are invalid",Toast.LENGTH_SHORT).show();
}
else {
try {
JSONObject object1 = new JSONObject(response);
String userid=object1.getString("id");
String name=object1.getString("name");
String email=object1.getString("email");
String mobile=object1.getString("mobile");
Session session=new Session(button.getContext());
session.userLoggedin(userid,name,email,mobile);
Intent i1=new Intent(button.getContext(),MainActivity.class);
startActivity(i1);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(button.getContext(),"network error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
queue1.add(request1);
}
}
});
404 means page not found i.e. the URL you are hitting is not found. please make sure your URL is correct and your method of hitting the service is correct.

StringRequest for loop

how i can use for loop with StringRequest to get all data in mysQl data base so this my code `
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
for(int i=0;i<jObj.length();i++){
String user = jObj.getJSONObject("user").getString("name");
//Toast.makeText(getApplicationContext(), "Hi " + user +", You are login!", Toast.LENGTH_SHORT).show();
// Launch User activity
// finish();
}} else {
String errorMsg =jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}`

How to dismiss Progress Dialog when Swipe to refresh is Refreshing in android?

I have an app in which inside onCreate its sending request to server and I have added a SwipeRefresh when I swipe down again, the request is sent to server.
Problem is that when I swipe down, a ProgressDialog is shown to me which I don't want. What I want is, if swipe is refreshing then don't show the ProgressDialog, otherwise show ProgressDialog.
Code:-
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getWalletBalance();
}
});
/* Here in this method we send request to server for wallet balance */
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
//here I am getting error
m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Define this variable in your activity
boolean isShowProgressDialog=true;
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
isShowProgressDialog=false;
getWalletBalance();
}
});
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
if(isShowProgressDialog){
isShowProgressDialog=true;
m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
}
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
if(m_Dialog!=null && m_Dialog.isShowing()){
m_Dialog.dismiss();}
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
if(m_Dialog!=null && m_Dialog.isShowing()){
m_Dialog.dismiss();}
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Set a variable to mark if the swipe refreshing is going on like this.
private boolean isRefreshing = false;
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
isRefreshing = true; // Set the swipe refresh to true
getWalletBalance();
}
});
/* Here in this method we send request to server for wallet balance */
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
// Add a check here
if(isRefreshing) m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
// Reset the value here
isRefreshing = false;
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources