2017-04-17 113 views
0

我想我已經從關於如何做到這一點的想法用盡。我正在建立和TODO應用程序與註冊和登錄功能。一旦用戶登錄,可以在SQLite(現在)中創建新的待辦事項任務,稍後我想刪除並重命名待辦事項。難以存儲共享首選項值爲SQLIte在Android中,並存儲空值

這是我用SQliteHelper創建的DB類。

public class DatabaseHelper extends SQLiteOpenHelper { 


// Database Version 
private static final int DATABASE_VERSION = 1; 

// Database Name 
private static final String DATABASE_NAME = "UserManager.db"; 

// User table name 
private static final String TABLE_USER = "user"; 

// User Table Columns names 
private static final String COLUMN_USER_ID = "user_id"; 
private static final String COLUMN_USER_NAME = "user_name"; 
private static final String COLUMN_USER_EMAIL = "user_email"; 
private static final String COLUMN_USER_PASSWORD = "user_password"; 

//Table mToDo task name 
private final static String mTODO = "Todos"; 

//Todos table columns names 
private final static String TASK_ID = "task_Id"; //autoincrement 
private final static String user_Id = "userId"; 
private final static String TITLE = "title"; 
private final static String CONTENT = "content"; 

// create table sql query 
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "(" 
     + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 
COLUMN_USER_NAME + " TEXT," 
     + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + 
")"; 

private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "(" 
     + TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL," 
     + TITLE + " TEXT," + CONTENT + " TEXT" + ")"; 

// drop table sql query 
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER; 

public DatabaseHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
//  this.ctx = context; 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL(CREATE_USER_TABLE); 
    db.execSQL(CREATE_mTODO_TABLE); 

} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

    //Drop User Table if exist 
    db.execSQL(DROP_USER_TABLE); 


    // Create tables again 
    onCreate(db); 

} 

添加新的任務以第二臺

public void add(ToDo todoTask) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
//  SharedPreferences sp = PreferenceManager 
//    .getDefaultSharedPreferences(ctx); 
//  String d = sp.toString(); 

ContentValues values = new ContentValues(); 
    values.put(TITLE, todoTask.getTitle()); 
    values.put(CONTENT, todoTask.getContent()); 

//  values.put(user_Id,todoTask.getUserID(d)); 


// Inserting Row 
    db.insert(mTODO, null, values); 
    db.close(); 
} 

ToDo.java

public class ToDo { 

private int id; 
private String userID; 
private String title; 
private String content; 

public ToDo(String content, int id, String title, String userID) { 
    this.content = content; 
    this.id = id; 
    this.title = title; 
    this.userID = userID; 
} 

public ToDo(String content, String title, String userID) { 
    this.content = content; 
    this.title = title; 
    this.userID = userID; 
} 

public ToDo() { 
} 

public String getContent() { 
    return content; 
} 

public void setContent(String content) { 
    this.content = content; 
} 

public int getId(String name) { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public String getTitle() { 
    return title; 
} 

public void setTitle(String title) { 
    this.title = title; 
} 

public String getUserID(String userID) { 
    return userID; 
} 

public void setUserID(String userID) { 
    this.userID = userID; 
} 
} 

添加活動類具有輸入和添加方法

public class addTask extends AppCompatActivity { 


private EditText titleUser; 
private EditText contentDesc; 
private DatabaseHelper db; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_add_task); 
    Button btnAdd = (Button) findViewById(R.id.addToDo); 
    titleUser = (EditText) findViewById(R.id.titleID); 
    contentDesc = (EditText) findViewById(R.id.contentDescId); 
    db = new DatabaseHelper(this); 
    btnAdd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
       AddItem(); 
     } 


    }); 

} 



private void AddItem() { 
    ToDo todo = new ToDo(); 
    todo.setTitle(titleUser.getText().toString().trim()); 
    todo.setContent(contentDesc.getText().toString().trim()); 
    db.add(todo); 
    finish(); 
} 

時記錄的,我把該用戶ID共享偏好 在我的第二個表中的當前用戶我有這樣的事情

task_Id user_id title content 
1  null Eat  go to Mc 

user_id是空在這裏,我不知道爲什麼

