How to create http connection which handles automatically if client changes activity - java

I have crated login application which is a part of my native application building process.There are few end points which uses login session.I am getting successful result for login endpoint but It was not forwarding its session to next activity.For example: If user is loggedIn successful he can access rest of features in further activities. But while I'm trying to switch activity I am getting "User Needs to login".
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonResponse = new LoginPOJO();
// UserLogin Field
etUserName = (EditText) findViewById(R.id.etUserName);
// UserLogin Password
etPassword = (EditText) findViewById(R.id.etPassword);
// Login Button Image
btnLogin = (ImageView) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
// User SignUp Button Image
ImageView btnSignUp = (ImageView) findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(this);
// Forget Password Textbutton
TextView frgtPassword = (TextView) findViewById(R.id.forgetpassword);
frgtPassword.setOnClickListener(this);
// Skip for now button
final TextView skipfornow = (TextView) findViewById(R.id.skipnow);
skipfornow.setOnClickListener(this);
}
private void logIn(final String username, final String password) {
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Logging you in...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxxx-dev.elasticbeanstalk.com/api/v1/login";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
LoginPOJO.setCode(parentObject.getString("code"));
// Getting the data from Data Json Object
JSONObject dataObject = parentObject.getJSONObject("data");
// Getting data from Geo object
JSONObject geoObject = dataObject.getJSONObject("geo");
// Getting data from businesses Array
JSONArray businessesArray = dataObject.getJSONArray("businesses");
// Getting data from Meta Object
JSONObject metaObject = parentObject.getJSONObject("meta");
startActivity(new Intent(MainActivity.this, PromotionsFeedActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(MainActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("email", username);
params.put("password",password);
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
feed.java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions_feed);
jsonResponse = new LoginPOJO();
communityImage = (TextView) findViewById(R.id.communityImage);
communityImage.setOnClickListener((View.OnClickListener) this);
searchImage = (TextView) findViewById(R.id.searchImage);
searchImage.setOnClickListener((View.OnClickListener) this);
specialsImage = (TextView) findViewById(R.id.searchImage);
specialsImage.setOnClickListener(this);
calenderImage = (TextView) findViewById(R.id.calenderImage);
calenderImage.setOnClickListener(this);
profileImage = (TextView) findViewById(R.id.profileImage);
profileImage.setOnClickListener(this);
TextView response = (TextView) findViewById(R.id.response);
String data = LoginPOJO.getCode();
response.setText(data);
}
private void getPromotionsFeed(final String location) {
final ProgressDialog progressDialog = new ProgressDialog(PromotionsFeedActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Getting promotions feed...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxx-dev.elasticbeanstalk.com/api/v1/get_promotions_feed";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(PromotionsFeedActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("location","xxx");
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
LogCat
04-03 18:47:26.263 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":200,"status":"ok","message":"Logged in.","data":{"id":"Pg4yYHXIQK","firstName":"Arun","lastName":"","shortName":"Arun","email":"arun#farbinder.com","role":"owner","showInviteMessage":false,"verified":true,"zipCode":"07666","location":"Teaneck, NJ","geo":{"latitude":40.888461,"longitude":-74.012066,"zipcode":"07666","city":"Teaneck","state":"NJ","type":"geo"},"defaultCommunity":{"id":18313,"name":"Teaneck, NJ Community","city":"Teaneck","state":"NJ","latitude":40.888461,"longitude":-74.012066,"type":"community"},"businesses":[{"id":72,"name":"my bus","type":"business"}],"type":"user"},"meta":{"userVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","businessVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-business.m4v","promoVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","searchVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","faqUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/faq","privacyUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/privacy","termsUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/terms","contactFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/contact?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","feedbackFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/feedback?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","type":"links"}}
04-03 18:47:26.265 1518-1877/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#2ddf4f6b attribute=null, token = android.os.BinderProxy#330c1b98
04-03 18:47:26.326 1518-1660/system_process V/WindowManager: Adding window Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 10 (after Window{27eec5b0 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.MainActivity EXITING})
04-03 18:47:26.330 1518-1880/system_process V/WindowManager: Adding window Window{1217747 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 11 (before Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity})
04-03 18:47:26.441 10750-10750/com.example.reception.farbinder_test E/RecyclerView: No adapter attached; skipping layout
04-03 18:47:26.457 1162-1162/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
04-03 18:47:27.092 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":401,"status":"error","message":"User not logged in."}

You do your login in a service, and then have the service broadcast the successful login to any interested classes.

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);
}

Error occurred while the connection of registration API by through PHP in android

I try to connect Login and Registration form through PHP API, But I get the error and I don't understand how its will be resolve. I check the solution regarding this error but I don't understand it. Thank you in advance!
Error :-
W/System.err: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
Here is my code for Registration form (Login.java)
Login. java (This is the java file where for Registration)
public class Login extends Activity {
EditText editname, editemail, editpassword, editmobile;
Button btnRegister;
private static final String TAG = "Login";
private static final String URL_FOR_REGISTRATION = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
ProgressDialog progressDialog;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
editname = (EditText) findViewById(R.id.editname);
editemail = (EditText) findViewById(R.id.editemail);
editpassword = (EditText) findViewById(R.id.editpassword);
editmobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton)findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
private void submitForm() {
registerUser(editname.getText().toString(),
editemail.getText().toString(),
editpassword.getText().toString(),
editmobile.getText().toString());
}
private void registerUser(final String name, final String email, final String password,
final String mobile) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Login.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
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.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("gender", mobile);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
Here is the some image which i test it on postman
[1
Check this
[2
Try this
your response not any boolean error = jObj.getBoolean("error"); so you can read your response code and change your condition as your requirement..
try
{
JSONObject jObj = new JSONObject(response);
String respCode = jObj.getString("resp_code");
//boolean error = jObj.getBoolean("error");
if (respCode.equals("200")) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Login.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}

Cannot enter data into phpmyadmin from Java class

when I run this code there's no new data in my database. I've already checked my connection and tried it using postman app its working the data entered the database. But when i tried to send data from my xml file to phpmyadmin. there's no new data tht I send in it.
when I checked my userRegister.php there's nothing wrong with it.
but still when I try submit the form there's no data in my database.
and the toast msg appear without any msg just a blank black toast msg.
private EditText editTextUsername, editTextEmail, editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
private TextView textViewLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textViewLogin = (TextView) findViewById(R.id.textViewLogin);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(this);
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
progressDialog.setMessage("Registering user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View view) {
if (view == buttonRegister)
registerUser();
}
registerUser.php
require_once'../includes/DbOperations.php';
$response = array();
if ($_SERVER['REQUEST_METHOD']=='POST'){
//check user give all the info required
if(
isset($_POST['username'])and
isset($_POST['email']) and
isset($_POST['password']))
{
//operate the data further
//create db operation object
$db = new DbOperations();
//call method
if($db-> createUser(
$_POST['username'],
$_POST['password'],
$_POST['email']
)){
$response['error'] = false;
$response['message'] = "User registered successfully";
}else{
$response['error'] = true;
$response['message'] = "Some error occured please try again";
}
}else{
$response['error']= true;
$response['message']= "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
//display error in json format
echo json_encode($response);

Display user specific data from MySql in Android Studio

I am currently building an app in which students from an university/school log in and see their marks and other specific info about themselves. I would like to know if it's possible to retrieve data from a table just for the user that logged in and display it, and how exactly could I do that?
Eg. If user A logs in and he wants to see his marks, the he would just go to the marks activity and that would display his marks
LoginActivity.java
public class LoginActivity extends Activity {
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;
private SQLiteHandler db;
#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);
// 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();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// 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_LOGIN, 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);
// 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.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("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
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();
}
});
}
/**
* 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();
}
}

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