【问题标题】:Making a dynamic ListView clickable to change activity使动态 ListView 可单击以更改活动
【发布时间】:2014-05-07 19:39:38
【问题描述】:

我的 android 应用程序当前使用 sqlite 表的内容填充 ListView(在 MainActivity 中)。我希望能够单击创建的 ListView 项目之一并将其更改为我的 EditNote 活动,但还将与该 ListView 相关的数据库记录传递到 EditNote,并填充 EditTexts。

我的 MainActivity 在加载时填充 ListView:

public class MainActivity extends ListActivity{


    DatabaseHelper dbh;
    ArrayList<String> listItems = new ArrayList<String>();
    ArrayAdapter<String> adapter;

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

         dbh = new DatabaseHelper(this);
            dbh.open();

            adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, listItems);

            setListAdapter(adapter);

            ArrayList<String[]> searchResult = new ArrayList<String[]>();

            //EditText searchTitle = (EditText) findViewById(R.id.searchC);

            listItems.clear();

            searchResult = dbh.fetchNotes("");
            //searchResult = dbh.fetchNotes(searchTitle.getText().toString());

            String title = "", note = "";


            for (int count = 0 ; count < searchResult.size() ; count++) {

                  note = searchResult.get(count)[1];
                  title = searchResult.get(count)[0];                           

                  listItems.add(title);

            }                

                adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }


    public void addNote(View v){
        Intent newActivity = new Intent (this, AddingNote.class);
        startActivity(newActivity);
        finish();
    }

}

我的数据库类用于创建表和选择语句:

public class DatabaseHelper {

    private static final String DATABASE_NAME = "noteDatabase";
    private static final int DATABASE_VERSION = 1;  
    private static final String TABLE_NAME = "note";

    private OpenHelper mDbHelper;
    private SQLiteDatabase mDb;
    private final Context dbContext;

    private static final String DATABASE_CREATE =
                        "CREATE TABLE " + TABLE_NAME + " (" +
                        "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "title TEXT NOT NULL, " +
                        "note TEXT NOT NULL); ";


    public DatabaseHelper(Context ctx) {

        this.dbContext = ctx;

    }

    public DatabaseHelper open() throws SQLException {
        mDbHelper = new OpenHelper(dbContext);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public boolean createNote(String title, String note) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("title", title);
        initialValues.put("note", note);

        return mDb.insert(TABLE_NAME, null, initialValues) > 0;
    }

    public boolean updateNote(long rowId, String title, String note) {

        ContentValues args = new ContentValues();

        args.put("title", title);
        args.put("note", note);

        return mDb.update(TABLE_NAME, args, "_id=" + rowId, null) > 0;
    }

    public void deleteAll() {
        mDb.delete(TABLE_NAME, null, null);
    }

    public void deleteRecord(long rowID) {
        mDb.delete(TABLE_NAME, "_rowId=" + rowID, null);
    }

    public ArrayList<String[]> fetchNotes(String title) throws SQLException {

        ArrayList<String[]> myArray = new ArrayList<String[]>();

        int pointer = 0;     

        Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"_id", "title",
                "note"}, null, null,
                    null, null, "_id");

        int titleColumn = mCursor.getColumnIndex("title");
        int noteColumn = mCursor.getColumnIndex("note");     

        if (mCursor != null){

           if (mCursor.moveToFirst()){

                do {
                    myArray.add(new String[3]);

                    myArray.get(pointer)[0] = mCursor.getString(titleColumn);
                    myArray.get(pointer)[1] = mCursor.getString(noteColumn);
                    //increment our pointer variable.
                    pointer++;
                } while (mCursor.moveToNext()); // If possible move to the next record
           } else {

               myArray.add(new String[3]);
               myArray.get(pointer)[0] = "NO RESULTS";
               myArray.get(pointer)[1] = "";
           }
        } 

        return myArray;

    }

    public ArrayList<String[]> selectAll() {

        ArrayList<String[]> results = new ArrayList<String[]>();

        int counter = 0;

        Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "id", "forename", "surname", "age" }, null, null, null, null, "surname desc");

        if (cursor.moveToFirst()) {
        do {
            results.add(new String[3]);
            results.get(counter)[0] = cursor.getString(0).toString();
            results.get(counter)[1] = cursor.getString(1).toString();
            results.get(counter)[2] = cursor.getString(2).toString();
            results.get(counter)[3] = cursor.getString(3).toString();
            counter++;
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }

        return results;
    }

    private static class OpenHelper extends SQLiteOpenHelper {

        OpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }
}

我的列表视图 XML(在 activity_main.xml 中):

<ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/container" >

    </ListView>

我对 android 开发还很陌生,因此我们将不胜感激任何帮助。谢谢。

【问题讨论】:

    标签: android sqlite android-listview


    【解决方案1】:

    为您的 ListView 设置一个 onClickListener 并启动一个指向您的 EditNote 活动的 Intent,该活动使用以下方式获取数据:

    getIntent().getStringExtra(...);
    

    例子:

    主活动:

    getListView().setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
    
           Intent i = new Intent(this, EditNote.class);
           i.putExtra("listItem", listItems[position]);
           startActivity(i);
    
    }
    });
    

    编辑注释:

    String listItem = getIntent().getStringExtra("listItem");

    这就是你要找的吗?

    【讨论】:

    • 是的,这看起来很像我想要的。但是,我尝试输入该代码并且“getListView()”出现错误“方法的返回类型丢失”并建议我将返回类型更改为 void。
    • getListView() 是一种只能在 ListActivity 中访问的方法(您的 MainActivity 是 ListActivity,对吧?)
    • 是公共类MainActivity扩展ListActivity,它在MainActivity类中。 Screenshot of code
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2022-11-01
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多