Android SQLite Database not working when returning to main activity
I'm working on app that request user to use phone number to login and once they logged in, I'm passing that phone number from LoginActivity
to MainActivity
via IntentPutExtra
evrything is working fine number is showing on top of the layout in Main activity. But when user starts making order for one of my service (provided in the app) and when it comes back to main Activity the phone number that users use to login is gone.
I tried to save that phone number in SharedPreferences
and Database
too but the same thing happens when user comes back to Main Activity the stored phone number is not displaying neither by SharedPreferences
nor by Database
.
Here is my MainActivity
code:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SessionManager manager;
TextView tvHinum;
private Button btBikeServiceBook, btCarServiceBook;
public SharedPreferences user_details;
public static final String USER_DETAILS = "User_Details";
private static final String TAG = "MainActivity";
private static String USERNAME= "";
public String passUserName , UserMob ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
USERNAME = intent.getStringExtra(LoginActivity.USER_NAME);
passUserName = intent.getStringExtra(LoginActivity.USER_NAME);
// Session Manager use to check first login
manager = new SessionManager();
/*
USERNAME = passUserName;
user_details = getSharedPreferences(USER_DETAILS, MODE_WORLD_READABLE);
// Writing data to SharedPreferences
SharedPreferences.Editor editor = user_details.edit();
editor.putString("key",USERNAME);
editor.apply();
// Reading from SharedPreferences
String value = user_details.getString("key","");
Log.d(TAG, value);
*/
Log.d("Insert: ", "Inserting ..");
DatabaseHandler db = new DatabaseHandler(this);
db.addContact(new Contact(passUserName, ""));
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
UserMob = cn.getName();
}
btBikeServiceBook = (Button)findViewById(R.id.btBookBike);
btBikeServiceBook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BikeMakeModelActivity.class);
startActivity(intent);
}
});
btCarServiceBook = (Button)findViewById(R.id.btBookCar);
btCarServiceBook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intntnt = new Intent(MainActivity.this, CarMakeModelActivity.class);
startActivity(intntnt);
}
});
tvHinum = (TextView) findViewById(R.id.tvHiUserNumber);
tvHinum.setText(UserMob);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
this.finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_logout) {
manager.setPreferences(MainActivity.this, "status", "0");
Intent intent= new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is My DataBase Handler
Class:-
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
When I'm returning from Final activity
to MainActivity
I'm using
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
to clear stack. I thought this is the problem with Clearing Stack but after returning normally without clearing Stack same thing happens and no phone number displayed.
Tauseef You can get your id, password from LoginActivity to MainActivity like this , First you can store your id and pass in Sharedpreference when you enter your detail id and pass in LoginActivity like as.
strId = edtEmail.getText().toString().trim();
strPassword = edtPassword.getText().toString();
SharedPreferences preferences = getApplicationContext().getApplicationContext().getSharedPreferences("session", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("id", strId);
editor.putString("pass", strPassword);
editor.commit();
Second, then you can just get this value in your MainActivity like as.
SharedPreferences preferences = getApplicationContext().getApplicationContext().getSharedPreferences("session", Context.MODE_PRIVATE);
String strId = preferences.getString("id", "");
String strPass = preferences.getString("pass", "");
Log.e("Log", "Id---" + strId);
Log.e("Log", "Pass---" + strPass);
Thanks for your support guys. Now my app is working fine as @Secret Coder said i'm using my methods in onRestart()
and onPause()
and now I'm receiving the Phone Number Entered my user
上一篇: 查询Android数据库是否存在!