Volley not working, Android - android

I am building an android app and I am trying to send basic info on a phpmyadmin DB. I wrote a script (working, tested it with postman) and I used volley in my andorid app to send params to script. Here is my code.
public class Info extends AppCompatActivity {
EditText e_mail, age, group_size;
Button next;
static final String insertURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertUser.php";
static final String insertGroupURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertGroupUser.php";
String id_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
next = (Button) findViewById(R.id.next);
e_mail = (EditText) findViewById(R.id.e_mail);
age = (EditText) findViewById(R.id.age);
group_size = (EditText) findViewById(R.id.group_size);
Intent intent = getIntent();
id_user = intent.getStringExtra("id");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insertUser();
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
}
});
}
public void insertUser() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, insertURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parametar = new HashMap<String, String>();
parametar.put("id_user", id_user);
parametar.put("age", String.valueOf(age.getText()));
parametar.put("email", String.valueOf(e_mail.getText()));
return parametar;
}
};
requestQueue.add(request);
}
}
The problem is that I don't get any errors. And I did a previous project that was very similar, and did it exactly like this and it worked. Now I can't figure out why it won't work.
Every answer is appreciated. Thank you!
EDIT
My script is:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
require 'connection.php';
insertUser();
}
function insertUser(){
global $connect;
$id_user = $_POST["id_user"];
$age = $_POST["age"];
$email = $_POST["email"];
$query = "INSERT INTO user ( id_user, age, email)
VALUES ( '$id_user', '$age', '$email');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>

I figured it out thanks to Nabil Mohammed Nalakath's suggestion to use log in onResponse(). Which gave me an value to long for column error.
Since I used uniqueID = UUID.randomUUID().toString(); i got an id of length 36 and in my table i only set varchar(35). So I changed that and it worked!

I think whenever you get success response then you want to open LocationSearch screen for that you need to keep this code:
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
Inside onResponse() method and there you need to check have you got success response or not.If success then above code should be executed.
I think you should use requestQueue.enque(request);

Its important to configure AndroidMenifest.xml file
by
and
android:usesCleartextTraffic="true"

Related

How to send response of a volley POST request called from one activity to another in android

Requirement:
In Android app code, in MainActivity, I want to call a REST POST API through Volley and then pass the JSON response as it is in next Activity. But the response which gets passed is blank. The code is:
Please note that
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
public class MainActivity extends AppCompatActivity {
public static final String LOGIN_RESULT = "com.example.awgpusers2.loginResult";
static String globalOutput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View view) throws Exception {
EditText emailEditText = findViewById(R.id.editTextTextEmailAddress2);
EditText phoneEditText = findViewById(R.id.editTextPhone2);
EditText passwordEditText = findViewById(R.id.editTextTextPassword);
String emailAddress = emailEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String password = passwordEditText.getText().toString();
makePostCall(emailAddress, phone, password, new VolleyCallback() {
#Override
public void onSuccess(String result) {
System.out.println("result " + result);
globalOutput = result;
System.out.println("globalOutput " + globalOutput);
}
});
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
Intent intent = new Intent(this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
}
void makePostCall(String emailAddress, String phone, String password, final VolleyCallback callback) throws Exception {
//String globalOutput;
String postUrl = "http://18.188.180.148:8080/auth/login";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject postData = new JSONObject();
try {
postData.put("email", emailAddress);
postData.put("password", password);
postData.put("phoneNumber", phone);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, postData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(response.toString());
}
}, new Response.ErrorListener() {
........................
});
requestQueue.add(jsonObjectRequest);
}
}
Please help
makePostCall() method is asynchronous function.
So you need to process in callback function.
public void login(View view) throws Exception {
EditText emailEditText = findViewById(R.id.editTextTextEmailAddress2);
EditText phoneEditText = findViewById(R.id.editTextPhone2);
EditText passwordEditText = findViewById(R.id.editTextTextPassword);
String emailAddress = emailEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String password = passwordEditText.getText().toString();
makePostCall(emailAddress, phone, password, new VolleyCallback() {
#Override
public void onSuccess(String result) {
System.out.println("result " + result);
globalOutput = result;
System.out.println("globalOutput " + globalOutput);
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
}
});
}
});
}
Your System.out.println is executed before Volley returns the response. Volley's enqueue method is asynchronous, i.e. you can't tell exactly when it'll be executed.
Move
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
Intent intent = new Intent(this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
Into the onSuccess method of the VolleyCallback

How to stop the process if name exists in the database android

I have one page by this page new user can register in my app to his can use my app.
I have two fields in this page one for phone number and second for his password.
Also I have one button if his press this button his will move to another page.
What I try to do I need in this page if user click this button to continue to another page before move I try to check if this phone number or his ID of device in my db already. So if his phone number or ID devices already exists in my db. user will show message like "phone number already available" and stop continue to another page or stop this process. In this case button of continue will be not work. That what I try to do.
Now the code in button like that:
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry = spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this, VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
}
});
how I try to do it like that. I make one connection by volley and php file to see if this phone number available in db or no.
private void Regist(){
String URL_REGIST = "https://xxxxxxxxxxxxx/registers.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
Toast.makeText(RegistrationPage.this,"Test"+ Response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegistrationPage.this,"This device already exists", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegistrationPage.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("deviceID",deviceID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And add this method in button before intent:
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();//================here like that
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry = spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this, VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
}
});
Now like that my code is working I can see message of "This device already exists". But still the user move to another page so how I can make it stop if this message come?
PHP CODE
<?php
include 'connt.php';
$deviceID = $_POST['deviceID'];
$CheckSQL = "SELECT * FROM user WHERE deviceID='$deviceID'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'phone Already Exist';
}
mysqli_close($con);
?>
The problem is after you've checked, you still have the code to proceed no matter what, so create a new method called continue then put the continue code inside like:
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry =
spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this,
VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
delete it from the button onClicklistener. Then in the Regist(); inside the try function put the new continue method after the toast. It should work

