Specific data retrieve from database : android - android

public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_login";
// Login table name
private static final String TABLE_USER = "user";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_Branch = "branch";
private static final String KEY_SEM = "semester";
private static final String KEY_AMIZONE = "amizone";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
+KEY_Branch + " TEXT," +KEY_SEM + " TEXT ," +KEY_AMIZONE + " TEXT,UNIQUE" + KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name,String email, String Branch, String Semester, String Amizone, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_Branch, Branch); // uid
values.put(KEY_SEM, Semester); // uid
values.put(KEY_AMIZONE, Amizone); // uid
values.put(KEY_UID, uid); // uid
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_USER, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_USER ;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(4));
user.put("created_at", cursor.getString(5));
user.put("branch", cursor.getString(3));
user.put("semester", cursor.getString(7));
user.put("amizone", cursor.getString(6));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_USER, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
}
User_Profile.java
class User_Profile extends Fragment {
private TextView txtName,txtBranch,txtSem,txtAmizone;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.nav_userprofile, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("User Profile");
txtName = (TextView)view.findViewById(R.id.name);
txtEmail = (TextView)view.findViewById(R.id.email);
btnLogout = (Button)view.findViewById(R.id.btnLogout);
txtName = (TextView)view.findViewById(R.id.name);
txtEmail = (TextView)view.findViewById(R.id.email);
txtBranch = (TextView)view.findViewById(R.id.branch);
txtSem = (TextView)view.findViewById(R.id.semester);
txtAmizone = (TextView)view.findViewById(R.id.amizoneid);
btnLogout = (Button)view.findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().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");
String branch = user.get("branch");
String semester = user.get("semester");
String amizone = user.get("amizone");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
txtBranch.setText(branch);
txtAmizone.setText(amizone);
txtSem.setText(semester);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(User_Profile.this.getActivity(),LoginActivity.class);
startActivity(intent);
User_Profile.this.getActivity().finish();
Toast.makeText(User_Profile.this.getActivity(), "Logged Out Successfully", Toast.LENGTH_SHORT).show();
}
}
LoginActivity
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, Home.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(Request.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");
String Branch = user.getString("branch");;
String Semester = user.getString("semester");
String Amizone = user.getString("amizone");
// Inserting row in users table
db.addUser(name, email, uid, created_at,Branch,Semester,Amizone);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, Home.class);
startActivity(intent);
finish();
Toast.makeText(LoginActivity.this, "Login Successfull", Toast.LENGTH_SHORT).show();
} 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();
}
}
RegisterActivity
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword,semester,branch,amizoneid;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
semester = (EditText)findViewById(R.id.sem);
branch = (EditText)findViewById(R.id.branch);
amizoneid = (EditText)findViewById(R.id.amizone);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// 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,Home.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String Branch = branch.getText().toString().trim();
String Semester = semester.getText().toString().trim();
String Amizone = amizoneid.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()&& !Branch.isEmpty() && !Semester.isEmpty()) {
registerUser(name,email, password,Branch,Semester,Amizone);
} else {
Toast.makeText(getApplicationContext(), "Please enter your details!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password,final String Branch,final String Semester,final String Amizone) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// 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 Branch = user.getString("branch");
String Semester = user.getString("semester");
String Amizone = user.getString("amizone");
String created_at = user.getString("created_at");
// Inserting row in users table
db.addUser(name,email,created_at,Branch,Semester,Amizone,uid);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
String tkn = FirebaseInstanceId.getInstance().getToken();
// Toast.makeText(RegisterActivity.this,"Current token ["+tkn+"]",Toast.LENGTH_LONG).show();
Log.d("App", "Token ["+tkn+"]");
// Launch login activity
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), "Regitering User Failed", 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("branch", Branch);
params.put("amizone", Amizone);
params.put("semester", Semester);
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();
}
}
Error : In the User_Profile , not able to retrieve user specific data from the SQl database , only the email and name is showing , other details are blank
Details for fetching data from SQldatabase : D/SQLiteHandler: Fetching user from Sqlite: {email=test#test.com, name=Priyansh, semester=, created_at=2017-08-25 18:09:06, uid=59a067c2185e95.56562559, branch=, amizone=}

Related

posting data to mysql database using rest api which is done in magento 2 from my android app?

facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// 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(
RegisterActivity.this,
LoginActivity.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("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
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();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.

The app works on emulator but not on actual device

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

How to Access Oauth 1.0 ?? I am working on SugarCrm

Hello everyone I am working on a CRM project which uses Sugarcrm 6.5 version. I wanted to know what kind of changes I have to do in my LoginActivity to get Token So that I can call it in other Activity.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private Button button;
private EditText editText;
private EditText editText2;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
CheckBox show_password;
String user_fullname, email, user_id,user_mobile, session_id, module;
public LoginActivity(){
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
show_password = (CheckBox) findViewById(R.id.show_hide_password);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// get the show/hide password Checkbox
// 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
show_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
editText2.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
editText2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = editText.getText().toString().trim();
String password = editText2.getText().toString().trim();
// Check for empty data in the form
if (!username.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(username, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String username, final String password) {
pDialog.setMessage("Logging in ...");
showDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL= "http://crm.sparshnow.com/api/index.php?username="+username+"&password="+password;
final JsonObjectRequest strReq = new JsonObjectRequest(URL,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
String success = response.getString("success");
Log.d("response_value", success);
if (success.equals("TRUE")) {
user_fullname=response.getString("user_fullname");
email=response.getString("email");
user_id=response.getString("user_id");
user_mobile=response.getString("user_mobile");
session_id=response.getString("session_id");
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
intent.putExtra("user_fullname",user_fullname);
intent.putExtra("email",email);
intent.putExtra("user_mobile",user_mobile);
intent.putExtra("session_id", session_id);
session.setLogin(true);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Enter Correct Detail ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError success) {
Log.e(TAG, "Login Error: " + success.getMessage());
Toast.makeText(getApplicationContext(),
success.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
requestQueue.add(strReq);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
A little code
and how to use it will be very useful for me.. please Help me

What is the probleme please ? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
this is all the code
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;
String CK="admin";
#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);
My problem is here, i'm using if(!(CK==uid)) it works but when CK==uid it doesn't work , String CK= admin and when i login with admin not a simple user the uid=admin too . i used Log.e to verify you can see my capture image
you can see that CK and uid are the same but when i use (if CK==uid) it doesn't work
// 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);
Log.e(TAG,"CK: " + CK + " user uid: " + uid);
// Launch main activity
if(!(CK==uid)){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else{
Intent i = new Intent(getApplicationContext(), AllReclamationsActivity.class);
startActivity(i);
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);
}
my problem is in this part :
// 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);
Log.e(TAG,"CK: " + CK + " user uid: " + uid);
// Launch main activity
if(!(CK==uid)){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else{
Intent i = new Intent(getApplicationContext(), AllReclamationsActivity.class);
startActivity(i);
finish();
}
This not a integer value its a string so compare it like as
Use the below function in your condition:
if(!(CK.equals(uid))){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}

User Login credential doesn't show up in the landing page(Homepage) after logging in

I got user-login template from github. I modified it a bit to suit my need but didn't altered any important code.
Problem 1: If I register and login, the page goes to activity_main class(landing page) and my login credentials(name & email) are shown. But if I log out and logging again the credentials are not shown on the landing page. First time it shows next time never.
Problem 2: If I register a new ID but login with any old already registered ID (immediately after registering new), landing page shows the credential of newly register ID. After that again it won't show up if I log in with any ID.
What I want to Happen: User credential to be shown on landing page whenever he logs in.Also prob 2nd to be fixed.
Any help would be appreciated guys.
login page code:
#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(Activity_Login.this, Activity_Main.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(),
Activity_Register.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,
Config_URL.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(Activity_Login.this,
Activity_Main.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();
}
}
Register page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
inputNumber = (EditText) findViewById(R.id.number);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// 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(Activity_Register.this,
Activity_Main.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String number = inputNumber.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !number.isEmpty()) {
registerUser(name, email, password, number);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Login.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password, final String number) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// 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);
// Launch login activity
Intent intent = new Intent(
Activity_Register.this,
Activity_Login.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.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("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("number", number);
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();
}
}
Main activity page code:
public class Activity_Main extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Button booknow;
public void init(){
booknow= (Button) findViewById(R.id.booknow);
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(Activity_Main.this,BikeEntryActivity.class);
startActivity(toy);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
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(Activity_Main.this, Activity_Login.class);
startActivity(intent);
finish();
}
}
For problem 1, when you logout, you are deleting users by calling db.deleteUsers();
When you login again, you need to call db.addUser(name, email, uid, created_at); as you did for registration.
The same applies for problem 2.
UPDATE:
....
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
//You need to save the user here before launching main activity.
db.addUser(name,email);//or whatever method you use to save user.
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
}

Categories

Resources