Android SQLite数据库在返回主要活动时不起作用
我正在开发应用程序,要求用户使用电话号码登录,一旦他们登录,我通过IntentPutExtra
LoginActivity中的电话号码LoginActivity
给MainActivity
工作正常,正在主要活动的布局顶部显示。 但是,当用户开始为我的一项服务(在应用程序中提供)下订单时,以及当它返回到主Activity时,用户用于登录的电话号码消失了。
我尝试在SharedPreferences
和Database
保存该电话号码,但同样的事情发生在用户回到主要活动时,存储的电话号码既不由SharedPreferences
也不由Database
。
这是我的MainActivity
代码:
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;
}
}
这是我的DataBase Handler
类: -
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();
}
}
当我从Final activity
返回MainActivity
我正在使用
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
清除堆栈。 我认为这是Clearing Stack的问题,但是在没有清除堆栈的情况下正常返回后,堆栈也会发生同样的情况,并且不显示电话号码
Tauseef你可以从LoginActivity得到你的id,密码,就像这样,MainActivity首先你可以存储你的id并传入Sharedpreference,当你输入你的详细id并通过LoginActivity就像。
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();
其次,你可以在你的MainActivity中得到这个值,就像。
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);
感谢您的支持人员。 现在我的应用程序工作正常,因为@Secret Coder说我在onRestart()
和onPause()
使用我的方法,现在我正在接收电话号码输入我的用户
上一篇: Android SQLite Database not working when returning to main activity