2012-12-02 56 views
1

當用戶在應用程序啓動時輸入它時,我從我的Main類中設置了一個ID。考慮到我將它設置在名爲GetSet.java的類中,該類也有一個方法在被調用時返回它。所以我需要這個第一類的id集合,名爲MySQLitehelper.java,這樣我就可以根據id集合檢索數據,而不是硬編碼它。這將使我的應用動態而不是靜態。這是我的代碼:在一個類中設置值並從Java中的另一個類中檢索

/---- MainActivity.java -----/

public class MainActivity extends Activity { 

EditText etGWid; 
Button OKbtn; 

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    etGWid = (EditText)findViewById(R.id.etGWID); 
    OKbtn = (Button)findViewById(R.id.OKbtn); 

    final GetSet obj_getset = new GetSet(); 
    //MySQLitehelper db = new MySQLitehelper(null); 

    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this); 
      // Create a shared preferences variable using the SharedPreferenceManager for storing GWids 

    SharedPreferences.Editor editor = app_preferences.edit(); // We also need a shared preferences editor to handle the shared preference requests 
    // Call the edit method (library function) to editor variable can edit the key, values. 

    editor.putInt("47688507", 47688507); // put in the shared preferences values of user GWids and give them a key for retrieval purposes 
    editor.putInt("1234567", 1234567); 
    editor.putInt("7654321", 7654321); 

    editor.commit(); //commit is necessary to save the shared preferences 



    OKbtn.setOnClickListener(new View.OnClickListener() { 


     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 

      String gwidCheck = etGWid.getText().toString(); //get the value user enters for GWid 

      if(app_preferences.contains(gwidCheck))  // this will check the stored shared preferences and compare with the value entered 
      { 
       Context context = getApplicationContext(); 
       CharSequence text = "Login Successfull"; 
       int duration = Toast.LENGTH_SHORT;        //If it exists, then create a toast message for success 



       //etGWid.setText(""); // make the textbox empty 
       long setid = Long.parseLong(gwidCheck); // take the string gwid and convert to long 
       obj_getset.setId(setid); // set the gwid entered 



       Toast toast = Toast.makeText(context, text, duration); 
       toast.show(); 
       intentfunction(); 
      } 
      else 
      { 
       Context context = getApplicationContext(); 
       CharSequence text = "Login Failed";      // If doesnt exist, create a toast for fail 
       int duration = Toast.LENGTH_SHORT; 

       Toast toast = Toast.makeText(context, text, duration); 
       toast.show(); 
      } 

     } 
    }); 
} 


private void intentfunction() 
{ 
    Intent intent = new Intent(this, SelectOptions.class); 
    //editText = (EditText) findViewById(R.id.editText1); 
    //editText = new EditText(this); 
    etGWid.setText(""); //set the edit text to blank 
    String message = "TestHello"; 
    intent.putExtra(EXTRA_MESSAGE, message); 
    startActivity(intent); 

} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

} 

/*-----GetSet.java----*/ 

public class GetSet { 

long gwid=0; 

public void setId(long id) 
{ 
    gwid = id; 
} 

public long getId() 
{ 
    return gwid; 
} 

} 

/--- MySQLitehelper.java ---/

public class MySQLitehelper { 

//public static final String TABLE_COMMENTS = "comments"; 
    public static final String COLUMN_ID = "GWid"; 
    public static final String COLUMN_DATE = "DateGWU"; 
    public static final String COLUMN_LOCATION = "location"; 
    public static final String COLUMN_TIME = "time"; 

    public static final String TABLE_NAME = "UPDTable"; 

    private static final String DATABASE_NAME = "UPDdb_version6"; 
    private static final int DATABASE_VERSION = 6; 

    private final Context context; 
    GetSet getset = new GetSet(); 
    public void GetIdForGwid(GetSet get) 
    { 
    getset=get; 
    } 

