Android Limiting signup for one user - java

I developed an android application ... It is an applications first page... two buttons it have ... signup and sign in .. when user enter for first time he needs to signup and when sign up is pressed registration process will start ... user has to give an username, password and a mobile number .. once he give all this a passcode will be generated annd will be send to the mobile number provided user has to enter this passcode recieved along with the username and password to register... once he got register .. he can signin with the username and password.
Al these part is working fine ... My requirement is to limit the registration for only 1 username.... so for one download one username is allowed .. after one registartion the signup option must deactivated... so what I have to do for that .. I am giving the code ..below...
MainActivity
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
public class MainActivity extends Activity {
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnSignIn=(Button)findViewById(R.id.buttonSignIn);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Signup Activity
import java.util.Random;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
Intent intent = new Intent(SignUPActivity.this, MainActivity.class);
intent.putExtra("number", sms + "");
startActivity(intent);
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0) {
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created and the passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
LoginDataBaseAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number for Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}

To make it simple
Just get the count of the LOGIN Table. If it returns 1 then hide the SignUp button otherwise show the SignUP button. Use the following line of code to get the total count of the table.
In Activity
if(loginDataBaseAdapter.getUsercount()==1){
btnSignUp.setVisibility(View.INVISIBLE);
}
In Database
public long getUsercount() {
return DatabaseUtils.queryNumEntries(db, "LOGIN");
}
It should work.

A quick simple approach would be to use a "marker" that carries a value indicating if they created an account or not. You can use a boolean or an int.
So your programming logic would go as such:
Main Activity
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
public class MainActivity extends Activity {
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnSignIn=(Button)findViewById(R.id.buttonSignIn);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getValue("registrationComplete"==1){
Toast.makeText(getApplicationContext(), "You already have registered.",
Toast.LENGTH_LONG).show(); }
else{
Intent intentSignUP = new
Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
}
});
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
public int getValue(String name) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
return prefs.getInt(name, 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
SingUp Activity
import android.content.SharedPreferences;
import java.util.Random;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
Intent intent = new Intent(SignUPActivity.this, MainActivity.class);
intent.putExtra("number", sms + "");
startActivity(intent);
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0) {
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
// Set value of registrationComplete to 1 to indicate its done.
setValue("registrationComplete",1);
Toast.makeText(getApplicationContext(), "Account Successfully Created and the passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
}
}
});
}
public void setValue(String name, int newValue) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(name, newValue);
editor.commit();
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}

Related

Multi level login user and admin using session?

