Android:不显示数据库数据

时间:2011-12-08 10:28:06

标签: android database

帮助,不显示保存的数据到数据库。这是代码:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.compose_message);
        mDbHelper = new MessagesDBAdapter(this);
        mDbHelper.open();

        btnRecipient = (Button) findViewById(R.id.button_recipient_picker);
        btnSend = (Button) findViewById(R.id.button_send);
        editTextRecipient = (EditText) findViewById(R.id.editText_recipient);
        editTextRecipient.setInputType(0);
        editTextNewMessage = (EditText) findViewById(R.id.editText_new_message);
        spinnerTimeDelay = (Spinner) findViewById(R.id.spinner_delay);
        tv_details = (TextView) findViewById(R.id.tv_details);

        spinnerTimeDelay.setOnItemSelectedListener(this);
        ArrayAdapter<String> aa=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,items);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTimeDelay.setAdapter(aa);

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

btnRecipient.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, CONTACT_PICKER_RESULT);
            }
        });

        mDbHelper.close();
    }

    // Spinner
    public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        count=pos;
        if(FirstLoad){
            FirstLoad = false;
            return;                         
        }

        Toast.makeText(parent.getContext(), "You chose " + 
                  parent.getItemAtPosition(pos).toString()+ " to delay", Toast.LENGTH_LONG).show();
        }

        public void onNothingSelected(AdapterView<?> parent) {
          return;
        }

    public  void showProgress () {
        dialog = new ProgressDialog(this);
        dialog.setCancelable(true);
        dialog.setMessage("Sending Message .. ");
        dialog.show(); 
    }

    // Contact Picker    
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case (CONTACT_PICKER_RESULT):

                if (resultCode == Activity.RESULT_OK) {
                    StringBuilder sb = new StringBuilder();
                    Uri contactData = data.getData();
                    Cursor contactsCursor = managedQuery(contactData,
                            null, null, null, null);
                    if (contactsCursor.moveToFirst()) {
                        String id = contactsCursor.getString(contactsCursor
                                .getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                        String name = contactsCursor.getString(contactsCursor
                                .getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                        String hasPhoneNumber = contactsCursor.getString(contactsCursor
                                .getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        sb.append(name);
                        if (Integer.parseInt(hasPhoneNumber) > 0) {
                            Uri myPhoneUri = Uri.withAppendedPath(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id);
                            Cursor phoneCursor = managedQuery(
                                    myPhoneUri, null, null, null, null);
                            for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext()) {
                                String phoneNumber = phoneCursor.getString(phoneCursor
                                        .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                sb.append(phoneNumber);
                            }
                        } else {
                            sb.append("This contact doesn't have a phone number");
                        }
                        editTextRecipient.setText(sb.toString());
                    }
                }
                break;
            }


         btnSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String phoneNo = editTextRecipient.getText().toString();
                String message = editTextNewMessage.getText().toString(); 
                Log.d(phoneNo, message);
               saveState(phoneNo, message);
                boolean split = false;

                /*SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                //String date = s.format(new Date());
                Calendar c = Calendar.getInstance();
                Timestamp timeStamp = new Timestamp(c.get(Calendar.YEAR)-1900, c.get(Calendar.MONTH), 
                        c.get(Calendar.DATE), c.get(Calendar.HOUR), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), 0);
                //saveState(phoneNo, message);*/

                final Toast toast = Toast.makeText(getBaseContext(), 
                         "Your message " + "\"" + message + "\"" + " is sent to " +"\""+ phoneNo+"\"", 
                          Toast.LENGTH_SHORT);

                Runnable showToastRunnable = new Runnable() {
                  public void run() {
                      dialog.cancel();
                      toast.show();
                  }
              };

                if (phoneNo.length()>0 && message.length()>0)  {
                    showProgress();
                    if (count == 0) {
                          handler.postDelayed(showToastRunnable, 0);
                      }
                      else if (count == 1) {
                          handler.postDelayed(showToastRunnable, 15000);
                      }
                      else if (count == 2) {
                          handler.postDelayed(showToastRunnable, 30000);
                      }
                      else if (count == 3) {
                          handler.postDelayed(showToastRunnable, 60000);
                      }
                }

                   // sendSMS(phoneNo, message, split); */
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });      
         mDbHelper.close();
    }

     private void populateFields() {
        if (mRowId!=null) {
            Cursor message=mDbHelper.fetchNote(mRowId);
            startManagingCursor(message);
            editTextRecipient.setText(message.getString(message.getColumnIndexOrThrow(MessagesDBAdapter.KEY_RECIPIENT)));
            editTextNewMessage.setText(message.getString(message.getColumnIndexOrThrow(MessagesDBAdapter.KEY_MESSAGE)));
        }
     }

     private void saveState(String phoneNo, String message) {
         Log.i(phoneNo, message);

        if (mRowId==null) {
            long id = mDbHelper.createNote(phoneNo, message);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateNote(mRowId, phoneNo, message);
        }
    }
}

这是另一个:

