晚上好 我需要知道如何通过 Intent 将字符串发送到数据库!
我试过这样做,但没有成功。
这是来自 Activity 的代码。
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
note = (EditText) findViewById(R.id.etNote);
String notes = note.getText().toString();
db.insert(notes);
}
});
这是数据库中的代码。
public long insert(String message) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(NOTE, message);
return db.insert(DATABASE_TABLE, null, cv);
}
但不幸的是它没有用! 有人知道这样做的方法吗?
这是将显示带有数据库的 listView 的 Activity 的全部代码。
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.widget.ListView;
public class show extends FragmentActivity implements LoaderCallbacks<Cursor> {
SimpleCursorAdapter mAdapter;
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
mListView = (ListView) findViewById(R.id.listview);
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.listview_item_layout,
null,
new String[] { CustomerDB.NOTE},
new int[] { R.id.note }, 0);
mListView.setAdapter(mAdapter);
/** Creating a loader for populating listview from sqlite database */
/** This statement, invokes the method onCreatedLoader() */
getSupportLoaderManager().initLoader(0, null, this);
}
/** A callback method invoked by the loader when initLoader() is called */
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri uri = Customer.CONTENT_URI;
return new CursorLoader(this, uri, null, null, null, null);
}
/** A callback method, invoked after the requested content provider returned all the data */
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
mAdapter.swapCursor(arg1);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
}
这就是内容提供者。
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
/** A custom Content Provider to do the database operations */
public class Customer extends ContentProvider{
public static final String PROVIDER_NAME = "in.wptrafficanalyzer.sqllistviewdemo.customer";
/** A uri to do operations on cust_master table. A content provider is identified by its uri */
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/customers" );
/** Constants to identify the requested operation */
private static final int CUSTOMERS = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "customers", CUSTOMERS);
}
/** This content provider does the database operations by this object */
CustomerDB mCustomerDB;
/** A callback method which is invoked when the content provider is starting up */
@Override
public boolean onCreate() {
mCustomerDB = new CustomerDB(getContext());
return true;
}
@Override
public String getType(Uri uri) {
return null;
}
/** A callback method which is by the default content uri */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if(uriMatcher.match(uri)==CUSTOMERS){
return mCustomerDB.getAllCustomers();
}else{
return null;
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
这就是数据库。
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
public class CustomerDB extends SQLiteOpenHelper{
/** Database name */
private static String DBNAME = "sqllistviewdemo";
/** Version number of the database */
private static int VERSION = 1;
/** Field 1 of the table cust_master, which is the primary key */
public static final String KEY_ROW_ID = "_id";
public static final String NOTE="OK";
/** A constant, stores the the table name */
private static final String DATABASE_TABLE = "cust_master";
/** An instance variable for SQLiteDatabase */
private SQLiteDatabase mDB;
/** Constructor */
public CustomerDB(Context context) {
super(context, DBNAME, null, VERSION);
this.mDB = getWritableDatabase();
}
/** This is a callback method, invoked when the method
* getReadableDatabase() / getWritableDatabase() is called
* provided the database does not exists
* */
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table "+ DATABASE_TABLE + " ( "
+ KEY_ROW_ID + " integer primary key autoincrement , "
+ NOTE + " text ) " ;
db.execSQL(sql);
}
public long insert(String message) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(NOTE, message);
return db.insert(DATABASE_TABLE, null, cv);
}
/** Returns all the customers in the table */
public Cursor getAllCustomers(){
return mDB.query(DATABASE_TABLE, new String[] { KEY_ROW_ID, NOTE } ,
null, null, null, null,null
);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
最佳答案
/** SQLiteDatabase IMPLEMENTATION */
public final class SQLiteDatabase extends SQLiteClosable {
/**
* Convenience method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be <code>null</code>.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided <code>values</code> is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the <code>nullColumnHack</code> parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your <code>values</code> is empty.
* @param values this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert(String table, String nullColumnHack, ContentValues values)
检查内容值中的必填列(标记为 REQUIRED NOT NULL)
顺便说一下,你把所有的东西都混合了
如果您决定使用内容提供商 - 它应该与您的应用分开
- 在内容提供商中
您将数据库例程插入/更新/删除用于相应的内容提供者方法 在应用程序中( Activity 等) 你使用加载器(回调)或内容解析器
getContentResolver().insert(...);/。询问(..); .删除(..);
如何使用内容解析器的示例:
/**
* update user by id with USERS table info
* returns row (should be the same as prev
*/
public int updateUserPassword(User user) {
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put(UserTable.USER_PASSWORD, user.getPassword());
// get where for insert/update
String query = " " + UserTable.USER_ID + "=?";
String rowId = String.valueOf(user.getID());
/** insert record via content provider */
App.log.debug("Sending uri via content resolver to content provider...");
// construct URI
Uri uri = Uri.parse(ContentProvider.USERS_CONTENT_URI + "/" + rowId);
// involve content resolver
int updatedRouCount = getContext().getContentResolver().update(uri,
updatedValues,
query,
new String[]{rowId});
/** return count of updated rows should be 1 if all ok */
return updatedRouCount;
}
实现内容提供者先读
关于android - 通过 Intent 向数据库发送一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31775756/