Android Studio - Using Volley to get JSON data from the server - java

This is my first attempt to create a login system in Android Studio and already got myself into trouble with my code.
My PHP script always returns something as JSON and I'm trying to parse that JSON in my LoginActivity, inside the login -method, but I'm getting
the following error after creditentials were forwarded to the server and the login button was clicked:
I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22
I/qtaguid﹕ Untagging socket 43 failed errno=-22
W/NetworkManagementSocketTagger﹕ untagSocket(43) failed with errno -22
It did work earlier, when I was doing a stringRequest instead of jsonRequest, so everything should be fine on the server side. Since I'm very new to Android development, I'm unable to figure this one out by myself and need desperately your help.
Here's my LoginActivity without the imports:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
// Define Views
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private ProgressBar progress;
private UserLocalStore userLocalStore;
private boolean loggedIn = false;
private final String TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); // Hides the Action Bar for Login Activity
setContentView(R.layout.activity_login); // Sets the Content View
// Initializing Views
// EditText fields
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
// Buttons
buttonLogin = (Button) findViewById(R.id.buttonLogin);
// Other
progress = (ProgressBar) findViewById(R.id.progressBar);
// This method will set watcher for the EditTextFields
// The method will watch the value set to the EditTextFields.
// If there is nothing inputted in the EditTextField, "Login" button is disabled.
// Correspondingly, if there are text in the field, "Login" button is enabled.
watcher(editTextEmail, editTextPassword, buttonLogin);
// On-Click listeners
buttonLogin.setOnClickListener(this);
}
// Watcher method to check the value of EditText field
public void watcher(final EditText editText, final EditText editPassword, final Button button)
{
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (editText.length() == 0 && editPassword.length() == 0) // If length of the text field is equal to 0
button.setEnabled(false); // Disable the "Send" button
else
button.setEnabled(true); // Otherwise enable
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
if(editText.length() == 0 && editPassword.length() == 0)
button.setEnabled(false); //disable at app start
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
// If the value of loggedIn variable is true
if(!loggedIn) {
// We will start the Courses activity
Intent intent = new Intent(LoginActivity.this, CourseActivity.class);
startActivity(intent);
}
}
private void login() {
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// This line will not print out
System.out.println(response);
try {
String json_status = response.getString("status");
String message = response.getString("message");
if(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
System.out.println(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// You can handle the error here if you want
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Return parameters
return params;
}
};
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// If button Login was clicked
case R.id.buttonLogin:
login(); // Start login method after "Login" button is clicked
// startActivity(new Intent(this, MainActivity.class));
break;
}
}
}
And here's my PHP:
<?php
require_once("dbconnect.php");
// POST Variables
$post_email = $_POST['email'];
$post_password = $_POST['password'];
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(array(
':email' => $post_email,
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && password_verify($post_password, $row['password']) && $row['role'] != 'staff') {
$user = array(); // Create an array for the user information
$user['id'] = $row['id'];
$user['name'] = $row['name'];
$user['email'] = $row['email'];
$user['password'] = $row['password'];
$user['role'] = $row['role'];
// echo json_encode(["message" => "success"]);
echo json_encode(["status" => "success", "message" => "Successfully logged in"]); // Format the array to JSON
} else {
echo json_encode(["status" => "error", "message" => "Incorrect creditentials"]);
}

You might not be passing the params, I usually use this syntax:
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
Map<String, Object> params = new ArrayMap<>(2);
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG, response.toString());
// other stuff ...
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
// You can handle the error here if you want
}
});
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
Also, you might want to handle all the volley requests in a Singleton class, have a look at this SO question.
Hope this helps in any way :)

Related

Show function data without blinking with Volley in Android Studio

Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}

Retrieve data from database to my app (NOT WORKING)

