使动态ListView可单击以更改活动

时间:2014-05-07 19:39:38

标签: android sqlite android-listview

我的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();
    }

}

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

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开发很新,所以任何帮助都将非常感激。谢谢。

1 个答案:

答案 0 :(得分:1)

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

getIntent().getStringExtra(...);

示例:

MainActivity:

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

}
});

EditNote:

String listItem = getIntent()。getStringExtra(&#34; listItem&#34;);

这是你正在寻找的吗?