cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)' - java

Im going to make a database in php my sql using android studio
but this error is in the way
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
I receive the error cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import prefs.UserInfo;
import prefs.UserSession;
public class Login extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Login.class.getSimpleName();
private EditText email, password;
private Button login;
private TextView signup;
private ProgressDialog progressDialog;
private UserSession session;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_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) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}

addToRequestQueue is a method defined for the volley application controller which seems to be AndroidLoginController in your case. Change the line to
AndroidLoginController.getInstance().addToRequestQueue(strRe‌​q,tag_string_req)
This is assuming you have created the singleton using standard volley tutorials or android developer documentation

Related

How can I solve the register button to pass the form to mysql database and direct me to login page on android studio using java?

I have started mobile app programming using java on android studio, I created a login and register activity for the user and the backend using PHP MySQL to save the details and retrieve them while logging in. When testing register to fill the form and click the button it does not do anything. At first, it brought the error "volley timeout error and I fixed it using the retry policy and fixed the post variables in PHP. But still, it doesn't show any error nor direct me to login page or no changes in the database.
I tried to change the URL from my PC's IP to the emulator's and the server database address but to no avail. I've tried to see what is the error but I'm going through circles. my xamp is also running. I have tried to debug the login activity first and by that, I'll be able to know what error occurs there
Register Activity
package com.example.artisanapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
TextView loglink;
private EditText etid, etname, etmob, etpassword, etpassword2, etemail;
private TextView tvStatus;
private Button btnregister;
private String URL = "http://192.168.0.13:8080/artisan_system/register.php";
private String id, fname, mobileno, password, reenterpass, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etid = findViewById(R.id.etid);
etname = findViewById(R.id.etname);
etmob = findViewById(R.id.etmob);
etpassword = findViewById(R.id.etpassword);
etpassword2 = findViewById(R.id.etpassword2);
etemail = findViewById(R.id.etemail);
tvStatus = findViewById(R.id.tvStatus);
btnregister = findViewById(R.id.btnregister);
id = fname = mobileno = password = reenterpass = email = "";
loglink = findViewById(R.id.loginlink);
}
public void save(View view) {
id = etid.getText().toString().trim();
fname = etname.getText().toString().trim();
mobileno = etmob.getText().toString().trim();
password = etpassword.getText().toString().trim();
reenterpass = etpassword2.getText().toString().trim();
email = etemail.getText().toString().trim();
if(!password.equals(reenterpass)) {
Toast.makeText(this, "Password should be the same", Toast.LENGTH_SHORT).show();
}
else if(!id.equals("") && !fname.equals("") && !mobileno.equals("") && !password.equals("") && !email.equals("")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered");
btnregister.setClickable(false);
} else if (response.equals("failure")) {
tvStatus.setText("Something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("id", id);
data.put("fname",fname );
data.put("mobileno",mobileno );
data.put("password", password);
data.put("email",email);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
Register.php
<?php
if(isset($_POST['id']) && isset($_POST['fname']) && isset($_POST['mobileno']) && isset($_POST['password']) && isset($_POST['email'])) {
require_once "connection.php";
require_once "validate.php";
$id = validate($_POST['id']);
$fname = validate($_POST['fname']);
$mobileno = validate($_POST['mobileno']);
$password = validate($_POST['password']);
$email = validate($_POST['email']);
$sql = "insert into register values('$id', '$fname', '$mobileno', '" . md5($password) . "', '$email')";
echo $sql;
if(!$conn->query($sql)) {
echo "Failure";
} else {
echo "Success";
}
}
?>
login activity
package com.example.artisanapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
TextView forgetbtn;
Button login;
private EditText etid, etpassword;
private String id, password;
private String URL = "https://10.0.2.2/artisan_system/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
id = password = "";
forgetbtn = findViewById(R.id.forgetbtn);
etid = findViewById(R.id.id_no);
etpassword = findViewById(R.id.password);
forgetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, ForgotPassActivity.class);
startActivity(i);
}
});
}
public void login(View view) {
id = etid.getText().toString().trim();
password = etpassword.getText().toString().trim();
if(!id.equals("") && !password.equals("")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("res", response);
//if response state succes then create an intent object and launch success with an intent
if (response.equals("success")) {
Intent intent = new Intent(LoginActivity.this, HomeScreen.class);
startActivity(intent);
finish();
}
else if(response.equals("failure")) {
Toast.makeText(LoginActivity.this, "Invalid login", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("id", id);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}else{
Toast.makeText(this, "Fields cannot be empty", Toast.LENGTH_SHORT).show();
}
}
public void register(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
finish();
}
}

Login button need to be clicked twice in order to login

I am making an attendance app on android studio, but whenever I try to log in using correct credentials I need to click twice on the login button to move forward to the next activity. I tried Asynctasks because of its background thread, after the same result I just reverted back
So, at first click nothing happens but as soon as please wait dialog box disappears and if I click like in under a second or two then it moves to the next activity.
clicking on login fetches some data from the server after the server has validated that the login exists and is correct. when data is received then the new activity is supposed to start since that received data will be shown in the next activity. (i have a list that is checked if it has data then it moves forward)
Login Activity code:
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//sign up and login button
private Button btnSignUp;
private Button btnLogin;
private ProgressDialog progressDialog;
private RequestQueue Queue;
//data URL
private String extractStudentDataURL = "https://asuiot12.000webhostapp.com/checkLoginCredentials.php";
private String extractEnrolmentsDataURL = "https://asuiot12.000webhostapp.com/retrieveEnrolledCoursesData.php";
//editText
private EditText editTextEmail, editTextPassword;
private ConstraintLayout login;
//string variables
public static String inputEmail;
private String inputPassword;
//array list to store enrolled courses data
public static LinkedList<Courses> enrolledCoursesData = new LinkedList();
//static variable
public static StudentData studentData;
//shared preferences to maintain the login status of the user...
public static SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = findViewById(R.id.login_activity);
login.setBackgroundColor(Color.WHITE);
btnSignUp = findViewById(R.id.button_sign_up);
btnLogin = findViewById(R.id.button_login);
// sp = getSharedPreferences("login", MODE_PRIVATE);
editTextEmail = findViewById(R.id.editText_RA_emailAddress);
editTextPassword = findViewById(R.id.editText_RA_password);
//login button listener
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = editTextEmail.getText().toString();
inputPassword = editTextPassword.getText().toString();
if (inputEmail.isEmpty()) {
editTextEmail.setError("Email Required");
editTextEmail.requestFocus();
} else if (inputPassword.isEmpty()) {
editTextPassword.setError("Password Required");
editTextPassword.requestFocus();
} else {
enrolledCoursesData.clear();
ExtractData();
}
}
});
//signUp button listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivityForResult(intent, 1);
}
});
}
//retrieving data from the server and checking the login credentials
private void ExtractData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractStudentDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
int success = data.getInt("success");
if (success == 1) {
Long CNIC = data.getLong("CNIC");
String name = data.getString("Full_Name");
String fss = data.getString("FSS");
String regNo = data.getString("Reg_No");
String batch = data.getString("Batch");
String department = data.getString("Department");
int semester = data.getInt("Semester");
Long mobileNo = data.getLong("Mobile_No");
String nationality = data.getString("Nationality");
String MACAddress = data.getString("MAC_Address");
String homeAddress = data.getString("Home_Address");
String email = data.getString("Email");
String loginPassword = data.getString("Login_Password");
String photo = data.getString("Photo");
studentData = new StudentData(new BigInteger(String.valueOf(CNIC)), new BigInteger(String.valueOf(mobileNo))
, semester, name, fss, regNo, batch, department, nationality,
MACAddress, homeAddress, email, loginPassword, photo);
Toast.makeText(MainActivity.this, "Plz wait....", Toast.LENGTH_LONG).show();
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} else if (success == 0) {
Toast.makeText(MainActivity.this, "Incorrect username or password",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", editTextEmail.getText().toString().trim());
params.put("password", editTextPassword.getText().toString().trim());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//retrieving data of enrolments from server
private void extractDataOfEnrolments(final String email) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractEnrolmentsDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
If layout code or server-side PHP code is required to better understand the question, then please do ask.
You have a misunderstanding as to how threading works.
In your ExtractData method and its onResponse handler, you call extractDataOfEnrolments(), which is itself asynchronous:
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
// the list hasn't been filled yet, will be empty!!!
if (!enrolledCoursesData.isEmpty()) {
}
You then immediately inspect the enrolledCoursesData list and start the CoursesActivity if not empty. The extractDataOfEnrolments() has an asynchronous callback (onResponse()) that hasn't completed yet, so the list would be empty.
You might consider moving the startActivity code into extractDataOfEnrolments(), e.g.:
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
// now your list is populated, so now Ok to startActivity
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} catch (Exception e) {
}

Value connected of type java.lang.string cannot be converted to jsonobject [Android Volley Library]

I know, i know, it's an old question to ask but I'm totally stuck. I've been trying to solve it using all those answer on Stackoverflow but still helpless. So, this is my code:
[Java]:
package com.projectbengkelin;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
EditText Edtnama,Edtemail,Edtalamat,EdtnoHp,Edtpassword;
Button btnLanjut;
Button btnKembali;
ProgressBar loading;
String nama, email, alamat, noHp, password;
//private static String URL_REGISTER = "http://192.168.56.1/finals-mobile/register.php";
String URL_REGISTER = "https://bengkelinteam.000webhostapp.com/api/insert_user.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Edtnama = findViewById(R.id.nama);
Edtemail = findViewById(R.id.email);
Edtalamat = findViewById(R.id.alamat);
EdtnoHp = findViewById(R.id.noHp);
Edtpassword = findViewById(R.id.password);
loading = findViewById(R.id.loading);
btnLanjut = findViewById(R.id.btnLanjut);
btnKembali = findViewById(R.id.btnKembali);
btnKembali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
}
});
btnLanjut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register();
}
});
}
private void Register() {
loading.setVisibility(View.VISIBLE);
btnLanjut.setVisibility(View.GONE);
nama = Edtnama.getText().toString();
email = Edtemail.getText().toString();
alamat = Edtalamat.getText().toString();
noHp = EdtnoHp.getText().toString();
password = Edtpassword.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int sukses = jsonObject.getInt("success");
// Toast.makeText(Register.this, "Setelah jsonObject", Toast.LENGTH_SHORT).show();
if (sukses == 1) {
Toast.makeText(Register.this, "Register Success!", Toast.LENGTH_SHORT).show();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Register.this, "Register Failed!" + e.toString(), Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, "Register Failed!" + error.toString(), Toast.LENGTH_SHORT).show();
//error.printStackTrace();
Log.e("Error", error.getMessage());
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("nama", nama);
params.put("email", email);
params.put("alamat", alamat);
params.put("noHp", noHp);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
And then, here is my PHP code which is I'd put on 000webhost:
[PHP]:
<?php
header('Content-type:application/json;chartset=utf-8');
include 'conn.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$noHp = $_POST['noHp'];
$email = $_POST['email'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$password = $_POST['password'];
// $password = password_hash($password, PASSWORD_DEFAULT);
// require_once 'connect.php';
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
echo json_encode($response);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($response);
mysqli_close($conn);
}
}
Everytime I tried to insert the data using that API JSON, I always get this error messange:
value connected of type java.lang.string cannot be converted to jsonobject
Please help me.
there is simple issue in your php code - do like that :
$response=array();
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
} else {
$response["success"] = "0";
$response["message"] = "error";
}
echo json_encode($response);
mysqli_close($conn);
use Postman to check your response

