单击ListView中的项目时,从数据库获取项目的ID

时间:2018-06-13 10:24:30

标签: java android sqlite

我是android的新手,在我的应用程序中,当我点击listview项目时,我需要从数据库获取id,并且我使用此id在第二个活动中从数据库中检索数据。但是我无法从listview获得id (Listview在主要活动中)

我的MainActivity - 在我的数据库的列表视图中显示数据

public class test extends AppCompatActivity {
ImageButton btnadd;
SQLiteDatabase sqLiteDatabase;
DatabaseOpenHelper databaseHelper;
TextView yekuntxt;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        this.listView = (ListView) findViewById(R.id.listView);
        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
        databaseAccess.open();
        final List<String> costumer_data = databaseAccess.getData();
        databaseAccess.close();
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, costumer_data);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                {
                   View view = getLayoutInflater().inflate(R.layout.arrayadapter,null);

                    String Id = listView.getItemAtPosition(position).toString();
                    Intent i =new Intent(test.this, activity_daxilet.class);
                    i.putExtra("ID", position);
                    startActivity(i);

                }

            }
        });

我的数据库访问

public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;

private DatabaseAccess(Context context) {
    this.openHelper = new DatabaseOpenHelper(context);
}

public static DatabaseAccess getInstance(Context context) {
    if (instance == null) {
        instance = new DatabaseAccess(context);
    }
    return instance;
}
public void open() {
    this.database = openHelper.getWritableDatabase();
}
public void close() {
    if (database != null) {
        this.database.close();
    }
}

public List<String> getData() {
    List<String> list = new ArrayList<>();
    Cursor cursor = database.rawQuery("SELECT AD,SOYAD FROM costumer_data", null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        list.add(cursor.getString(0)+ " " + cursor.getString(1));

        cursor.moveToNext();
    }
    cursor.close();
    return list;

我的第二项活动

public class activity_daxilet extends AppCompatActivity {
TextView ad,medaxil,mexaric;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_daxilet);



    Bundle bundle = getIntent().getExtras();
    if (bundle !=null){
        ad.setText("@position");
    }

}

3 个答案:

答案 0 :(得分:1)

使用ListAdapter的第3个参数位置不等于id,尤其是在已删除行的情况下。

最简单的方法是使用游标适配器,在这种情况下,id将是传递给onItemClickListener的第4个参数。 SimpleCursorAdapter可能就足够了。