I have a project to create a login application in Android studio using multi-level session and user login and admin login with different activities.
For example, if the admin click the login button then it goes to the admin activity. If the user clicks then it goes to the user to user activity. All this already works; however, the problem is if I login with admin and close the application by pressing the back button twice without logging out, after that I try to reopen the application, but what appears is user activity(**MainActivity**) not admin activity(**AdminActivity**) ....
Do you have a solution to help me? Sorry if my English bad/
package com.example.ilvan.gogas;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.ilvan.gogas.app.AppController;
import com.example.ilvan.gogas.util.Server;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
ProgressDialog pDialog;
EditText txtusername, txtpassword;
Button btnLogin;
TextView btnRegister;
int success;
ConnectivityManager conMgr;
private String url = Server.URL + "checkLogin.php";
private static final String TAG = com.example.ilvan.gogas.Login.class.getSimpleName();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public final static String TAG_USERNAME = "username";
public final static String TAG_ID = "user_id";
public final static String TAG_USERTYPE = "user_type";
String tag_json_obj = "json_obj_req";
SharedPreferences sharedpreferences;
Boolean session = false;
String user_id, username,user_type;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
final String MESSAGE_NO_INTERNET_ACCESS = "No Internet Connection";
final String MESSAGE_CANNOT_BE_EMPTY = "Kolom Tidak Boleh Kosong";
final String MESSAGE_LOGIN = "Logging in ...";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS,
Toast.LENGTH_LONG).show();
}
}
btnLogin = (Button) findViewById(R.id.btn_login);
btnRegister = (TextView) findViewById(R.id.lbl_register);
txtusername = (EditText) findViewById(R.id.txt_username);
txtpassword = (EditText) findViewById(R.id.txt_password);
// Cek session login jika TRUE maka langsung buka halaman setelah login
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
user_id = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);
user_type = sharedpreferences.getString(TAG_USERTYPE, null);
if (session) {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, user_id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
// mengecek kolom yang kosong
if (username.trim().length() > 0 && password.trim().length() > 0) {
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkLogin(username, password);
} else {
Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS, Toast.LENGTH_LONG).show();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), MESSAGE_CANNOT_BE_EMPTY, Toast.LENGTH_LONG).show();
}
}
});
btnRegister.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(Login.this, Register.class);
Login.this.startActivity(intent);
}
});
}
private void checkLogin(final String username, final String password) {
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage(MESSAGE_LOGIN);
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String user_type = jObj.getString(TAG_USERTYPE);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
// menyimpan login ke session
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// Memanggil halaman setelah login
if (session && user_type.contentEquals("penjual")) {
Intent intent = new Intent(com.example.ilvan.gogas.Login.this, MainActivityPenjual.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
Log.e("username : ", username);
Log.e("password : ",password);
}
} 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() throws AuthFailureError {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
The solution is simple, just override the onBackPressed method with your method to logout in the last activity
#Override
public void onBackPressed() {
super.onBackPressed();
logout();
}
}
And you define logout() method as you want.
About your project, you can do it by several ways, and implementing more than one design pattern, but to keep it simple you can try the following...
Create a screen that serves as a User Roles management. A SplashScreen is handly with this. There you can check the User's type, and it helps you to maintain the separation of concerns.
Now we can see that you're checkin only the session on your onCreate method, but you ain't checking the user_type. Actually you need to do the same as in the Callback of your checkLogin method but this time validating the session's variable.
if (session && user_type.contentEquals("admin")) {
Intent intent = new Intent(com.example.ilvan.gogas.Login.this, AdminActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
So you're only getting inside the MainActivity regardless of the user type.
Hope this help you! Cheers... welcome to stackoverflow!

Android Studio Sending Variables To Other Activities and Opening Activities At The Same Time

So basically this is my example
Activity A, B, and C.
Say I want to send variables from A to C, and at the same time, open activity B. I I was thinking about multiple intents, but that does not seem to work. Please help with a simple example.
"ACTIVITY A"
package com.example.munaseribrahimewallet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.view.MotionEvent;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;
public class SignUpActivity extends AppCompatActivity{
//we will use these constants later to pass the Member name and id to another activity
public static final String EXTRA_EMAIL = "com.example.munaseribrahimewallet.EXTRA_NAME";
private DatePickerDialog mDatePickerDialog;
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$");
private EditText inputEmail, inputPassword, confirmPassword,editDate; //hit option + enter if you on mac , for windows hit ctrl + enter
private Button btnSignIn, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
DatabaseReference reff;
Member member;
long maxid = 0;
String email, password, cPassword, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
reff = FirebaseDatabase.getInstance().getReference("Members");
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
confirmPassword = (EditText) findViewById(R.id.password2);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
editDate = (EditText) findViewById(R.id.editDateBirth);
reff = FirebaseDatabase.getInstance().getReference().child("Member");
reff.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
}
});
btnSignUp.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
cPassword = confirmPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(cPassword)) {
Toast.makeText(getApplicationContext(), "Confirm password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
if (!(password.matches(cPassword))) {
Toast.makeText(getApplicationContext(), "Password and Confirmation Password are not the same!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Registered successfully. Please check your email for verification", Toast.LENGTH_SHORT).show();
inputEmail.setText("");
inputPassword.setText("");
Intent intent = new Intent(SignUpActivity.this, ProfileActivity.class);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
finish();
}
}
});
}
}
});
}
});
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private boolean validateEmail() {
String emailInput = inputEmail.getText().toString().trim();
if (emailInput.isEmpty()) {
inputEmail.setError("Field can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
inputEmail.setError("Please enter a valid email address");
return false;
} else {
inputEmail.setError(null);
return true;
}
}
private boolean validatePassword() {
String passwordInput = inputPassword.getText().toString().trim();
if (passwordInput.isEmpty()) {
inputPassword.setError("Field can't be empty");
return false;
} else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
inputPassword.setError("Password too weak");
return false;
} else {
inputPassword.setError(null);
return true;
}
}
public void addMember() {
//getting the values to save
email = inputEmail.getText().toString().trim();
id = reff.push().getKey();
//checking if the value is provided
if (!TextUtils.isEmpty(email)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Contact
//Saving the Contact
reff.child(id).setValue(member);
//setting edittext to blank again
inputEmail.setText("");
inputPassword.setText("");
//displaying a success toast
Toast.makeText(this, "Member added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter a email", Toast.LENGTH_LONG).show();
}
}
private boolean updateMember(String id, String email) {
//getting the specified Contact reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(id);
//updating Contact
//Member member = new Member(id, email);
dR.setValue(member);
return true;
}
}
"ACTIVITY B"
package com.example.munaseribrahimewallet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
public class PaypalDB extends AppCompatActivity {
private Button btnPaypalLogin;
private EditText editPaypalLogin;
private TextView temail, thomeAddress, tcountry, tcompanyName, tcompanyAddress, tzipcode, tdate, tname, tpaypalEmail;
Member member;
DatabaseReference reff;
String memail, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mdate, mname, mpaypalEmail, mid;
long maxid = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paypal_db);
reff = FirebaseDatabase.getInstance().getReference("Members");
editPaypalLogin = (EditText) findViewById(R.id.editPaypalLogin);
btnPaypalLogin = (Button) findViewById(R.id.btnPaypalLogin);
temail= (TextView) findViewById(R.id.txtemail);
thomeAddress= (TextView) findViewById(R.id.txthomeaddress);
tcountry= (TextView) findViewById(R.id.txtcountry);
tcompanyName= (TextView) findViewById(R.id.txtcompanyname);
tzipcode= (TextView) findViewById(R.id.txtzipcode);
tdate= (TextView) findViewById(R.id.txtdate);
tname= (TextView) findViewById(R.id.txtname);
tcompanyAddress = (TextView) findViewById(R.id.txtcompany);
reff = FirebaseDatabase.getInstance().getReference().child("Member");
reff.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btnPaypalLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
memail = extras.getString("EXTRA_EMAIL");
mhomeAddress = extras.getString("EXTRA_HOMEADDRESS");
mcountry = extras.getString("EXTRA_SPINNERCOUNTRYTEXT");
mcompanyName = extras.getString("EXTRA_COMPANYNAME");
mcompanyAddress = extras.getString("EXTRA_COMPANYADDRESS");
mzipcode = extras.getString("EXTRA_ZIPCODE");
mdate = extras.getString("EXTRA_DATE");
mname = extras.getString("EXTRA_NAME");
mpaypalEmail = editPaypalLogin.getText().toString();
tcompanyAddress.setText(mcompanyAddress);
tname.setText(mname);
mid = reff.push().getKey();
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(mid);
reff.child(mid).setValue(member);
member = new Member(mid, memail, mdate, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mpaypalEmail, mname);
dR.setValue(member);
}
});
}
}
Try to use sharedPreference
Create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
Storing data as KEY/VALUE pair
editor.putBoolean("key_name1", true); // Saving boolean - true/false
editor.putInt("key_name2", "int value"); // Saving integer
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Get SharedPreferences data
// If value for key not exist then return second param value - In this case null
boolean userFirstLogin= pref.getBoolean("key_name1", true); // getting boolean
int pageNumber=pref.getInt("key_name2", 0); // getting Integer
float amount=pref.getFloat("key_name3", null); // getting Float
long distance=pref.getLong("key_name4", null); // getting Long
String email=pref.getString("key_name5", null); // getting String
Deleting Key value from SharedPreferences
editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Clear all data from SharedPreferences
editor.clear();
editor.commit(); // commit changes
if my solution is hard for you to understand refer This to get more details

