2013-03-06 54 views
-2

我想將一個變量傳遞給我的DBConnector.Java,我正在執行一個SQLite查詢,但我不知道該怎麼做,需要一些幫助。Android - 將變量傳遞給另一個活動

public void onItemSelected(AdapterView<?> parent, View view, int position,long id) 
    { 
       spinnerRub.setSelection(position);  
      myRub = (String) spinnerRub.getSelectedItem(); 

    } 

現在我想myRub傳遞給我的DBConnector.Java在那裏我有:

public List<String> getAllCapabilities1() 
{    

List<String> Caps = new ArrayList<String>(); 

       String selectQuery = "SELECT Cap_Name FROM capability where Rub_ID = 'myRub'"; 

      SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase(); 
      //Cursor cursor = database.rawQuery(selectQuery, null); 
      Cursor cursor = database.rawQuery(selectQuery, null); 
      // looping through all rows and adding to list 
      if (cursor.moveToFirst()) 
      { 
       do 
       { 
        Caps.add(cursor.getString(0)); 
       } while (cursor.moveToNext()); 
      } 

      // closing connection 
      cursor.close(); 
      database.close(); 

      // returning lables 
      return Caps; 
     } 

但我在努力做到這一點,需要幫助。

+1

使用共享首選項或意圖傳遞數據 – 2013-03-06 10:54:45

回答

4

使用意向來傳遞您的數據:

i.putExtra("myRub",myRub); 

iIntent對象。

使用

Bundle extras = getIntent().getExtras(); 
String a = extras.getString("myRub"); 
+0

感謝您的答案,但我在DBConnector.java中遇到此錯誤 「方法getExtras()未定義類型對象」 請問您爲什麼會出現此錯誤?謝謝。 – Trojan 2013-03-06 11:08:59

+1

什麼是DBConnector.java?它是什麼擴展?如果它是你寫的課程?你不能只是創建一個接受字符串的公共方法嗎? – 2013-03-06 11:16:20

+0

@DeanWild它只是一個類,並沒有擴展,我的方法是一個公共方法,你可以看到,但我不知道我到底錯過了什麼。 – Trojan 2013-03-06 11:19:26

1

在dbconnetion.java文件修改這一點,並通過方法或sharedpref傳遞myrub

String selectQuery = "SELECT Cap_Name FROM capability where Rub_ID = '"+myRub+"'"; 

兩人之間活動

Intent i = new Intent(Intent.ACTION_VIEW); 
i.putExtra("myrub", "This value one for ActivityTwo "); 
startActivity(i); 
+0

感謝您的更正,但我也想知道通過這兩個活動之間的值。 – Trojan 2013-03-06 10:59:08

-1

使用意圖來傳遞

Intent intent = new Intent(yourActivity.this, DBConnector.class); 
    intent.putExtra("myRub", myRub); 
    startActivity(intent); 

活動之間的數據,並使用getIntent().getExtras()取回

+0

-1調用一個活動,他只是要求傳遞一個值 – 2014-07-13 05:41:58

+0

@穆罕默德法拉茲提及「感謝您的更正,但我也想知道要傳遞這兩個活動之間的值。「評論的答案是http:// stackoverflow。com/a/15245448/1273336,我已經編寫了代碼來在活動之間傳遞數據並進行檢索。無論如何,我在回答時也考慮過這些評論:) – 2014-07-14 11:13:15

0

這裏是將數據傳遞到一個樣品檢索它在其他活動活動和檢索

Intent intent = new Intent(); 
intent.setClass(this, New.class); 

Bundle b = new Bundle(); 
b.putInt("action", nResponse); // integer value 
b.putString("homename", sHomeName); // string value 
intent.putExtras(b); 
startActivity(intent); 
在你3210

new.class的onCreate方法請按照

Bundle b = getIntent().getExtras(); 
if(b != null){ 
    nAction = b.getInt("action"); 
    sHomeName = b.getString("homename"); 
} 
0

在你的活動(IM假設你有dbConnector參考):

spinnerRub.setSelection(position);  
myRub = (String) spinnerRub.getSelectedItem(); 
dbConnector.setMyRub(myRub); 

在DBConnector.java

public void setMyRub(String myRub){ 
    // do what you need to do with myRub 
} 
相關問題