簡體   English   中英

如何將整數傳遞給類的實例並使用它來調用另一個類的方法?

[英]How do I pass an integer to an instance of a class and use it to call the method of another class?

這是活動 1,它是一個列表視圖。 當用戶單擊一個項目時,我希望單擊該項目以啟動一個類的實例並將一個 int 值傳遞給它,該值稍后將在開關中使用。

       @Override
    public void onItemClick(AdapterView<?> adapter, View view,
                int position, long id) {


    switch(position){

   case 0:


       Intent g = new Intent(books.this, SpecificBook.class);
       Bundle b = new Bundle();
       b.putInt("dt", 0);
       g.putExtras(b);
       books.this.startActivity(g);
       break;

    case 1: 
        Intent ex = new Intent(books.this, SpecificBook.class);
       Bundle b1 = new Bundle();
       b1.putInt("dt", 1);
       ex.putExtras(b1);
       books.this.startActivity(ex);
      break;

      //etc.

這是活動 2,它應該檢索 int 值並從數據庫幫助程序類調用適當的方法。

      public class SpecificBook extends Activity {

       private DatabaseHelper Adapter;

Intent myLocalIntent = getIntent();
 Bundle myBundle = myLocalIntent.getExtras();
  int dt = myBundle.getInt("dt");

 @SuppressWarnings("deprecation")
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
  setContentView(R.layout.listy);


ListView lv = (ListView)findViewById(R.id.listview);     
 Adapter = new DatabaseHelper(this);
 Adapter.open();    
 Cursor cursor = null;


switch(dt){
 case 0:cursor = DatabaseHelper.getbook1Data(); break;
 case 1:cursor = DatabaseHelper.getbook2Data(); break;
  //etc.
}

startManagingCursor(cursor);

等等。

數據庫方法是查詢。 基本上,我希望書籍類 listview 中的每個項目根據所選項目運行它自己的查詢並顯示結果。 我收到“找不到源”和運行時異常錯誤。 我哪里錯了? 有沒有更好的方法來解決這個問題?

我已經嘗試過“getter 和 setter”方式無濟於事。 我也在意圖的實例上嘗試了“putextra”方法,但沒有奏效。

最早可以訪問 Intent 的是onCreate()

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listy);

    Intent myLocalIntent = getIntent();
    Bundle myBundle = myLocalIntent.getExtras();
    int dt = myBundle.getInt("dt");

您應該檢查 Intent 或 Bundle 是否為空,如果您只想要 Intent 中的一項,則可以使用:

Intent myLocalIntent = getIntent();
if(myLocalIntent != null) {
    int dt = myLocalIntent.getIntExtra("dt", -1); // -1 is an arbitrary default value
}

最后,你不需要創建一個新的 Bundle 來在 Intent 中傳遞值,看起來你只是想傳遞position ......所以你可以大大縮短你的onItemClick()方法:

@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
    Intent g = new Intent(books.this, SpecificBook.class);
    g.putInt("dt", position);
    books.this.startActivity(g);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM