单击ListView时如何从数据库中获取数据

时间:2015-06-30 10:56:05

标签: java android listview

我是android的新手,我设法将EditText中的数据插入到数据库中,然后将其显示到ListView中,但现在我需要在ListView中单击项目时显示单个注释,而我只是“不要”。我知道怎么做。我希望它可以在 activity_edit_note.xml 中编辑。有人可以帮帮我吗?这是我的代码。

Notes.java

package com.cidecode.xnotes;
public class Notes {
    private long id;
    private String title;
    private String note;
    private String date;

    public Notes(){

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString(){
    return title + "\t" + date + "\n" + note;
} 
}

DatabaseHelper.java

package com.cidecode.xnotes;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String TABLE_NOTES = "notes";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_NOTE = "note";
    public static final String COLUMN_DATE = "date";

    private static final String DATABASE_NAME = "xnotes.db";
    private static final int DATABASE_VERSION = 1;

    // Create the database
    private static final String DATABASE_CREATE = "create table " + TABLE_NOTES + "(" +
            COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " text not null, " +
            COLUMN_NOTE + " text not null, " + COLUMN_DATE + " text not null);";

    // Drop table notes
    private static final String DATABASE_DROP_TABLE_NOTES = "drop table if exists " + TABLE_NOTES;

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

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

    @Override
    public void onUpgrade(android.database.sqlite.SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(), "Upgrading database from v" + oldVersion + " to v" +
                newVersion + " which will delete all old data.");

        db.execSQL(DATABASE_DROP_TABLE_NOTES);
        onCreate(db);
    }
}

NotesDataSource.java

package com.cidecode.xnotes;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.EditText;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NotesDataSource {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private String[] allColumns = {DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_TITLE, DatabaseHelper.COLUMN_NOTE, DatabaseHelper.COLUMN_DATE};

public NotesDataSource(Context context){
    dbHelper = new DatabaseHelper(context);
}

public void open() throws SQLException{
    database = dbHelper.getWritableDatabase();
}

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

public Notes createNote(String title, String note, String date){
    ContentValues values = new ContentValues();
    values.put(DatabaseHelper.COLUMN_TITLE, title);
    values.put(DatabaseHelper.COLUMN_NOTE, note);
    values.put(DatabaseHelper.COLUMN_DATE, date);
    long insertId = database.insert(DatabaseHelper.TABLE_NOTES, null, values);

    Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
            DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
    cursor.moveToFirst();
    Notes newNotes = cursorToNote(cursor);
    cursor.close();
    return newNotes;
}

public List<Notes> getAllNotes(){
    List<Notes> notesList = new ArrayList<Notes>();

    Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
            null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()){
        Notes note = cursorToNote(cursor);
        notesList.add(note);
        cursor.moveToNext();
    }
    cursor.close();
    return notesList;
}

private Notes cursorToNote(Cursor cursor){
    Notes note = new Notes();
    note.setId(cursor.getLong(0));
    note.setTitle(cursor.getString(1));
    note.setNote(cursor.getString(2));
    note.setDate(cursor.getString(3));
    return note;
}

public void deleteNote(int id){
    database.delete(DatabaseHelper.TABLE_NOTES, DatabaseHelper.COLUMN_ID + "=" + id, null);
}

}

AddNote.java

package com.cidecode.xnotes;

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.SQLException;


public class AddNote extends ActionBarActivity {

private EditText title = null;
private EditText note = null;
private String s_title, s_note, s_date;
Button b_save;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private NotesDataSource datasource;

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

    dbHelper = new DatabaseHelper(this);
    datasource = new NotesDataSource(this);
    try {
        datasource.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    title = (EditText)findViewById(R.id.id_title);
    note = (EditText)findViewById(R.id.id_write_note_here);

    s_title = title.getText().toString();
    s_note = note.getText().toString();
    s_date = "21.11.1111";

    b_save = (Button)findViewById(R.id.id_save);
    b_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datasource.createNote(title.getText().toString(), note.getText().toString(), s_date);
            Toast.makeText(getApplicationContext(), "Note is saved.", Toast.LENGTH_LONG).show();
            Log.w("Title: ", title.getText().toString());
            Log.w("Note: ", note.getText().toString());
            Log.w("Date: ", s_date);
            Intent intent = new Intent(AddNote.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_add_note, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

activity_add_note.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#EBD28F">

    <TextView
        android:id="@+id/id_add_new_note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s_add_new_note"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_marginBottom="10dp"/>

    <EditText
        android:id="@+id/id_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/s_title"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"/>

    <EditText
        android:id="@+id/id_write_note_here"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:hint="@string/s_write_note_here"
        android:gravity="top" />

    <Button
        android:id="@+id/id_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:text="@string/s_save"
        android:textColor="#FFFFFF"
        android:background="#5E553A"/>

</LinearLayout>

MainActivity.java

package com.cidecode.xnotes;

import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.sql.SQLException;
import java.util.List;


public class MainActivity extends ListActivity {

    Button AddNew;
    private ListView listView;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private NotesDataSource datasource;


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

        dbHelper = new DatabaseHelper(this);
        datasource = new NotesDataSource(this);
        try {
            datasource.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        List<Notes> values = datasource.getAllNotes();
        final ArrayAdapter<Notes> adapter = new ArrayAdapter<Notes>(this, android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);

        listView = getListView();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
               return false;
            }
        });

        AddNew = (Button)findViewById(R.id.id_add_new);
        AddNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddNote.class);
                startActivity(intent);
            }
        });



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#EBD28F">

    <TextView
        android:id="@+id/id_xnotes"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s_xnotes"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_marginBottom="10dp"/>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:clickable="true"
        android:longClickable="true"></ListView>

    <Button
        android:id="@+id/id_add_new"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:text="@string/s_add_new"
        android:textColor="#FFFFFF"
        android:background="#5E553A"/>

</LinearLayout>

EditNote.java

package com.cidecode.xnotes;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class EditNote extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_edit_note, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_edit_note.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#EBD28F">

    <TextView
        android:id="@+id/id_add_new_note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s_edit_note"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_marginBottom="10dp"/>

    <EditText
        android:id="@+id/id_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/s_title"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"/>

    <EditText
        android:id="@+id/id_write_note_here"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:hint="@string/s_write_note_here"
        android:gravity="top" />

    <Button
        android:id="@+id/id_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:text="@string/s_save"
        android:textColor="#FFFFFF"
        android:background="#5E553A"/>

</LinearLayout>

2 个答案:

答案 0 :(得分:1)

它是一种通过COLUMN_ID

获取单个音符的方法
        public Notes getSingleNote(long id){

            Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
                    COLUMN_ID +"=?", new String[]{String.valueOf(id)}, null, null, null);

            Note note = null;
            if(cursor.moveToFirst())
                note = cursorToNote(cursor);
            cursor.close();
            return note;
        }

答案 1 :(得分:0)

全局声明List<Notes> values。并更新您的listView项目点击监听器,如下所述:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 Notes selectedNote = values.get(position);    
            }
        });

这里&#34; selectedNote&#34;选定的项目。并按照以下链接传递此项目。

How do I pass an object from one activity to another on Android?