    // Database creation sql statement 
    private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME + 
           " (" +COLUMN_ID+ " integer," + COLUMN_DATE + " VARCHAR," + 
           COLUMN_LOCATION+" VARCHAR," +COLUMN_TIME +" VARCHAR);"; 

// private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME + 
//            " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');"; 

    private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME + " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," + 
      COLUMN_LOCATION+" ," +COLUMN_TIME +")" + 
          " Values (47688507,'DEC-07-2012','MARVIN 203','20:00');"; 



    DatabaseHelper dbhelper; 
    SQLiteDatabase db; 




public MySQLitehelper(Context ctx) 
    { 
     this.context = ctx; 
     dbhelper = new DatabaseHelper(ctx); 
    } 



private static class DatabaseHelper extends SQLiteOpenHelper { 

    public DatabaseHelper(Context context) 
    { 
     super(context,DATABASE_NAME, null,DATABASE_VERSION); 
    } 

@Override 
public void onCreate(SQLiteDatabase db) { 
    // TODO Auto-generated method stub 
    db.execSQL(DATABASE_CREATE);   //execute create table 
    db.execSQL(DATABASE_INSERT);   //execute insert query 
    db.execSQL("INSERT INTO " +TABLE_NAME + " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +")" +" Values (47688507,'DEC-22-2012','OLD MAIN','23:00');"); 
    db.execSQL("INSERT INTO " +TABLE_NAME + " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +")" +" Values (1234567,'DEC-14-2012','FUNGER','12:00');"); 
    db.execSQL("INSERT INTO " +TABLE_NAME + " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +")" +" Values (7654321,'DEC-29-2012','GELMAN','22:00');"); 
    db.execSQL("INSERT INTO " +TABLE_NAME + " (" +COLUMN_ID+ " ," + COLUMN_DATE + "," +COLUMN_LOCATION+" ," +COLUMN_TIME +")" +" Values (47688507,'DEC-12-2012','IVORY','23:00');"); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // TODO Auto-generated method stub 
    Log.w(MySQLitehelper.class.getName(), 
      "Upgrading database from version " + oldVersion + " to " 
       + newVersion + ", which will destroy all old data"); 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
     onCreate(db); 
    } 
} 


// open the DB 
public MySQLitehelper open() throws SQLException 
{ 
    System.out.println("Inside open function"); 
    db = dbhelper.getWritableDatabase(); 
    return this; 
} 

public void close() 
{ 
    dbhelper.close(); 
} 



public void insertRecord(long gwid, String date, String location, String time) 
    { 
      ContentValues initialValues = new ContentValues(); 
      initialValues.put(COLUMN_ID, gwid); 
      initialValues.put(COLUMN_DATE, date); 
      initialValues.put(COLUMN_LOCATION, location); 
      initialValues.put(COLUMN_TIME, time); 
      db.insert(TABLE_NAME, null, initialValues); 
    } 

public Cursor getAllrows()  //function to get all rows in the DB. Testing initially. 
{ 

    Cursor cur = db.rawQuery("SELECT * FROM "+TABLE_NAME, null); 
    return cur; 
} 

public Cursor getRecord() throws SQLException 
{ 
     Cursor mCursor = 
     db.query(true, TABLE_NAME, new String[] {COLUMN_ID, 
     COLUMN_DATE, COLUMN_LOCATION, COLUMN_TIME}, 
     COLUMN_ID + "= 47688507", null, null, null, null, null); //HARDCODED. Please make it dynamic 
     if (mCursor != null) 
     { 
      mCursor.moveToFirst(); 
     } 
return mCursor; 
} 

} 

我在上面的類的getRecord()方法中檢索它的底部,而不是COLUMN_ID + "= 47688507我希望從GetSet類(getId方法)中獲得設置值並將其替換爲plac e的47688507。有什麼建議麼 ?

回答

0

我想,你應該能夠使用你的實例變量obj_getset設置id與

obj_getset.setid(mCursor.COLUMN_ID)

getRecord函數然後檢索它以同樣的方式,當你需要

obj_getset.getID()

+0