how to solve java.net.SocketException: socket failed: EPERM (Operation not permitted)

When I was using my Android Studio to create a simple registration to my local database I met the problem that shows on the title, and here is my code:
public class registerInterface extends AppCompatActivity {
private EditText editTextUsername, editTextPassword, editTextEmail;
private Button buttonRegister, backToLogin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_interface);
editTextUsername = findViewById(R.id.username);
editTextPassword = findViewById(R.id.password);
editTextEmail = findViewById(R.id.email);
buttonRegister = findViewById(R.id.register);
backToLogin = findViewById(R.id.go_back_login);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerUser();
}
});
}
public void registerUser(){
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String username = editTextUsername.getText().toString().trim();
progressDialog.setMessage("Registering...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, DataBaseConstants.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I have already add these in my AndroidManifest.xml, but still does not work:
<uses-permission android:name="android.promission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
I don't if it is the problem about the IP address, but I just cannot figure it out.
First
Just uninstall the app from the emulator then run again and it’ll work I had the same issue.
Sometime this issue occur when problem with emulator.
Secondly -
May be problem is with your network, the wifi you are connected with in emulator is not allowing you to connect to the api you are calling.
Hi and I have found the solution. It's the matter of the virtual device, in my version API 29 the connection of network is forbidden. I recommend using the third party virtual device and now I'm using 'NetEase MUMU' and if you meet similar question you can check it out.
Uninstalling the app from the emulator didn't do the trick. You have to kill the emulator first, uninstall the app, and build it again. At least, that's what's worked for me.

The app works on emulator but not on actual device

I just wanted help in my android app actually scene is like ,I have made an android app that stores and fetch data from mysql database,so the twist is whenever I run app on android emulator it runs fine but as soon as I try to run it on actual device there seem to be nothing is happening however the login and register buttons seem to be doing nothing they don't call the api,I am using wamp as local server and my device and laptop is on same wifi network router so I am not getting it,btw the logcat shows no error at all and it also runs perfectly on emulator
my register activity to add user into database
public class Register extends AppCompatActivity {
private static final String TAG = Register.class.getSimpleName();
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword;
public Button btnSignUp;
public Button btnLinkLogin;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
SessionManager session = new SessionManager(getApplicationContext());
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Register.this,
Matchboard.class);
startActivity(intent);
finish();
}
signupInputName = (EditText) findViewById(R.id.name);
signupInputEmail = (EditText) findViewById(R.id.email);
signupInputPassword = (EditText) findViewById(R.id.password);
btnSignUp = (Button) findViewById(R.id.btnRegister);
btnLinkLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = signupInputName.getText().toString().trim();
String email = signupInputEmail.getText().toString().trim();
String password = signupInputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_SHORT).show();
}
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Login.class);
startActivity(i);
finish();
}
});
}
private void registerUser(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "Hi "+name+",You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
Login.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_SHORT).show();
}
} 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_SHORT).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I believe when you are on your local machine the call to made to the localhost but when the app is on your actual device there might be some IP issue.You might be accessing it wrongly.
The thing is that your actual device and the system should be on the same network.
Check your IP using ipconfig command and then retry on same network.

Unable to navigate to Activity after successful login - Android volley

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

Categories

Resources