2013-02-20 65 views
0

我有這個代碼需要從用戶的輸入,我基本上想從用戶的小通訊錄應用程序獲取名稱和電話號碼。當用戶在的EditText字段中輸入數據,我從「SQLiteOpenHelper」活動之間共享,第一類擴展活動,但其他不需要

提取數據並做this--

 String _name,_phone; 
     _name=name.getText().toString(); 
     _phone=phone.getText().toString(); 
     Intent in = new Intent(this, DatabaseHandler.class); 
     in.putExtra("name", _name); 
     in.putExtra("phone", _phone); 
     startActivity(in); 

,但其他類不是從Activity類繼承,但實際上

公共類數據庫處理器擴展SQLiteOpenHelper

因此該方法

 getIntent().getExtras().get("name");
won't work, may be because the class isn't inherited from the Activity or something else. So, how can I share the data from the first activity to the second activity called "DatabaseHandler"

+0

意圖用於不在java類之間的活動之間的導航 – Pragnani 2013-02-20 07:29:49

+0

你的問題已經在這裏解答:http://stackoverflow.com/questions/14937410/how-to-use-getintent-in-a-class-that-does-not-extend-activity/14937577#14937577 – 2013-02-20 07:32:58

+0

你能標記一個答案。正確的如果你的問題已經解決,所以它不是沒有答案? TNKS。 – lokoko 2013-02-20 09:02:25

回答

0

you can use two technique: 1.take help of an Application類。或者2。獲得SharedPreference的幫助。

我要講述第二種方法。因爲它很容易使用。

SQLiteOpenHelper類調​​用DatabaseHandler寫此之前:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context); 
SharedPreferences.Editor editor = prefs.edit(); 
editor.putString("username", your_username); 
editor.putInt("password", your_password); 
editor.commit(); 

現在稱之爲DatabaseHandler,還通過_context

現在

DatabaseHandler類寫:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
String username = prefs.getString("username"); 
String password = prefs.getInt("password"); 
0

Instead of using intent why don't you use shared preferences for put whatever values you want in it, so that you can get anywhere in your app need not that should be an activity compulsory just pass context to that class in order to use shared preferences.

+1

,如果只需要getIntent(),那麼只有在活動不是JAVA類的情況下才有可能。爲此,您必須在活動中檢索該值並將該值傳遞給相應的JAVA類。 – Narendra 2013-02-20 07:41:36

+1

您可以將上下文從activity傳遞到該類,並且您可以使用this.getSharedPreference()。 – Narendra 2013-02-20 07:57:48

+2

這是我的DatabaseHelper類不是一個活動,我已經通過從調用活動傳遞上下文來使用共享首選項...'SharedPreferences Pref; \t Pref = myContext.getSharedPreferences(「SessionManagement」,0); // 0 - 用於私人模式 \t SharedPreferences.Editor editor = Pref.edit(); \t editor.putString(「UserId」,mCursor.getString(mCursor.getColumnIndex(「UserId」)));' – Narendra 2013-02-20 08:09:01

0

廣東話你只需要使用getter和製片人的一個實例來獲得價值?喜歡的東西

Producer.java

public String getName() { 
    return username; 
} 

public String getPwd() { 
    return password; 
} 

,並在消費類使用這些,就像這樣:

Consumer.java

Producer producer = new Producer(); 
producer.getName(); 
producer.getPwd(); 

您也可以參考How to use getIntent() in a class that does not extend Activity?