setid和getID都在不同的類中。我在MainActivity中設置它。但我需要在SelectOptions.java類中獲取它。 – noobcoder

+0

我可能會錯過一些東西,但是如果您將它設置爲與您調用intent()函數相同的活動,爲什麼不能將id作爲參數傳遞給該函數並將其作爲額外的意圖發送? – codeMagic

1
  • 使用全局單例存儲和檢索data。當你這樣做時,確保單例不包含對你的活動或上下文的引用。
  • 由於mysqlitehelper具有對上下文的引用,因此您還可以從SharedPreferences中檢索持久數據。
  • -
3

閱讀「單例模式」,這是一種創建持久對象以保存信息的方法。

但是,請記住,一旦您的活動調用了onPause(),系統就可以完全銷燬您的應用程序,並在以後重新構建。這意味着即使是單例類也不能保證您的數據將在您的應用程序重新啓動時存在。您必須始終準備好從您的onCreate()方法中的永久存儲中恢復狀態。

以下是我如何使用單例類實現全局首選項持有者:簡而言之,在任何有上下文的地方,都可以調用Prefs.getPrefs()來獲取首選項對象。在第一次調用時,它將從持久存儲中讀取首選項。在所有後續調用中,它只是返回指向已經加載的對象的指針。如果您的應用程序被系統中止並重新啓動,則getPrefs()會根據需要無縫地重新讀取首選項。

/** 
* This is a singleton class to hold preferences. 
*/ 
public class Prefs { 
    private static volatile Prefs instance = null; 

    // The values held by this class 
    String identity = null; 
    String apiUrl = "http://example.com/cgi-bin/api"; 
    int interval = 3600; // when there's no activity 

    /** 
    * Return the single instance of this class, creating it 
    * if necessary. This method is thread-safe. 
    */ 
    public static Prefs getPrefs(Context ctx) { 
     if (instance == null) { 
      synchronized(Prefs.class) { 
       if (instance == null) { 
        instance = new Prefs(); 
        instance.readPrefs(ctx); 
       } 
      } 
     } 
     return instance; 
    } 

    /** 
    * Re-read all preferences (you never need to call this explicitly) 
    */ 
    private void readPrefs(Context ctx) { 
     try { 
      SharedPreferences sp = 
       PreferenceManager.getDefaultSharedPreferences(ctx); 
      identity = sp.getString("identity", identity); 
      apiUrl = sp.getString("apiUrl", apiUrl); 
      interval = sp.getInt("interval", interval); 
     } catch (Exception e) { 
      Log.e(TAG, "exception reading preferences: " + e, e); 
      // TODO: report it 
     } 
    } 

    /** 
    * Save preferences; you can call this from onPause() 
    */ 
    public void savePrefs(Context ctx) { 
     try { 
      SharedPreferences.Editor sp = 
       PreferenceManager.getDefaultSharedPreferences(ctx).edit(); 
      sp.putString("identity", identity); 
      sp.putString("apiUrl", apiUrl); 
      sp.putInt("interval", interval); 
      sp.commit(); 
     } catch (Exception e) { 
      Log.e(TAG, "exception reading preferences: " + e, e); 
      // TODO: report it 
     } 
    } 

    /** 
    * Save preferences to a bundle. You don't really need to implement 
    * this, but it can make start-up go faster. 
    * Call this from onSaveInstanceState() 
    */ 
    public void onSaveInstanceState(Bundle state) { 
     state.putString("identity", identity); 
     state.putString("apiUrl", apiUrl); 
     state.putInt("interval", interval); 
    } 

    /** 
    * Recall preferences from a bundle. You don't really need to implement 
    * this, but it can make start-up go faster. 
    * Call this from onCreate() 
    */ 
    public void restoreInstanceState(Bundle state) { 
     identity = state.getString("identity"); 
     apiUrl = state.getString("apiUrl"); 
     interval = state.getInt("interval"); 
    } 
} 
+0

我在我的應用程序中使用類似的實現。很高興知道我不是唯一得出這個結論的人。 –

相關問題