Java 如何将字符串数据从sqlite发送到另一个活动

Java 如何将字符串数据从sqlite发送到另一个活动,java,android,Java,Android,我有一个sqlite数据库,我成功地从中获取了所有数据,并将其存储在字符串数据中,然后使用另一个java类显示它,该类只有Toast 现在我正在尝试将此数据发送到另一个活动 我如何做到这一点 NotesDbAdapter.java: public class NotesDbAdapter { public static final String KEY_TITLE = "title"; public static final String KEY_DATE = "date";

我有一个sqlite数据库,我成功地从中获取了所有数据,并将其存储在字符串数据中,然后使用另一个java类显示它,该类只有Toast

现在我正在尝试将此数据发送到另一个活动

我如何做到这一点

NotesDbAdapter.java:

public class NotesDbAdapter {
    public static final String KEY_TITLE = "title";
    public static final String KEY_DATE = "date";
    public static final String KEY_BODY = "body";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement, "
        + "title text not null, body text not null, date text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(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) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public NotesDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public NotesDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

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


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createNote(String title, String body, String date) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        initialValues.put(KEY_DATE, date);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteNote(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllNotes() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
                KEY_BODY,KEY_DATE}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_TITLE, KEY_BODY,KEY_DATE}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateNote(long rowId, String title, String body,String date) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_BODY, body);

        //This lines is added for personal reason
        args.put(KEY_DATE, date);

        //One more parameter is added for data
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    public String getALLData(){
        mDb = mDbHelper.getWritableDatabase();
        String[] columns={KEY_ROWID ,KEY_TITLE,KEY_BODY};
        Cursor cursor = mDb.query(DATABASE_TABLE, columns, null, null, null, null, null);
        StringBuffer buffer=new StringBuffer();
        while (cursor.moveToNext()){
            int cid=cursor.getInt(0);
        String title=cursor.getString(1);   
        String body=cursor.getString(2);
        buffer.append(cid+" "+title+" "+body+"\n");
        }
        return buffer.toString();
    }}
存储数据的NoteEdit活动:

public class NoteEdit extends Activity {
    public static int numTitle = 1; 
    public static String curDate = "";
    public static String curText = "";  
    private EditText mTitleText;
    private EditText mBodyText;
    private TextView mDateText;
    private Long mRowId;

    private Cursor note;

    private NotesDbAdapter mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();        

        setContentView(R.layout.note_edit);
       // getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(R.string.app_name);

        mTitleText = (EditText) findViewById(R.id.title);
        mBodyText = (EditText) findViewById(R.id.body);
        mDateText = (TextView) findViewById(R.id.notelist_date);

        long msTime = System.currentTimeMillis();  
        Date curDateTime = new Date(msTime);

        SimpleDateFormat formatter = new SimpleDateFormat("d'/'M'/'y");  
        curDate = formatter.format(curDateTime);        

        mDateText.setText(""+curDate);


        mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
                                    : null;
        }

        populateFields();

    }

      public static class LineEditText extends EditText{
            // we need this constructor for LayoutInflater
            public LineEditText(Context context, AttributeSet attrs) {
                super(context, attrs);
                    mRect = new Rect();
                    mPaint = new Paint();
                    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
                    mPaint.setColor(Color.BLUE);
            }

            private Rect mRect;
            private Paint mPaint;       

            @Override
            protected void onDraw(Canvas canvas) {

                int height = getHeight();
                int line_height = getLineHeight();

                int count = height / line_height;

                if (getLineCount() > count)
                    count = getLineCount();

                Rect r = mRect;
                Paint paint = mPaint;
                int baseline = getLineBounds(0, r);

                for (int i = 0; i < count; i++) {

                    canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
                    baseline += getLineHeight();

                super.onDraw(canvas);
            }

        }
      }

      @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            saveState();
            outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
        }

        @Override
        protected void onPause() {
            super.onPause();
            saveState();
        }

        @Override
        protected void onResume() {
            super.onResume();
            populateFields();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.noteedit_menu, menu);
            return true;        
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {
            case R.id.menu_about:

                /* Here is the introduce about myself */            
                AlertDialog.Builder dialog = new AlertDialog.Builder(NoteEdit.this);
                dialog.setTitle("About");
                dialog.setMessage("This project "
                           );
                dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();

                       }
                   });
                   dialog.show();              
                   return true;
            case R.id.menu_delete:
                if(note != null){
                    note.close();
                    note = null;
                }
                if(mRowId != null){
                    mDbHelper.deleteNote(mRowId);
                }
                finish();
                return true;
                //speech button
            case R.id.menu_speech:
                //saveState();
                //finish();         
                return true;


            case R.id.menu_save:
                saveState();
                finish();           
                return true;
           /* case android.R.id.home:
                finish();  */   
           default:
                return super.onOptionsItemSelected(item);
            }


        }




        private void saveState() {
            String title = mTitleText.getText().toString();
            String body = mBodyText.getText().toString();

            if(mRowId == null){
                long id = mDbHelper.createNote(title, body, curDate);
                if(id > 0){
                    mRowId = id;
                }else{
                    Log.e("saveState","failed to create note");
                }
            }else{
                if(!mDbHelper.updateNote(mRowId, title, body, curDate)){
                    Log.e("saveState","failed to update note");
                }
            }
        }


        private void populateFields() {
            if (mRowId != null) {
                note = mDbHelper.fetchNote(mRowId);
                startManagingCursor(note);
                mTitleText.setText(note.getString(
                        note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
                mBodyText.setText(note.getString(
                        note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
                curText = note.getString(
                        note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
            }

        }
public void viewDetails(View view){

String data= mDbHelper.getALLData();
Message.message(this,data);


}

}
public类notedit扩展活动{
公共静态int numTitle=1;
公共静态字符串curDate=“”;
公共静态字符串curText=“”;
私有编辑文本mTitleText;
私人编辑文本;
私有文本视图mDateText;
私人长mRowId;
私人光标注释;
私人票据登记簿;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mDbHelper=新的NotesDbAdapter(本);
mDbHelper.open();
setContentView(R.layout.note\u编辑);
//getActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.app_name);
mTitleText=(EditText)findViewById(R.id.title);
mBodyText=(EditText)findViewById(R.id.body);
mDateText=(TextView)findViewById(R.id.notelist\u日期);
long msTime=System.currentTimeMillis();
日期curDateTime=新日期(msTime);
SimpleDataFormat格式化程序=新的SimpleDataFormat(“d'/'M'/'y”);
curDate=formatter.format(curDateTime);
mDateText.setText(“+curDate”);
mRowId=(savedInstanceState==null)?null:
(Long)savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if(mRowId==null){
Bundle extras=getIntent().getExtras();
mRowId=extras!=null?extras.getLong(NotesDbAdapter.KEY\u ROWID)
:null;
}
populateFields();
}
公共静态类LineEditText扩展了EditText{
//我们需要这个构造器来实现LayoutFlater
公共LineEditText(上下文、属性集属性){
超级(上下文,attrs);
mRect=新的Rect();
mPaint=新油漆();
mPaint.setStyle(绘制、样式、填充和笔划);
mPaint.setColor(Color.BLUE);
}
私人直肠;
私人油漆;
@凌驾
受保护的void onDraw(画布){
int height=getHeight();
int line_height=getLineHeight();
int count=高度/线条高度;
如果(getLineCount()>count)
count=getLineCount();
Rect r=mRect;
油漆油漆=mPaint;
int基线=getLineBounds(0,r);
for(int i=0;i0){
mRowId=id;
}否则{
Log.e(“保存状态”,“无法创建注释”);
}
}否则{
if(!mDbHelper.updateNote(mRowId、title、body、curDate)){
Log.e(“保存状态”,“无法更新注释”)
Intent intent=new Intent(getApplicationContext(), SecondActivity.class);
    intent.putExtra("key1", "your value1 here");
    intent.putExtra("key2", "your value2 here");
    startActivity(intent);
String your_value1=getIntent().getStringExtra("key1");
    String your_value2=getIntent().getStringExtra("key2");