public class Inbox extends ListActivity {
    ListView list;

    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private MessagesDBAdapter mDbHelper;
    private Cursor mMessagesCursor;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.inbox);
            mDbHelper = new MessagesDBAdapter(this);
            mDbHelper.open();
            fillData();
            registerForContextMenu(getListView());

            list = (ListView) findViewById(android.R.id.list);
        }

        private void fillData() {
            mMessagesCursor = mDbHelper.fetchAllNotes();
            startManagingCursor(mMessagesCursor);
            String[] from = new String[]{MessagesDBAdapter.KEY_RECIPIENT, MessagesDBAdapter.KEY_MESSAGE};
            int[] to = new int[]{R.id.tv_recipient, R.id.tv_details};
            SimpleCursorAdapter messages = 
                new SimpleCursorAdapter(this, R.layout.message_custom_row, mMessagesCursor, from, to);
         }

         /*@Override
            public boolean onCreateOptionsMenu(Menu menu) {
                super.onCreateOptionsMenu(menu);
                menu.add(0, INSERT_ID, 0, R.string.menu_insert);
                return true;
            }

            @Override
            public boolean onMenuItemSelected(int featureId, MenuItem item) {
                switch(item.getItemId()) {
                    case INSERT_ID:
                        createNote();
                        return true;
                }

                return super.onMenuItemSelected(featureId, item);
            }*/

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.add(0, DELETE_ID, 0, R.string.menu_delete);
        }

        @Override
        public boolean onContextItemSelected(MenuItem item) {
            switch(item.getItemId()) {
                case DELETE_ID:
                    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                    mDbHelper.deleteNote(info.id);
                    fillData();
                    return true;
            }
            return super.onContextItemSelected(item);
        }

        private void createNote() {
            Intent i = new Intent(this, KAHTextApp.class);
            startActivityForResult(i, ACTIVITY_CREATE);
        }

        @Override
        protected void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
            Cursor c = mMessagesCursor;
            c.moveToPosition(position);
            Intent i = new Intent(this, KAHTextApp.class);
            i.putExtra(MessagesDBAdapter.KEY_ROWID, id);
            i.putExtra(MessagesDBAdapter.KEY_RECIPIENT, c.getString(
                    c.getColumnIndexOrThrow(MessagesDBAdapter.KEY_RECIPIENT)));
            i.putExtra(MessagesDBAdapter.KEY_MESSAGE, c.getString(
                    c.getColumnIndexOrThrow(MessagesDBAdapter.KEY_MESSAGE)));
            startActivityForResult(i, ACTIVITY_EDIT);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            super.onActivityResult(requestCode, resultCode, intent);
            Bundle extras = intent.getExtras();
            switch(requestCode) {
                case ACTIVITY_CREATE:
                    String recipient = extras.getString(MessagesDBAdapter.KEY_RECIPIENT);
                    String message = extras.getString(MessagesDBAdapter.KEY_MESSAGE);
                    mDbHelper.createNote(recipient, message);
                    fillData();
                    break;
                case ACTIVITY_EDIT:
                    Long rowId = extras.getLong(MessagesDBAdapter.KEY_ROWID);
                    if (rowId != null) {
                        String editTitle = extras.getString(MessagesDBAdapter.KEY_RECIPIENT);
                        String editBody = extras.getString(MessagesDBAdapter.KEY_MESSAGE);
                        mDbHelper.updateNote(rowId, editTitle, editBody);
                    }
                    fillData();
                    break;
            }
        }
}

然后是数据库:

public class MessagesDBAdapter {

    public static final String KEY_RECIPIENT = "recipient";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_ROWID = "_id";

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

     //Database creation sql statement

    private static final String DATABASE_CREATE =
             "create table notes (" + KEY_ROWID + " integer primary key autoincrement, "
        + KEY_RECIPIENT + " text not null, " + KEY_MESSAGE + " 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 MessagesDBAdapter(Context ctx) {
        this.mCtx = ctx;
    }

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

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

    public long createNote(String phoneNo, String message) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_RECIPIENT, phoneNo);
        initialValues.put(KEY_MESSAGE, message);

        open();

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

    public boolean deleteNote(long rowId) {

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

    public Cursor fetchAllNotes() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_RECIPIENT,
                KEY_MESSAGE}, null, null, null, null, null);
    }

    public Cursor fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

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

    }

    public boolean updateNote(long rowId, String phoneNo, String message) {
        ContentValues args = new ContentValues();
        args.put(KEY_RECIPIENT, phoneNo);
        args.put(KEY_MESSAGE, message);

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

我不知道我错过了什么,或者删除了但是数据没有保存在数据库中。谁能帮我?这里没有错误,数据不仅显示在列表视图中。

1 个答案:

答案 0 :(得分:0)

您创建了一个SimpleCursorAdapter,但是您没有将其提供给ListView。在fillData()中创建适配器后添加setListAdapter(消息)。

注意:在ListActivity中,您可以使用getListView()获取ListView,您不需要使用findViewById()。这与你的问题无关,只是一个信息:)