How can I fix too many things happening Android Studio - java

The problem is definitely from this code.
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etuserame.getText().toString();
final String email = etemail.getText().toString();
final String password = etpassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
when the user clicks register, it does not open the new activity and I get nothing in my database. I just get a cancelling event due to no window focus and too many processes running.
This is my RegisterRequest class.
private Map<String, String> params;
public RegisterRequest(String username, String email, String password, Response.Listener<String> listener){
/*
NExt line means we are going to pass some information into the register.php
*/
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
/*
This is how we pass in the information from the register to the thing, we are using a hashmap
*/
params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
}
/*
Volley needs to get the data so we do a get params
Which gives us this method
*/
#Override
public Map<String, String> getParams() {
return params;
}
}

Related

How to fix "my interminable login" in android studio

I have some problem with my login code. After clicking the login the progress bar loads so long but nothing really happened.
I can not find what is wrong
I'm using php, mysql, volley library
This is my login code:
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://188.173.127.17/Login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading = findViewById(R.id.loading);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPass = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
}else {
email.setError("Please insert email");
password.setError("Please insert password");
}
}
});
final Button bSignup = (Button) findViewById(R.id.bSignup);
bSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
}
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 response) {
try {
JSONObject jsonObject = new JSONObject(response);
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 username = object.getString("username").trim();
String email = object.getString("email").trim();
Toast.makeText(LoginActivity.this,
"Success Login. \nYour Username : "
+username+"\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(LoginActivity.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(LoginActivity.this, "Error" +error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
according to your code onResponse() AND onErrorResponse() mehtod not call;
this is come from some reason
1- check your internet connection
2-check your url
3-you may forget to add permission internet
4-if you are on local you may forget run xampp
5-you may set Retry policy and set timeout to your connection thus add it according to following code :
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 response) {
try {
JSONObject jsonObject = new JSONObject(response);
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 username = object.getString("username").trim();
String email = object.getString("email").trim();
Toast.makeText(LoginActivity.this,
"Success Login. \nYour Username : "
+username+"\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(LoginActivity.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(LoginActivity.this, "Error" +error.toString(),
Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
stringRequest.setRetryPolicy(new
DefaultRetryPolicy(YOUR_TIMOUT_IN_MILLI_SECOND,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
AND important reason :
6- probably onResponse() is called and success is not equal to 1
thus you must put loading.setVisibility(View.GONE); out of if (success.equals("1")) {...} condition

App doesn't send http requests on other androids than the LG i am testing on

I have a app but have teen testing it on an LG G4 i just started testing on other devices but with my samsung s9 the http requests/POST i make to receive JSON data from an API wont work i can not even log into the app
So i have tried to google answers and look on this site to see if there is a solution but tried a lot of them none that worked the message i get from the logcat is:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
tried to google those messages but came up with the same results as previous i am using the Volley library to POST to the server
This is my LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText username = findViewById(R.id.username);
final EditText password = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String uName = username.getText().toString();
final String pWord = password.getText().toString();
Response.Listener<String> listener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Map<String, List<String>> map = new HashMap<>();
JSONObject jsonResponse = new JSONObject(response);
String success = jsonResponse.getString("sukses");
if (success.equals("true")) {
JSONObject jsonArray = jsonResponse.getJSONObject(uName);
JSONArray regions = jsonArray.names();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < regions.length(); i++) {
String id = regions.getString(i);
list.add(regions.getString(i).toString());
JSONObject regionArray = jsonArray.getJSONObject(id);
JSONArray fields = regionArray.names();
List<String> fieldName = new ArrayList<>();
for (int d = 0; d < fields.length(); d++) {
String field = fields.getString(d);
fieldName.add(field);
}
map.put(id, fieldName);
}
Intent farms = new Intent(LoginActivity.this, FarmsActivity.class);
farms.putExtra("username", uName);
farms.putExtra("password", pWord);
farms.putExtra("list", list);
farms.putExtra("map", (Serializable) map);
startActivity(farms);
} else {
AlertDialog.Builder invalid = new AlertDialog.Builder(LoginActivity.this);
invalid.setTitle("Login Failed");
invalid.setMessage("Invalid Login Details")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e){
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(uName, pWord, listener);
loginRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
and this is the LoginRequest:
public class LoginRequest extends StringRequest{
private static final String LOGIN_REQUEST_URL = "MY HTML LINK";
private Map<String, String> params;
public LoginRequest(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams(){
return params;
}
}

My php script is connected, but android studio won't use it. No visible error outputs

I have a php script for handling very basic registration. its in a folder in my localhost; http://(ipaddress/localhost):3306/testing/Register.php. Android studio points to this URL but i get no error output when i run the emulator. When i open the PHP script in the browser, everything looks good.
Here is the registerrequest java script:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://(ipaddress/localhost):3306/testing/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
here is my createuser script
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
finally, here is my PHP script, Register; m
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
mysqli_stmt_bind_param($statement, "ssi",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Im using xampp (apache and mysql turned on) and my Register is in a folder in Htdocs.
Thank you in advance for any help!
You could modify constructor of RegisterRequest:
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener() errListener){ //add error listener
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
......
}
And in CreateUser class file, add below:
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show();
}
}
Then:
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,
responseListener,errorListener);
Now, run again and when error occured, you could see it in error listener.

Response.Listener not working

i have a registration form for my app and the volley sends the request to the php file on the server and i see the user registered on the database, but the response listener does not receive the response which allows it to go back to homepage
this is my android code
if (rdPassword.equals(rdPassword2)) {
if(rdEmail.matches(emailPattern)||rdEmail.matches(emailPattern2)){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
System.out.println(response);
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
pd.dismiss();
Intent bktohome = new Intent(driver_registration.this, home.class);
bktohome.putExtra("company", rdCompany);
startActivity(bktohome);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DriverRegistration registerRequest = new DriverRegistration(rdUsername, rdPassword, rdName, rdEmail,
rdMobile, rdCompany, rdAddress, rdSSN, rdDLN,rdImage_encoded, responseListener);
RequestQueue queue = Volley.newRequestQueue(driver_registration.this);
queue.add(registerRequest);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage("Wrong Email Format...")
.setNegativeButton("Retry",null)
.create()
.show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage(" Passwords do not match")
.setNegativeButton("Retry", null)
.create()
.show();
}
DriverRegistration class
public class DriverRegistration extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://trackitfinal.hostei.com/registerDriver.php";
private Map<String , String> params;
public DriverRegistration(String username , String password , String name , String email , int mobile , String company , String address ,
int SSN , int DLN,String rdImage_encoded, Response.Listener<String> listener)
{
super(Method.POST,REGISTER_REQUEST_URL,listener,null);
params=new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("name",name);
params.put("email",email);
params.put("mobile",mobile+"");
params.put("company",company);
params.put("address",address);
params.put("SSN",SSN+"");
params.put("DLN",DLN+"");
params.put("image",rdImage_encoded);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
check if your Api is working and sending proper response when User hit it or it may be just updating DB.and is there Api for getting user detail you can check it by hitting it or check it in the postman.

when i try to register by my app i didn't get any respnse

I am trying to save my data to server. can any one help me?
when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??
public class Register extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
etCity;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.name);
etEmail = (EditText) findViewById(R.id.email);
etMobile = (EditText) findViewById(R.id.mobile);
etCity = (EditText) findViewById(R.id.etCity);
etPassword = (EditText) findViewById(R.id.password);
//etRePassword = (EditText) findViewById(R.id.rePassword);
register = (Button) findViewById(R.id.bRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String email = etEmail.getText().toString();
final String password = etPassword.getText().toString();
final String city = etCity.getText().toString();
final String phoneno = etMobile.getText().toString();
StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + " Response");
if(response.equals("SUCCESS")){
startActivity(new Intent(Register.this,MainActivity.class));
}
else{
Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.toString());
if(error.networkResponse == null){
if(error.getClass().equals(TimeoutError.class));
Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders()throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("name",name);
headers.put("email",email);
headers.put("password",password);
headers.put("city",city);
headers.put("phoneno",phoneno);
return headers;
}
};
registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + "");
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Registration failed").setNegativeButton("Retry", null)
.create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//super.getHeaders();
Map<String,String> headers = new HashMap<>();
String credential = "raju#gmail.com:123";
String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
//headers.put("Content-Type");
headers.put("Authorization",auth);
//
return headers;
}
};*/
RequestQueue queue = Volley.newRequestQueue(Register.this);
registerRequest.setShouldCache(false);
queue.add(registerRequest);
}
}
Here Is my server code....
#RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public #ResponseBody String saveUser(#RequestBody MobileUserModel mobileUser) {
MobileUserModel user = new MobileUserModel();
user.setActivationKey(mobileUser.getActivationKey());
user.setCity(mobileUser.getCity());
user.setEmail(mobileUser.getEmail());
user.setImeino(mobileUser.getImeino());
user.setName(mobileUser.getName());
user.setPassword(mobileUser.getPassword());
user.setPhoneno(mobileUser.getPhoneno());
userrepository.save(user);
System.out.println("Saved");
// return "User has been saved Successfully";
return "SUCCESS";
}
Put following inside your onClick method:
switch (v.getId()) {
case R.id.bRegister:
// add your registration process code here
break;
}
Make Sure you have given Internet permissions in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Please provide your json response format and also the parameter type that you are sending. It may occur due to different reasons, for example, there is an json array in response and you are mapping it just in simple object or the attributes (variable) that you are mapping into it, names are not exactly similar to json response filed or there can be different multiple reasons.

Categories