User Registration using volley library in Android

Using a volley library I am sending a post request to a file register.php which should perform user registration and return JSONResponse after success. The code I have written is working fine in the local server(MAMP) but is not working in the live server. Logcat shows {success = 0} in the live server.
package com.example.androidregisterandlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
RequestQueue requestQueue;
private static String URL_REGIST = "https://domainname.com.np/mentordai/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
Log.d("TAG",response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")) {
Toast.makeText(MainActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Server code
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO student_users_table (name, email, password) VALUES ('$name', '$email', '$password')";
if ( mysqli_query($connection, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($connection);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
```
I'm not an php expert but it looks like your server is the one who return the 'success=0'
And it looks like you have some problem with the if ( mysqli_query($connection, $sql) ) statement, your code going to the else who return the success = 0.
Try to debug the server to see what happens when you send register request.
I think you should put validation at both end (Client as well as server end) on all of your form field . If any one of the field is kept empty your query will not be able to run.
For Validation in server use this at the start of your code
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']))
{
}
To Validate data in Client side use
if(this.name.getText().toString().trim().equals(""))
{
Toast.makeText(MainActivity.this, "Please Enter Name " + e.toString(), Toast.LENGTH_SHORT).show();
}
also for password and email

Android Volley Crashing

I'm using Android Volley to login a user in but when addToRequestQueue is called the following crash report is shown.
The login request is carried out onclick in the Loginactivity as follows:
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = inputUserName.getText().toString();
String pin = inputPIN.getText().toString();
// Check for empty data in the form
if (username.trim().length() > 0 && pin.trim().length() > 0) {
// login user
SharedPreferences prefs = getGCMPreferences(context);
String storeRegId = prefs.getString(PROPERTY_REG_ID, "");
String devid = Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID);
String vars = "/?tag=login&username=" + username + "&pin=" + pin + "&regid=" + storeRegId + "&devid=" + devid;
WebRequest wr = new WebRequest(context);
wr.Request(AppConfig.URL_LOGIN, vars, true, "Please Wait", "Logging in...", "req_login");
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
WebRequest, which uses volley looks like this:
package app;
import helper.SQLiteHandler;
import helper.SessionManager;
import helper.dbTables;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import main.MainActivity;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class WebRequest extends Activity {
private static final String TAG = "LoginActivity";
AtomicInteger msgId = new AtomicInteger();
GoogleCloudMessaging gcm;
SharedPreferences prefs;
public SQLiteHandler db;
SessionManager session;
protected Context context;
public WebRequest(Context context){
this.context = context.getApplicationContext();
}
public void Request(final String url, final String vars, final Boolean show, final String title, final String msg, final String requestName){
final SessionManager session = new SessionManager(context);
final ProgressDialog theProgressDialog = new ProgressDialog(context);
db = new SQLiteHandler(context);
if(show == true){
theProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
theProgressDialog.setTitle(title);
theProgressDialog.setMessage(msg);
theProgressDialog.setIndeterminate(true);
theProgressDialog.setCancelable(false);
theProgressDialog.show();
}
StringRequest strreq = new StringRequest(Method.GET, url + vars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "WEB Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
switch(requestName){
case "req_login":
//process user login
// Fetching user details from sqlite
HashMap<String, String> user = db.fetchResults(dbTables.TABLE_LOGIN, null);
String storedUid = user.get("uid");
JSONObject login = jObj.getJSONObject("login");
if(storedUid != login.getString("uid")){
//new user for device
String[] emptyTables = {dbTables.TABLE_LOGIN};
for(int i=0; i<emptyTables.length; i++){
db.emptyTable(emptyTables[i]);
Log.d(TAG, "empty table : " + emptyTables[i]);
}
}
//store user in database
db.addUser(login.getString("uid"),
login.getString("companyid"),
login.getString("resourceid"),
login.getString("groupid"),
login.getString("title"),
login.getString("firstname"),
login.getString("middleinitial"),
login.getString("lastname"),
login.getString("jobtitle"),
login.getString("managerid"),
login.getString("email"),
login.getString("photo_url"),
login.getString("signature_url"),
login.getString("language"),
login.getString("skin"),
login.getString("defaultprojectid"),
login.getString("cnNotifications"),
login.getString("crNotifications"),
login.getString("coNotifications"),
login.getString("addedby"),
login.getString("dateadded"),
login.getString("editedby"),
login.getString("dateedited"));
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//finish();
break;
}
if(show == true){
theProgressDialog.dismiss();
}
}else{
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
}catch(JSONException e){
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Web Error: " + error.getMessage());
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strreq, requestName);
}
}
I've also included the AppController which I haven't personally changed
package app;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
This is no way to create a Activity object. A lot get go wrong
like this.
Activity is a context therefore he doesnt need to hold a context
as a member. That is a common memory leak.
The activity doesnt go trough the proper life cycle and that is why
everything blows up.
I would suggest to you to start from the basic because when you will do this everything will be clearer.
The AppController isn't neccessary in creating a request using volley......Just add the request in volley android volley request.....https://www.simplifiedcoding.net/android-volley-post-request-tutorial/.......
The way you sends the request will determine if the app crashes.....one, the Sqlite will make the application crashes if the request is sent properly...

Categories