I am having problem with inserting string values (user_name, password) into a table, named login. Here are the codes: I have added "//THIS IS WHERE THE PROBLEM OCCURS" comment to highlight the problem...the DBAdapter class which is containing all the database-related methods, are also given after this code..
package images.tests.proj;
import java.io.IOException;
import images.tests.proj.DBAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.database.Cursor;
public class username extends Imagetest1Activity {
/** Called when the activity is first created. */
private DBAdapter db1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.username);
Button lbtn = (Button) findViewById(R.id.loginb);
Button rbtn = (Button) findViewById(R.id.registerb);
final EditText utext = (EditText) findViewById(R.id.utext);
final EditText ptext = (EditText) findViewById(R.id.ptext);
db1 = new DBAdapter(this);
rbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String ut = utext.getText().toString();
String pt = ptext.getText().toString();
try {
// THIS IS WHERE THE PROBLEM OCCURS
db1.insertContact(ut, pt);
} catch (NullPointerException e) {
Toast.makeText(username.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
The DBAdapter class contains the insertContact method as follows:
//---insert a contact into the database---
public long insertContact(String user_name, String password)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, user_name);
initialValues.put(KEY_PASSWORD, password);
return db.insert(DATABASE_TABLE, null, in开发者_如何学JAVAitialValues);
}
Could you point out the mistake? Any help would be appreciable. Thank you!
You need to have opened database that can be writeable in the DBAdapter class:
Try:
public long insertContact(String user_name, String password)
{
db= this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, user_name);
initialValues.put(KEY_PASSWORD, password);
return db.insert(DATABASE_TABLE, null, initialValues);
}
use this.
public long insertContact(String name, int moves,String time) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_MOVES, moves);
initialValues.put(KEY_TIME, time);
return db.insert(DATABASE_TABLE, null, initialValues);
}
精彩评论