so i am trying to retrieve data stored in my database.
basically the user inputs a car registration number and a rating (between 1-5)and click button. once the button is clicked my code will execute. which gets text from both editext and send to my server. i have php file saved, which will check if the carregistration number matches the value in the databse. if it matches retrieve the current rating stored in the database. the value is then showed on another acitivity. The php file works fine. i tried by inserting value manually. the problem i have is that when the button is clicked nothign happens. i have used this code to retrieve user name and other details on another app.
dataretrieve.java
public class DataRetrieve extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;
public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("carreg", carreg);
params.put("rating", rating + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Profile.java (where the user inputs carreg and rating)
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
final EditText editText = (EditText) findViewById(R.id.carreg);
final EditText editText1 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String carreg = editText.getText().toString();
final int rating = Integer.parseInt(editText1.getText().toString());
// Response received from the server
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) {
int rating = jsonResponse.getInt("rating");
Intent intent = new Intent(Profile.this, UserAreaActivity.class);
intent.putExtra("rating", rating);
Profile.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Profile.this);
queue.add(loginRequest);
}});
}
}
userareaactivity.java (where value is shown when retrieved)
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
Intent intent = getIntent();
username = intent.getIntExtra("rating", -1);
etusername.setText(username + "");
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
#Override
public void onBackPressed(){
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Intent intent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(intent);
}
return true;
}
I'm getting an error from your php page:
<b>Parse error</b>: syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />
You can see the output of your response in the log by using this line above your JSON parsing (before it throws the exception)
Log.d("Response", response.toString());
I copied your success block into the exception block and it works as expected, so that code is valid. I would also put some kind of alert in the catch to let you know the failure happened when you're done testing.
Side note, change your parameter line to this...it's cleaner:
params.put("rating", String.valueOf(rating));

On back pressed goes to login screen after register

I made an app that requires the user to register. The first time user opens the app - login screen opens. They need to click on the "go to register" button to go to register activity. After they register, they are automatically logged in.
Now here is the issue - when the user first registers he is sent to MainActivity. He should press back and the app should close. But when he tries to exit the app he presses the back button and instead of app closing it goes back to login screen.
The next time I try to sign in, I have no problem - it goes straight to the MainActivity.
This is how my activities look like:
LoginActivity:
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_REGISTER = 0;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_login) Button _loginButton;
#InjectView(R.id.link_register) TextView _registerLink;
CheckBox checkBoxShowPassword;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.inject(this);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = _emailText.getText().toString().trim();
String password = _passwordText.getText().toString().trim();
if (!email.isEmpty() && !password.isEmpty()) {
// login user
login(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Go to register screen
_registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Register activity
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
}
});
// Password checkbox
checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
_passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
_passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
}
// Login
public void login(final String email, final String password) {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
// Change to false for disabling after error
_loginButton.setEnabled(true);
String tag_string_req = "req_login";
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
// TODO: Implementing authentication logic
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
progressDialog.dismiss();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
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);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast toast = Toast.makeText(getApplicationContext(),
"Registration failed due to connectivity issues", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
// _loginButton.setEnabled(true);
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
// Validation
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 20) {
_passwordText.setError("Enter between 4 and 20 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
#InjectView(R.id.input_name) EditText _nameText;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_register) Button _registerButton;
#InjectView(R.id.link_login) TextView _loginLink;
CheckBox checkBoxShowPassword;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.inject(this);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
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(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register button
_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = _nameText.getText().toString().trim();
String email = _emailText.getText().toString().trim();
String password = _passwordText.getText().toString().trim();
String phone = getMyPhoneNumber();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
register(name, email, password, phone);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Go to login screen
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
finish();
}
});
// Password checkbox
checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
_passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
_passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
}
// Register
public void register(final String name, final String email, final String password, final String phone) {
Log.d(TAG, "Register");
if (!validate()) {
onRegisterFailed();
return;
}
_registerButton.setEnabled(false);
String tag_string_req = "req_register";
final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account...");
progressDialog.show();
// TODO: Implementing register logic
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());
progressDialog.dismiss();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
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);
//TODO: insert contacts to local db
String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
while (phones.moveToNext()) {
if (phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) != -1)
{
String username = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
db.addContact(username, phoneNumber);
}
}
phones.close();
Toast.makeText(getApplicationContext(), "Registration successful!", Toast.LENGTH_LONG).show();
// Auto login
session.setLogin(true);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast toast = Toast.makeText(getApplicationContext(),
"Registration failed due to connectivity issues", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
_registerButton.setEnabled(true);
progressDialog.dismiss();
}
}) {
#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);
params.put("phone", phone);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
public void onRegisterSuccess() {
_registerButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onRegisterFailed() {
Toast.makeText(getBaseContext(), "Registration failed", Toast.LENGTH_LONG).show();
_registerButton.setEnabled(true);
}
// Validation
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("Enter at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 20) {
_passwordText.setError("Enter between 4 and 20 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
// Get users phone number
private String getMyPhoneNumber() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String MyPhoneNumber = "0000000000";
try
{
MyPhoneNumber =tMgr.getLine1Number();
}
catch(NullPointerException ex)
{
}
if(MyPhoneNumber.equals("")){
MyPhoneNumber = tMgr.getSubscriberId();
}
return MyPhoneNumber;
}
private String getMy10DigitPhoneNumber() {
String s = getMyPhoneNumber();
return s.substring(2);
}
}
As per my idea you just do one thing that when you are passing from login activity to register_activity just finish the login_activity like this
// Go to register screen
_registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Register activity
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
LoginActivity.this.finish();
}
});
If you still facing the same problem then when you are opens the login_activity first then create a variable of that class and assign the value to that variable like this
public static LoginActivity mLogin_activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLogin_activity=LoginActivity.this;
Then check this value is null or not in onBackPressed() method in Main_Activity if that value is null then finish that main_activity otherwise finish that login_activity too; Something like this:
#Override
public void onBackPressed() {
super.onBackPressed();
if (LoginActivity.mLogin_activity!=null) {
LoginActivity.mLogin_activity.finish();
MainActivity.this.finish();
}else {
MainActivity.this.finish();
}
}
Hope i had answered your question...
when you write
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
This must need to override onActivityResult method to handle that result.
In that code you just write
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
finish();
I hope this could be help you.
For me, I found out that I was calling a variable from another activity which was on my Register.xml (the progressbarBtn) instead of the progressbar that I inserted on Login.Java which was ProgressbarBtn3
thats why it is taking me back to the register page