Data from sharedpreferences incorrect when validated on login.class

Login.class
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends AppCompatActivity {
EditText Lname, Password;
TextView Regit;
Button Login, Cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Lname = (EditText) findViewById(R.id.txtLname);
Password = (EditText) findViewById(R.id.txtPassword);
Login = (Button) findViewById(R.id.btnLogin);
Cancel = (Button) findViewById(R.id.btnCancel);
Regit = (TextView) findViewById(R.id.txtRegit);
Regit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Login.this, Registration.class);
startActivity(intent);
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Lname.setText("");
Password.setText("");
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
load();
}
});
}
public void run() {
Intent x = new Intent(Login.this, MainPage.class);
startActivity(x);
}
public void LoginSuccess() {
Toast.makeText(this, "Successfully Logged in!", Toast.LENGTH_SHORT).show();
run();
}
public void load(){
final SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = pref.edit();
String value=(pref.getString("Name", Lname.getText().toString()));
String value2=(pref.getString("Password", Password.getText().toString()));
if (value.equals(Lname) & value2.equals(Password)){
LoginSuccess();
} else{
Toast.makeText(this, "Last Name or Password Incorrect or Does not Exist!", Toast.LENGTH_SHORT).show();
}
}
}
Registration.class
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Pattern;
public class Registration extends AppCompatActivity {
EditText Lname, Fname, Mname, BDate, Email, Password;
String Lnamee, Fnamee, Mnamee, Bdatee, Emails, Passwords;
TextView Login;
Button Register, Cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Lname = (EditText) findViewById(R.id.txtFamilyName);
Fname = (EditText) findViewById(R.id.txtFirstName);
Mname = (EditText) findViewById(R.id.txtMiddleName);
BDate = (EditText) findViewById(R.id.txtBDay);
Email = (EditText) findViewById(R.id.txtEMail);
Password = (EditText) findViewById(R.id.txtPassword);
Register = (Button) findViewById(R.id.btnRegister);
Cancel = (Button) findViewById(R.id.btnCancel);
Login = (TextView) findViewById(R.id.txtLogin);
Login.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(Registration.this, Login.class);
startActivity(intent);
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Lname.setText("");
Fname.setText("");
Mname.setText("");
BDate.setText("");
Email.setText("");
Password.setText("");
}
});
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
register();
}
});
}
public void register() {
initialize();
if (!validate()) {
Toast.makeText(this, "Sign-up has Failed", Toast.LENGTH_SHORT).show();
} else {
onSignUpSuccess();
}
}
public void onSignUpSuccess() {
save();
Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration.this, Login.class);
startActivity(intent);
}
public boolean validate() {
boolean valid = true;
if (Lnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+").matcher(Lnamee).matches()) {
Lname.setError("Enter letters only!");
valid = false;
}
if (Mnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+ ").matcher(Mnamee).matches()) {
Mname.setError("Enter letters only!");
valid = false;
}
if (Fnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+").matcher(Fnamee).matches()) {
Fname.setError("Enter letters only!");
valid = false;
}
if (Emails.isEmpty() || Pattern.compile("[a-zA-Z0-9]" + "\\#" + "[a-zA-Z]" + "\\." + "[a-zA-Z]").matcher(Emails).matches()){
Email.setError("Enter valid e-mail address!");
valid = false;
}
if (Passwords.isEmpty() || Passwords.length() < 8){
Password.setError("Password must be 8 characters!");
valid = false;
}
return valid;
}
public void initialize(){
Lnamee = Lname.getText().toString().trim();
Mnamee = Mname.getText().toString().trim();
Fnamee = Fname.getText().toString().trim();
Emails = Email.getText().toString().trim();
Passwords = Password.getText().toString().trim();
}
public void save() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = pref.edit();
String LastNameReg = Lname.getText().toString();
String PWReg = Password.getText().toString();
editor.putString("Name", LastNameReg);
editor.putString("Password", PWReg);
editor.commit();
}
}
The expected behavior of the program would be, from the registration: when the user enters the Family Name or Last Name(txtFamilyName) & Password(txtPassword) it will be stored in sharedpreferences, and it will be use as a data to be entered for user to login(Login.class) and enter MainPage().
During registration(Registration.class), when I entered my Family or Last Name & Password, and use it on the Login.class, it does not enter to MainPage even though the required fields are correct.
It occurs to me that you are comparing the value of an EditView object with the actual username / password strings. You also don't want to be using the Lname and Password values as "default" values. In this case, if there is no username / password saved it will always identify as logged in.
The changes made below should suffice.
public void load() {
final SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = pref.edit();
String value=(pref.getString("Name", ""));
String value2=(pref.getString("Password", ""));
if (value.equals(Lname.getText().toString()) & value2.equals(Password.getText().toString())){
LoginSuccess();
} else{
Toast.makeText(this, "Last Name or Password Incorrect or Does not Exist!", Toast.LENGTH_SHORT).show();
}
}

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to run an App with SQLite, but whenever I click on a button to enter some data this message appear
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.os.Bundle.getInt(java.lang.String)' on a null object reference
at com.example.carlos.assigmentcarlos.Register$1.onClick(Register.java:39)
This is part of my code
package com.example.carlos.assigmentcarlos;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button Login, Register, Delete, Update;
int status = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Login = (Button) findViewById(R.id.Login);
Register = (Button) findViewById(R.id.Reg);
Delete = (Button) findViewById(R.id.Delete);
Update = (Button) findViewById(R.id.Update);
Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
status = 1;
Bundle b = new Bundle();
b.putInt("status", status);
Intent i = new Intent(MainActivity.this, Register.class);
i.putExtras(b);
startActivity(i);
}
});
Register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Register.class);
startActivity(i);
}
});
Update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
status = 2;
Bundle b = new Bundle();
b.putInt("status", status);
Intent i = new Intent(MainActivity.this, Register.class);
i.putExtras(b);
startActivity(i);
}
});
Delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
status = 3;
Bundle b = new Bundle();
b.putInt("status", status);
Intent i = new Intent(MainActivity.this, Register.class);
i.putExtras(b);
startActivity(i);
}
});
}
}
Register class
package com.example.carlos.assigmentcarlos;
/**
* Created by Carlos on 22/04/2016.
*/
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends Activity {
Button Login;
EditText USERNAME,USERPASS;
String username,userpass;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
Login = (Button) findViewById(R.id.b_login);
USERNAME = (EditText) findViewById(R.id.user_name);
USERPASS = (EditText) findViewById(R.id.user_pass);
Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Bundle b = getIntent().getExtras();
int status = b.getInt("status");
if(status == 1)
{
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&& (userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success----\n Welcome "+NAME, Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(getBaseContext(), "Login Failed---- ", Toast.LENGTH_LONG).show();
finish();
}
}
else if(status == 2)
{
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&& (userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success----\n Welcome "+NAME, Toast.LENGTH_LONG).show();
Intent i = new Intent("update_filter");
Bundle BN = new Bundle();
BN.putString("user_name",NAME );
BN.putString("user_pass",userpass );
i.putExtras(BN);
startActivity(i);
finish();
}
else
{
Toast.makeText(getBaseContext(), "Login Failed---- ", Toast.LENGTH_LONG).show();
finish();
}
}
else if(status == 3)
{
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&& (userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success----\n Welcome "+NAME, Toast.LENGTH_LONG).show();
Intent i = new Intent("delete_filter");
Bundle B = new Bundle();
B.putString("user_name",NAME );
i.putExtras(B);
startActivity(i);
finish();
}
else
{
Toast.makeText(getBaseContext(), "Login Failed---- ", Toast.LENGTH_LONG).show();
finish();
}
Intent i = new Intent("delete_filter");
startActivity(i);
}
}
});
}
}
Database Operations
package com.example.carlos.assigmentcarlos;
/**
* Created by Carlos on 22/04/2016.
*/
import com.example.carlos.assigmentcarlos.tableData.TableInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract.Columns;
import android.util.Log;
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE "+TableInfo.TABLE_NAME+"("+TableInfo.USER_NAME+" TEXT,"+TableInfo.USER_PASS+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(CREATE_QUERY);
Log.d("Database operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void putInformation(DatabaseOperations dop,String name,String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableInfo.USER_NAME, name);
cv.put(TableInfo.USER_PASS, pass);
long k = SQ.insert(TableInfo.TABLE_NAME, null, cv);
Log.d("Database operations", "One raw inserted");
}
public Cursor getInformation(DatabaseOperations dop)
{
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableInfo.USER_NAME,TableInfo.USER_PASS};
Cursor CR = SQ.query(TableInfo.TABLE_NAME,coloumns, null, null, null, null, null);
return CR;
}
public Cursor getUserPass(DatabaseOperations DOP, String user)
{
SQLiteDatabase SQ = DOP.getReadableDatabase();
String selection = TableInfo.USER_NAME +" LIKE ?";
String coloumns[] = {TableInfo.USER_PASS};
String args[] = {user};
Cursor CR = SQ.query(TableInfo.TABLE_NAME, coloumns, selection, args, null, null, null);
return CR;
}
public void deleteUser(DatabaseOperations DOP, String user, String pass)
{
String selection = TableInfo.USER_NAME+ " LIKE ? AND "+TableInfo.USER_PASS +" LIKE ?";
//String coloumns[] = {TableInfo.USER_PASS};
String args[] = {user,pass};
SQLiteDatabase SQ = DOP.getWritableDatabase();
SQ.delete(TableInfo.TABLE_NAME, selection, args);
}
public void updateUserInfo(DatabaseOperations DOP, String user_name, String user_pass, String new_user_name )
{
SQLiteDatabase SQ = DOP.getWritableDatabase();
String selection = TableInfo.USER_NAME+ " LIKE ? AND "+TableInfo.USER_PASS +" LIKE ?";
String args[] = {user_name,user_pass};
ContentValues values = new ContentValues();
values.put(TableInfo.USER_NAME, new_user_name);
SQ.update(TableInfo.TABLE_NAME, values, selection, args);
}
}
In this block of code you are not passing a Bundle
Register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Register.class);
startActivity(i);
}
});
You either need to add a Bundle to the above block
Bundle b = new Bundle();
b.putInt("status", status);
Intent i = new Intent(MainActivity.this, Register.class);
i.putExtras(b);
startActivity(i);
Or account for an Intent without a Bundle.
int status;
try{
Bundle b = getIntent().getExtras();
status = b.getInt("status");
} catch(Exception ex){
status = -1; //Or some error status //
}

