Android - 将变量传递给另一个活动

时间:2013-03-06 10:53:55

标签: android

我想将一个变量传递给我正在执行SQLite查询的DBConnector.Java,但我不知道该怎么做并需要一些帮助。

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;
        }   

但我正在努力做到这一点并需要帮助。

5 个答案:

答案 0 :(得分:4)

使用Intent传递数据:

  i.putExtra("myRub",myRub);

其中iIntent对象。

使用

在其他活动中检索它
Bundle extras = getIntent().getExtras();
String a = extras.getString("myRub");

答案 1 :(得分:1)

在dbconnetion.java文件中修改它,并通过method或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);

答案 2 :(得分: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);

你在new.class的oncreate方法请按照

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

答案 3 :(得分:0)

在您的活动中(假设您有对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
}

答案 4 :(得分:-1)

使用意图在活动之间传递数据

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

并使用getIntent().getExtras()将其取回