How to pass User_Id to every activity in android?

I am trying to build an android application. After logged in to the application I want to use User_Id for all activities for getting unique data based on that user_id. How it is possible? And what changes i want to make in this code to get user_id in all activities?
LoginActivity.java
public class LoginActivityMerchant extends AppCompatActivity implements View.OnClickListener {
//Defining views
private AutoCompleteTextView ACTUser;
private EditText etPassword;
private Button buttonLogin;
private TextView linkToRegister;
private ProgressDialog loading;
public static final String KEY_firstName = "First_Name";
public static final String KEY_LastName = "Last_Name";
public static final String KEY_Mob = "Mobile";
public static final String KEY_ShopName = "Shop_Name";
public static final String KEY_Location = "Location";
public static final String KEY_Radius = "UserId";
public static final String JSON_ARRAY = "result";
public static final String KEY_UserName = "User_Name";
public static final String KEY_Password = "Password";
public TextView test;
//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity_merchant);
//Initializing views
ACTUser = (AutoCompleteTextView) findViewById(R.id.email);
etPassword = (EditText) findViewById(R.id.password);
buttonLogin = (Button) findViewById(R.id.email_sign_in_button);
linkToRegister = (TextView) findViewById(R.id.Reg_TextView);
test=(TextView)findViewById(R.id.test);
//Adding click listener
buttonLogin.setOnClickListener(this);
linkToRegister.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
//Config.KEY_USERNAME=Config.USERNAME_SHARED_PREF;
SharedPreferences sharedPreferences1 = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String username = sharedPreferences1.getString(config.SHARED_PREF_NAME,"Not Available");
setInfos(username);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String user = ACTUser.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
if(user.isEmpty()||password.isEmpty())
{
Toast.makeText(LoginActivityMerchant.this, "Please fill all the fields", Toast.LENGTH_LONG).show();
}
//Creating a string request
else{
StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//test.setText(response);
//If we are getting success from server
if(response.contains("success")){
//Creating a shared preference
// Toast.makeText(LoginActivityMerchant.this, "Success", Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = LoginActivityMerchant.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
editor.putString(config.SHARED_PREF_NAME, user);
config.KEY_USERNAME = user;
//Saving values to editor
editor.commit();
//Starting profile activity
//Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
setInfos(user);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivityMerchant.this, "Invalid username or password", Toast.LENGTH_LONG).show();
ACTUser.setText(user);
etPassword.setText(password);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(KEY_UserName, user);
params.put(KEY_Password, password);
//test.setText(password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}}
#Override
public void onClick(View v) {
//Calling the login function
if(v==buttonLogin){
login();
}
if(v==linkToRegister){
Intent intent = new Intent(LoginActivityMerchant.this, Registration.class);
startActivity(intent);
}
}
public void setInfos(String username){
String url = config.LOGIN_URL+username;
loading = ProgressDialog.show(this, " Please wait...", "Fetching...", false, false);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivityMerchant.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String FirstName="";
String LastName="";
String UserName="";
String Mobile="";
String Location="";
String Radius="";
// String stringid="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject userData = result.getJSONObject(0);
FirstName = userData.getString(KEY_firstName);
UserName = userData.getString(KEY_UserName);
LastName = userData.getString(KEY_LastName);
Mobile = userData.getString(KEY_Mob);
Location = userData.getString(KEY_Location);
//stringid=userData.getString(KEY_USERID);
} catch (JSONException e) {
e.printStackTrace();
}
config.KEY_NAME=FirstName + " "+LastName;
config.KEY_USERNAME=UserName;
}
}
loginold.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['User_Name'];
$password = $_POST['Password'];
//Creating sql query
$sql = "SELECT * FROM User_Profile WHERE User_Name='$username' AND Password='$password'";
//importing dbConnect.php script
require_once('include/dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
else
{echo "error";}
You can use SharedPreference :
public class SaveId {
static final String ID = "ID";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setId(Context ctx, int value) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(ID, value);
editor.commit();
}
public static String getId(Context ctx) {
return getSharedPreferences(ctx).getString(ID, "");
}
}
When you want to set the id call SaveId.setId(yourID); and when you want to get the id call SaveId.getId();
Instead of read and write to SharedPreferences I would prefer a more efficient way to store a simple data like an ID.
There are two ways:
If you are using an MVP approach, you could delegate the setter and getter of the ID to your central manager, instead go for option 2
Set the id in your custom application and get it through it.
You have to override default application and set it in the manifest.
public class MyApplication extends Application {
private Integer id;
public void setId(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
In your activities you can get it through:
((MyApplication) getApplication()).getId();

Android login app not logging user in

I am trying to develop a chat application with a login and registration. The app is working without any errors, when I register it adds the right information in SQLite but when i log in with those details the app says "Logging in" but nothing happens. Does anyone know what is wrong with my code?
LoginActivity.java
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
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 (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
MainActivity.java
public class MainActivity extends Activity
{
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Socket sender;
public BufferedReader br;
public PrintStream bw;
class SocketListener implements Runnable
{
String str;
public void run()
{
try
{
sender = new Socket("127.0.0.1", 1234);
br = new BufferedReader (new InputStreamReader(sender.getInputStream()));
bw = new PrintStream (sender.getOutputStream());
bw.println("Connected");
while (true)
{
final TextView t = (TextView)findViewById(R.id.textView);
String s = br.readLine ();
CharSequence cs = t.getText ();
str = cs + "\r\n" + s;
Log.i("Chat-str:", str);
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
TextView tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
Button send1 = (Button)findViewById(R.id.button);
send1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText et = (EditText)findViewById(R.id.editText);
Editable e = et.getText();
final String s = e.toString();
new Thread ()
{
public void run ()
{
bw.println (s);
}
}.start();
}
});
Thread t = new Thread (new SocketListener ());
t.start();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
it doesnt look like you ever log them in. look here
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
what is checkLogin(email, password);
and if it is returning a boolean you should be saying
if(checkLogin){
//log them in
}
can you post the checklogin code?

Categories

Resources