要转换为使用SimpleCursorAdapter,请: -

  1. 向DatabaseAccess.java添加一个方法以返回Cursor(或替换getData方法),例如。
  2. : -

    public Cursor getDataAsCursor() {
        String[] columns = new String[]{"AD","SOYAD","rowid AS " + BaseColumns._ID};
        return this.database.query(
                "costumer_data",
                columns,
                null,null,null,null,null
        );
    }
    
    • 请注意,您是否已定义id列或其名称是不明确的。 Cursor适配器需要名为 _id 的列,BaseColumns._ID解析为 _id ,因此上面的用法。
      • 使用了查询便捷方法而不是rawQuery方法,虽然它可能看起来更复杂,但建议使用rawQuery。

    1. FOR TESTING向DatabaseAccess.java添加方法,允许添加数据
    2. : -

      public long addRow(String ad, String soyad) {
          ContentValues cv = new ContentValues();
          cv.put("AD",ad);
          cv.put("SOYAD",soyad);
          return this.database.insert("costumer_data",null,cv);
      }
      
      • 请注意,如果您已拥有数据或具有等效方法,则可能不需要此

      1. 修改MainActivity
      2. : -

        public class test extends AppCompatActivity {
            ImageButton btnadd; //??
            SQLiteDatabase sqLiteDatabase; // NOT NEEDED
            DatabaseOpenHelper databaseHelper; // NOT NEEDED
            TextView yekuntxt; //??
            private ListView listView;
            SimpleCursorAdapter adapter; // ADDED
            Cursor cursor; // ADDED
            DatabaseAccess databaseAccess; // ADDED
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_test);
        
                this.listView = (ListView) findViewById(R.id.listView);
                databaseAccess = DatabaseAccess.getInstance(this); // Changed to use class variable
                databaseAccess.open();
                addSomeData(); // <<<< ADDED for testing (adds some data to the table (4 rows as below))
                cursor = databaseAccess.getDataAsCursor(); // ADDED
                //final List<String> costumer_data = databaseAccess.getData(); // REMOVED
                //databaseAccess.close(); // <<<<<<<<<< MUST NOT CLOSE DB WHEN using Cursor (see onDestory method)
                adapter = new SimpleCursorAdapter(
                        this,
                        android.R.layout.simple_list_item_2, // (show AD and SOYAD seprately)
                        cursor, //<<<< The cursor used for the source data of the ListView
                        new String[]{"AD","SOYAD"}, // The columns FROM which to get the data
                        new int[]{android.R.id.text1, // The respective views TO which the data is placed
                                android.R.id.text2},
                        0
                );
                listView.setAdapter(adapter);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                        {
                            Intent i = new Intent(test.this, activity_daxilet.class);
                            i.putExtra("ID", id);
                            startActivity(i);
                        }
                    }
                });
            }
        
            //<<<<<<<<<< Added to close the Cursor  and then database when done with it
            @Override
            protected void onDestroy() {
                cursor.close();
                databaseAccess.close();
                super.onDestroy();
            }
        
            //<<<<<<<<<< Added to load some data for testing
            private void addSomeData() {
                databaseAccess.addRow("TestAD1","TestSOYAD1");
                databaseAccess.addRow("TestAD2","TestSOYAD2");
                databaseAccess.addRow("TestAD3","TestSOYAD3");
                databaseAccess.addRow("TestAD4","TestSOYAD4");
            }
        }
        
        • 评论应解释所做的更改

        1. 修改activity_daxilet.java以获取传递的内容
        2. : -

          public class activity_daxilet extends AppCompatActivity {
          
              TextView showpassedid;
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_daxilet);
                  showpassedid = (TextView) this.findViewById(R.id.showpassedid);
          
                  long passedid = this.getIntent().getLongExtra("ID",-1);
                  showpassedid.setText("Id Passed was " + String.valueOf(passedid));
              }
          }
          
          1. 修改activity_daxilet.xml以包含TextView showpassedid
          2. e.g。 : -

            <?xml version="1.0" encoding="utf-8"?>
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".activity_daxilet">
                <TextView
                    android:id="@+id/showpassedid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
            

            结果

            首次运行时: -

            enter image description here

            单击项目(3): -

            enter image description here

答案 1 :(得分:0)

您在$('.hotel-copy').each(function () { console.log($.trim($(this).children(".sidebar-box").children("p").text()).length) if ($.trim($(this).children(".sidebar-box").children("p").text()).length < 194) { // if count is less than 193 $(this).children(".sidebar-box").children(".read-more").hide(); } else if ($.trim($(this).children(".sidebar-box").children("p").text()).length >= 194) { // if count is greater than 193 $(this).children(".sidebar-box").children(".read-more").show(); } }); 中发送id的位置,我认为您希望传递给第二个活动的是listview它自己。

所以改变这一行:

id

with:

i.putExtra("ID", position);

要在您应该使用的第二个活动中检索您的数据,而不是:

i.putExtra("ID", Id);

这个(你也需要通过id找到你的textview):

Bundle bundle = getIntent().getExtras();
if (bundle !=null){
    ad.setText("@position");
}

如果你没有,你需要为你的ad = findViewById(R.id.textviewid); Intent intent = getIntent(); String Id = intent.getExtras().getString("ID"); ad.setText(Id); 添加一个ID!将此标记添加到textview文件中的textview

xml

应该是它。

答案 2 :(得分:0)

一种方式:

  • 当我们从数据库( getData )获取costumer_data时,我们可以获取id,如:SELECT ID,...
  • 将其作为额外内容传递给第二个视图,而不是当前设置位置
祝你好运

相关问题