我想是這樣的

task_Id user_id title content 
1  2 Eat  go to Mc 

user_id-應該是哪個用戶ID作出待辦事項

+0

的IntelliJ阿米亞·,因爲沒有工作,我測試的是讓我評論 – Lwq

回答

1

假設您已經知道如何從共享首選項中存儲和獲取用戶標識。

在你addTask活動,添加:

private String userId; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 
    userId = sharedPreference.getString("USER_ID",null); 
    ... 
} 

addItem()添加:

private void AddItem() { 
    ... 
    todo.setUserId(userId); 
    ... 
} 

在DB add()使用這樣的:

public void add(ToDo todoTask) { 
    ... 
    values.put(USERID, todoTask.getUserId()); 
    ... 
} 

OR:

另一種方法是直接從DB類獲取值,如果您確定不會爲其他用戶插入任務。

public void add(ToDo todoTask) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx); 
    String d = sp.toString(); 

    ContentValues values = new ContentValues(); 
    values.put(TITLE, todoTask.getTitle()); 
    values.put(CONTENT, todoTask.getContent()); 
    values.put(user_Id,todoTask.getUserID(d)); 

    db.insert(mTODO, null, values); 
    db.close(); 
} 

並在構造函數中保存上下文以供進一步使用。

private Context ctx; 

public DatabaseHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    this.ctx = context; 
} 
+0

它的工作謝謝 – Lwq

+0

我需要在我的add方法和db聲明SharedPrerences? – Lwq

+0

不,你不會!我的第一個答案就是你所需要的,第二個部分只是因爲我注意到了代碼中的一些註釋行,但將邏輯放在db控制器之外,這在我看來是最佳實踐。 –

0

您正在使用user_id創建ToDo表。而refrenced靜態字符串是用戶ID:因此,在數據庫中輸入時,它會空默認

//Table mToDo task name 
private final static String mTODO = "Todos"; 

//Todos table columns names 
private final static String TASK_ID = "task_Id"; 
private final static String user_Id = "userId"; //<----Wrong Here 
private final static String TITLE = "title"; 
private final static String CONTENT = "content"; 

private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "(" 
    + TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL," 
    + TITLE + " TEXT," + CONTENT + " TEXT" + ")"; 

而且這裏是你更多的東西,只要你必須提供的用戶ID值到外地。以下是一些示例如何操作

private static final String TAG = "DB_HANDLER"; 

private static final int DATABASE_VERSION = 15; 
private static final String DATABASE_NAME = "ElmexContactsManager.db"; 

/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/ 
private static final String TABLE_BIZ_SEGMENT = "BizSegment"; 

/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId"; 
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId"; 
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment"; 
/*04*/private static final String KEY_ADDED_ON = "AddedOn"; 
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn"; 

    /*-------------------------------------------BIZ_SEGMENT----------------------------------------*/ 
    String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "(" 
    /*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," 
    /*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER," 
    /*03*/ + KEY_BIZ_SEGMENT + " TEXT," 
    /*04*/ + KEY_ADDED_ON + " TEXT," 
    /*05*/ + KEY_UPDATED_ON + " TEXT" 
      + ")"; 

public ContactDatabaseHandler(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    //3rd argument to be passed is CursorFactory instance 
} 


@Override 
public void onCreate(SQLiteDatabase sqLiteDatabase) { try { 
     sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT); 
     sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE); 
     sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE); 
     sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY); 
     sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION); 
     sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK); 
     sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER); 
     sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
    Log.d(TAG, "Table Craeted "); 
} 
@Override 
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { 
    // Drop older table if existed 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER); 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET); 
    // Create tables again 
    onCreate(sqLiteDatabase); 
    Log.d(TAG, "Table Udgraded to Version :" + i1); 
} 

/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/ 
public void addBizSegment(BizSegment bizSegment) { 
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); 
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    ContentValues values = new ContentValues(); 
    values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId()); 
    values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment()); 
    values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn())); 
    values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn())); 
    // Inserting Row 
    sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values); 
    //2nd argument is String containing nullColumnHack 
    sqLiteDatabase.close(); // Closing database connection 
} 

