2

これがリストビューであるアクティビティ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);

データベース メソッドはクエリです。基本的に、ブッククラスのリストビューの各アイテムが、選択されたアイテムに基づいて独自のクエリを実行し、結果を表示するようにします。「ソースが見つかりません」とランタイム例外エラーが発生します。どこが間違っていますか?これについてもっと良い方法はありますか?

私はすでに「ゲッターとセッター」の方法を無駄にしようとしました。インテントのインスタンスで「putextra」メソッドも試しましたが、うまくいきませんでした。

4

1 に答える 1

2

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 が null かどうかを確認する必要があります。また、Intent から 1 つのアイテムのみが必要な場合は、次を使用できます。

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

最後に、Intent で値を渡すために新しい Bundle を作成する必要はありません。単に渡したいだけのように見えます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);
}
于 2012-11-26T04:56:17.800 に答える