Android service called data from list multiple times

1.hello, I have created service for Schedule message but the problem is i have set the loop in my service method but it send the message all the message that is set on list.
2.I want to set the loop like, send message on list will be send at least ones time.
3.And the message has been sent is not send again.
//Here is my code.
//MyService class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class SchedulerMsgService extends Service {
private static final String TAG = "MyService";
private DatabaseHelper mDbHelper;
private ArrayList<schedulerDetails> myschedule = new ArrayList<schedulerDetails>();
private String phoneNo, message, sDate, curTime;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "oNsTART IS rEADY ");
mDbHelper = new DatabaseHelper(this);
final List<schedulerDetails> ScheduleList = mDbHelper.selectAllNumbers();
for (int j = 0; j < ScheduleList.size(); j++) {
myschedule.add(ScheduleList.get(j));
phoneNo = myschedule.get(j).num;
message = myschedule.get(j).textMessage;
sDate = myschedule.get(j).date;
curTime = myschedule.get(j).time;
sendSMS(phoneNo, message, sDate, curTime);
}
Toast.makeText(this, "condition Matched", Toast.LENGTH_LONG).show();
// Toast.makeText(this, "condition Not Matched",
// Toast.LENGTH_LONG).show();
}
public void sendSMS(String phoneNo, String message, String sDate,
String curTime) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic Failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "Null Service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio Off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not Delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);
}
}
If the message has been sent, then remove the number from your database or add some information in the database that the message has been sent. Then mDbHelper.selectAllNumbers() can return only the numbers that need to receive the message.

Categories

Resources