public void updateBizSegment(BizSegment bizSegment) { 
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); 
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    ContentValues values = new ContentValues(); 
    //values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId()); 
    values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment()); 
    values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn())); 
    values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn())); 
    // Inserting Row 
    sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())}); 
    //2nd argument is String containing nullColumnHack 
    sqLiteDatabase.close(); // Closing database connection 
} 

public List<BizSegment> getBizSegmentAll() { 
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); 
    List<BizSegment> bizSegmentList = new ArrayList<BizSegment>(); 
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    // Select All Query 
    String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT; 

    Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null); 

    if (cursor.moveToFirst()) { 
     do { 
      try { 
       BizSegment bizSegment = new BizSegment(cursor.getInt(0), 
         cursor.getInt(1), 
         cursor.getString(2), 
         df.parse(cursor.getString(3)), 
         df.parse(cursor.getString(4))); 
       bizSegmentList.add(bizSegment); 
      } catch (ParseException e) { 
       e.printStackTrace(); 
      } 

     } while (cursor.moveToNext()); 
    } 
    cursor.close(); 
    sqLiteDatabase.close(); 
    //2nd argument is String containing nullColumnHack 
    return bizSegmentList; 
} 

public void deleteBizSegment(BizSegment bizSegment) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?", 
      new String[]{String.valueOf(bizSegment.getBizSegmentId())}); 
    db.close(); 
} 

其他方法是使用適用於有限數據的共享首選項。它不提供任何關係。我用它來存儲基本的用戶相關數據。不適用於複雜/關係型大數據。對於那個Sqlite是首選。

public class AppPreference { 

SharedPreferences pref; 
SharedPreferences.Editor edit; 

/** 
* @param clientMaster object to set preference 
* @param context  Context of call 
*/ 
public void putPreference(ClientMaster clientMaster, Context context) { 

    pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE); 
    edit = pref.edit(); 

    edit.putInt("ClientId", clientMaster.getClientId()); 
    edit.putString("FirstName", clientMaster.getFirstName()); 
    edit.putString("LastName", clientMaster.getLastName()); 
    edit.putString("Mobile", clientMaster.getMobile()); 
    edit.putInt("PincodeId", clientMaster.getPincodeId()); 
    edit.putString("Email", clientMaster.getEmail()); 
    edit.putString("Password", clientMaster.getPassword()); 
    edit.putString("MembershipCode", clientMaster.getMembershipCode()); 
    edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString()); 
    edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString()); 
    edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString()); 
    edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode()); 
    edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID()); 
    edit.putInt("ReferredByID", clientMaster.getReferredByID()); 
    //edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString()); 
    edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode()); 
    edit.putString("AddedOn", clientMaster.getAddedOn().toString()); 
    //edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString()); 
    edit.putBoolean("Login", true); 
    edit.putBoolean("Skip", false); 
    edit.commit(); 
} 

/** 
* 
* @param appLanguage 
* @param context 
*/ 
public void putLanguagePreference(String appLanguage, Context context) { 

    pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE); 
    edit = pref.edit(); 
    edit.putString("AppLanguage", appLanguage); 
    edit.commit(); 
} 

/** 
* To clear All Object preference & Login False 
* 
* @param context Context call 
*/ 
public void clearPreference(Context context) { 
    pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE); 
    edit = pref.edit(); 

    edit.clear(); 

    edit.putBoolean("Login", false); 
    edit.commit(); 

} 

/** 
* @param InstanceId Instance Id 
* @param context 
*/ 
public void putPreferenceInstance(String InstanceId, Context context) { 

    pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE); 
    edit = pref.edit(); 
    edit.putString("InstanceId", InstanceId); 
    edit.commit(); 
} 

}

+0

你有什麼建議我改變,我不太確定..很抱歉,我是初學者 – Lwq

+0

你必須瞭解Shared Preference和Sqlite的用法和區別。您的原因)在用戶ID是用於使用錯誤的字符串值。 –

+0

用於存儲基本值共享首選項是很好的。但是,當使用更詳細的SQL關係數據庫(您正在使用的Sqlite)適用於有大量數據的情況。我的代碼與SQLite有關 –