I am building a login in my android app. I am trying to make to make my app communicate with a Node.JS server using volley to make network request. The node.js server is already setup and is running. I made sure that my PC and my android phone are on the same network (I really don't know if this is necessary). Also Mongo DB is setup and running. But I get an error response when I try to login. This is my code:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getLoginEmail = loginEmail.getText().toString();
String getLoginPassword = loginPassword.getText().toString();
if (!TextUtils.isEmpty(getLoginEmail) && !TextUtils.isEmpty(getLoginPassword)) {
loginUser(getLoginEmail, getLoginPassword);
} else if...
}
});...
private void loginUser(final String gottenLoginEmail, final String gottenLoginPassword) {
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage(getString(R.string.logging_in));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("onResponse", response);
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Log.i("Response", response); //logged response
//check if response at first position (index 0) equals success
if (jsonObject.names().get(0).equals("success")) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
...
}
} catch (JSONException e) {
Log.i("Exception", e.getMessage()); //logged exception
Snackbar.make(findViewById(R.id.login_activity), e.getMessage(), Snackbar.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error", "ERRROR: " + error.getMessage()); //logged error. Refer to debugger image below
progressDialog.dismiss();
Snackbar.make(findViewById(R.id.login_activity), error.getMessage(), Snackbar.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", gottenLoginEmail);
params.put("password", gottenLoginPassword);
return params;
}
};
RequestHandler.getInstance(LoginActivity.this).addToRequestQueue(stringRequest);
}
In my Constants Java Class I have the following:
public class Constants {
public static final String ROOT_URL = "http://192.168.43.1:5000/api/user/auth/";
public static final String URL_LOGIN = ROOT_URL + "signin";
public static final String URL_REGISTER = ROOT_URL + "signup";
//192.168.43.1 is the DHCP server of the network my pc and android phone is connected to
//5000 is the node.js application port i.e. localhost:5000
}
Please I need help. I have been battling with this for 3 days now...
When I run the app I get this in the debugger console
N.B. "localhost:5000/api/user/auth/signin" is the API endpoint login route.
I think your trouble is Firewall try to disable it
if your OC is windows follow this guide https://www.youtube.com/watch?v=dlBgoVMXIWo
Related
I am working on an Android app.
This is one function inside a fragment:
private void guardar_paciente() {
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_CHECK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String id_paciente = jObj.getString("id");
String id_nhc = jObj.getString("nhc");
if (!error) {
editor2.putString("id_paciente", id_paciente);
editor2.putString("nhc", id_nhc);
editor2.apply();
} else {
// Error in login. Get the error message
// String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
// Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("nombre_completo", nombre_completo);
params.put("apellidos", apellidos);
params.put("tel1", tel1);
params.put("tel2", tel2);
params.put("email", email);
params.put("profesion", profesion);
params.put("sexo", sexo);
params.put("fecha_nacimiento", fecha_nacimiento);
params.put("edad", edad);
params.put("peso", peso);
params.put("talla", talla);
params.put("IMC", IMC);
params.put("consentimiento", "1");
params.put("clinica_paciente", clinica_actual);
params.put("imagen_paciente", imagen_paciente);
params.put("firma_paciente", numero+".JPG");
params.put("DNI", DNI);
params.put("direccion", direccion);
params.put("raza", raza);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
What I need is to execute another function, abrirPaciente(), just after guardar_paciente() has finished all its methods and it is safe to change the UI.
I have tried calling abrirPaciente() just after editor2.apply();, but the app crashes.
Making use of callbacks :
public class foo {
interface ExampleInterface {
void finishedServiceCallNoErrors();
void finishedServiceCallWithError(String error);
}
void guardar_paciente(ExampleInterface exampleInterface) {
...
#Override
public void onResponse(String response) {
....
//there was no error
exampleInterface.finishedServiceCallNoErrors();
//there was an error
exampleInterface.finishedServiceCallWithError("your error message here");
....
}
...
}
}
and an example of how you'd make use of this :
public class bar implements foo.ExampleInterface {
//simple example of how you'd use this
private void callingIt() {
new foo().guardar_paciente(this); //here, we can pass `this` because our class is implementing the interface
}
//these now get returned to the class making use of the service call, so you can easily handle things here, instead of worrying about the logic in your service call response
#Override
public void finishedServiceCallNoErrors() {
//TODO("Handle the response with no error");
//your call completed and everything was fine, now do something else
}
#Override
public void finishedServiceCallWithError(String error) {
// TODO("Handle the response with an error")
// there was an error, handle it here
}
}
I'm not sure if this callback pattern will be safe to use if it's being triggered from a background thread, so for that you'd need to switch threads inside the callbacks, so inside finishedServiceCallNoErrors and inside finishedServiceCallWithError you'd potentially need like a Runnable, so you can make use of the main thread, or inside the onResponse of the service call, before triggering the callbacks, you could also change there to the main thread. You can find help with something like that here
Below is my implementation of ReCaptcha V2 in my Android app.
When I run it, it returns: Error message: unknown status code: 12008
This means the following:
public static final int RECAPTCHA_INVALID_KEYTYPE Cannot start the
reCAPTCHA service because type of site key is not valid.
Please register new site key with the key type set to "reCAPTCHA
Android" via //g.co/recaptcha/androidsignup.
Constant Value: 12008
My site key is available on my ReCaptcha admin portal, so what do I need to do for it to be 'valid'?
The code example that I've implemented does include the following comments regarding the server url:
//it is google recaptcha siteverify server
//you can place your server url
Is this a requirement or a suggestion?
public void onCaptchaClick(View view) {
SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
.addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
if (!response.getTokenResult().isEmpty()) {
handleSiteVerify(response.getTokenResult());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
Log.d(TAG, "Error message: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
} else {
Log.d(TAG, "Unknown type of error: " + e.getMessage());
}
}
});
}
protected void handleSiteVerify(final String responseToken){
//it is google recaptcha siteverify server
//you can place your server url
String url = "https://www.google.com/recaptcha/api/siteverify";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getBoolean("success")){
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getBoolean("success")),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getString("error-codes")),Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Log.d(TAG, "JSON exception: " + ex.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error message: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("secret", SECRET_KEY);
params.put("response", responseToken);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
This error means that you are not using the right key.
Have you created an Android app key or a website key? I got this error when I tried to use the web key for the app, you need an Android app key.
Issue
After successful login verification from the server, unable to open New activity. Activity stays at Login Activity
Background
What I am trying to achieve here is open "Welcome" activity after successful User login. The server correctly validates the user login and displays the Toast, but not opening the activity
Code
private static final String LOGIN_URL = "<myURL>/login.php";
public static final String KEY_LOGUSERNAME = "loUname";
public static final String KEY_LOGPASSWORD = "loPass";
EditText LogUser, LogPass;
Button btnsLogin;
String loUser, loPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initalizevars();
btnsLogin.setOnClickListener(this);
}
public void initalizevars() {
LogUser = (EditText) findViewById(R.id.etLogUser);
LogPass = (EditText) findViewById(R.id.etLogPass);
btnsLogin = (Button) findViewById(R.id.btnLogin);
}
private void login() {
loUser = LogUser.getText().toString().trim();
loPassword = LogPass.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("Success"))
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
openProfile();
}else
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_LOGUSERNAME, loUser);
map.put(KEY_LOGPASSWORD, loPassword);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest1);
}
private void openProfile() {
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
#Override
public void onClick(View v) {
if (v == btnsLogin) {
login();
}
}
The Toast is being displayed from the server response on successful verification
What i tried
I tried changing the Intent to below
Intent i = new Intent(Login.this,Welcome.class);
startActivity(i);
But no luck. Am stuck and unable to figure out where and what went wrong.
Requesting your help in putting me in the right direction.
Thanks
EDIT
i modified the if condition to be more meaningful and to debug as well
if (response.trim().equals("Success")) {
Toast.makeText(Login.this, response + " Right", Toast.LENGTH_LONG).show();
openProfile();
} else {
Toast.makeText(Login.this, response + " Wrong", Toast.LENGTH_LONG).show();
openProfile();
}
As suggested by user #user1232726, the else part is being considered and the activity is opened which should not be the case.
My login.php outputs
Success
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
Basically the issue was with the server response as it did return some javascript along with the success message. Guidance from #cricket_007, #IshitaSinha actually help me fix the issue.
Solution : Additional javascript/ or messages can be added When using free hosting sites. Check the entire response before comparing it with the actual response
Hey developers i am tried send the data through intent
i am sending data A activity to B activity data is send A Activity properly but B Activity is not receive but some data is receive but some data not receive
Code is A Activity
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
final String user = responseObj.getString("uid");
String message = responseObj.getString("msg");
Intent intent1 = new Intent(getApplicationContext(),HttpService.class);
intent1.putExtra("uid", user); // <---Sending data here this data not recive B Activity ------>
Log.d("user id going","====>"+user);
if(!user.equalsIgnoreCase("")){
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"ErrorToast: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponce: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxxxxx");
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
// Adding request to request queue
newapp.getInstance().addToRequestQueue(strReq);
}
private void verifyOtp() {
String otp = inputOtp.getText().toString().trim();
if (!otp.isEmpty()) {
Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
// <---- sending data here also B Activity---->
grapprIntent.putExtra("key","xxxxxxxxxxxx");
grapprIntent.putExtra("mobileverify", otp);
startService(grapprIntent);
} else {
Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
private static boolean isValidPhoneNumber(String mobile) {
String regEx = "^[0-9]{10}$";
return mobile.matches(regEx);
}
B Activity
public class HttpService extends IntentService {
private static String TAG = HttpService.class.getSimpleName();
public HttpService() {
super(HttpService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String otp = intent.getStringExtra("mobileverify");
final String user1 = intent.getStringExtra("uid"); //<---- this is not recive value ---->
verifyOtp(otp,user1);
}
}
/**
* Posting the OTP to server and activating the user
*
* #param otp otp received in the SMS
*/
private void verifyOtp(final String otp, final String user1){
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
String message = responseObj.getString("msg");
if (message!="") {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user1); // here its given error
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
Please Help me Thanks
Your grapprIntentdoesn't contain a value for "uid" key because you don't put it. You use some intent1 which is not used anywhere more. Instead you need to put "uid" into grapprIntent:
grapprIntent.putExtra("uid", user);
Maybe grapprIntent should be global variable for the class or find a way to pass it between methods.
Create A Global variable in your Application class and Use set and get Methods
like this
Application.class
private String user;
public String setuser(String usermy) {
this.user = usermy;
return null;
}
public String getuser()
{
return user;
}
where you want to send value set value like as your code
SMSActivity
MyApplication myUser = (MyApplication)getApplicationContext();
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
String user = responseObj.getString("uid");
String user1 = myUser.setuser(user);
And Get Value in your HttpService.class
Like this
MyApplication uidinfo = (MyApplication)getApplicationContext();
final String user = uidinfo.getuser();
and mention manifest.xml inside Application tag
<application
android:name=".MyApplication"
/>
happy coding
I watched the google io ,and saw volley. But I don't know how to get start with it.
I've tried to clone https://android.googlesource.com/platform/frameworks/volley , but the test project keep warn me "resource directory does not exist" .
please give me some clue!
Set up the project as a library ( Project->Properties->Android->"Is Library" ).
Then, just create the res folder in Volley project, and eclipse will build the Volley.jar !
I found this to get start with.
I write this Test Project , and import com.android.volley and com.android.volley.toolbox from the volley library. And it works ^_^
protected static final String TAG = "com.gyh.myvolleytest";
public static final String url = "http://192.168.1.108:8080/httptest/servlet/mainservlet?name=stack&age=23";
public static Response.ErrorListener createErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error Response code: " + error.getMessage());
}
};
}
public static Response.Listener<String> createSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// TODO parse response
String string = response.toString();
Log.d(TAG, "string :" + string);
}
};
}
public static Response.Listener<JSONObject> createJsonListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String jsonStr = response.toString();
Log.d(TAG, "jsonStr :" + jsonStr);
System.out.println(jsonStr);
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
RequestQueue queue = Volley.newRequestQueue(this);
// JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
// url, null, createJsonListener(), createErrorListener());
StringRequest request = new StringRequest(Request.Method.GET, url,
createSuccessListener(), createErrorListener());
queue.add(request);
queue.start();
}
Hope this can help ^_^