Related
I have an application that supposed to take the text that the user enters from 4 EditTexts and a Spinner, and create a new item in the database when a button is clicked. (Image Below)
I have created a method in my database helper class that adds a new item, so in this activity I create a new item, and then pass that item to the method that should create it in the database. But for some reason weird text appear on the screen instead of a new item in the RecyclerView.
I don't know why I get the strings from the editTexts and the int (Which is the Arrival Time) and the string from the spinner and I pass it to a new item (Train) but this error keeps happening.
Here are my DatabaseHelper Class:
public class TrainDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "train.db";
public static final String TABLE_NAME = "train";
public static final String COLUMN_ID ="_id";
public static final String COLUMN_PLATFORM = "platform";
public static final String COLUMN_ARRIVAL_TIME = "arrival_time";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_DESTINATION_TIME = "destination_time";
public static final String[] COLUMNS = {COLUMN_ID, COLUMN_PLATFORM, COLUMN_ARRIVAL_TIME
, COLUMN_STATUS,COLUMN_DESTINATION,COLUMN_DESTINATION_TIME};
private static TrainDatabaseHelper sInstance;
public synchronized static TrainDatabaseHelper getInstance(Context context) {
if (sInstance == null){
sInstance = new TrainDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private TrainDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_PLATFORM + " TEXT, "
+ COLUMN_ARRIVAL_TIME + " INTEGER, "
+ COLUMN_STATUS+ " TEXT, "
+ COLUMN_DESTINATION + " TEXT, "
+ COLUMN_DESTINATION_TIME + " TEXT"
+ ")"
);
addTrain(db, new Train(0, "Albion Park Platform 1", 3,"On Time",
"Allawah", "14:11"));
addTrain(db, new Train(1, "Arncliffe Platform 2", 4, "Late",
"Central", "14:34"));
addTrain(db, new Train(2, "Artarmion Platform 3", 7, "On Time",
"Ashfield", "15:01"));
addTrain(db, new Train(3, "Berowra Platform 4", 12, "Late",
"Beverly", "15:18"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
db.execSQL("alter table " + TABLE_NAME + " add column description TEXT");
case 2:
db.execSQL("alter table " + TABLE_NAME + " add column air_conditioned TEXT");
}
}
public void addTrain(Train train){
addTrain(getWritableDatabase(), train);
}
private void addTrain(SQLiteDatabase db, Train train){
ContentValues values = new ContentValues();
values.put(COLUMN_PLATFORM, train.getPlatform());
values.put(COLUMN_ARRIVAL_TIME, train.getArrivalTime());
values.put(COLUMN_STATUS, train.getStatus());
values.put(COLUMN_DESTINATION, train.getDestination());
values.put(COLUMN_DESTINATION_TIME, train.getDestinationTime());
db.insert(TABLE_NAME,null,values);
}
public void deleteTrains (){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
public Train getTrain(int position){
return getTrains().get(position);
}
public List<Train> getTrains(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
List<Train> trains = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Train train = new Train(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5));
trains.add(train);
} while (cursor.moveToNext());
}
cursor.close();
return trains;
}
Here is the activity where we add a new item (Train):
public class AddTrainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mPlatformEt, mArrivalEt, mDestinationEt, mDestinationTimeEt;
private String mStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_train_activity);
mPlatformEt = findViewById(R.id.platform_entry);
mArrivalEt = findViewById(R.id.arrival_time_entry);
mDestinationEt = findViewById(R.id.destination_entry);
mDestinationTimeEt = findViewById(R.id.destination_time_entry);
mSpinner = findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this,
R.array.status_array, android.R.layout.simple_spinner_item);
// Apply the adapter to the spinner
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSpinner.setAdapter(mAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
mStatus = getString(R.string.status_on_time);
break;
case 1:
mStatus = getString(R.string.status_late);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(AddTrainActivity.this, R.string.status_toast, Toast.LENGTH_LONG).show();
}
});
}
public void addTrainButton (View view) {
int arrivalTime = Integer.valueOf(mArrivalEt.toString());
String platform = mPlatformEt.toString();
String destination = mDestinationEt.toString();
String destinationTime = mDestinationTimeEt.toString();
Train train = new Train(4,platform,arrivalTime, mStatus,
destination ,destinationTime);
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
helper.addTrain(train);
Toast.makeText(this, R.string.add_train_toast, Toast.LENGTH_SHORT).show();
goBackHome();
}
public void cancelButton(View view) {
goBackHome();
}
public void goBackHome(){
startActivity(new Intent(AddTrainActivity.this, MainActivity.class));
}
And this is the MainActivity Class:
public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTrainsRv = findViewById(R.id.train_rv);
mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
mTrainAdapter = new TrainAdapter(this);
mTrainsRv.setAdapter(mTrainAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
/** a FAB onClick Listener that starts a new activity to add a train */
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,AddTrainActivity.class));
}
});
}
#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 */
switch (item.getItemId()) {
case R.id.action_delete:
// TODO deleting all trains from database
mTrainAdapter.notifyDataSetChanged();
return true;
case R.id.action_refresh:
return true;
case R.id.action_quit:
Toast.makeText(this, R.string.quit_menu,
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
}
Thanks in advance and if you need more code let me know.
The problem was I forgot to do .getText() before doing .toString()
example:
mPlatformEt.getText().toString();
instead of
mPlatformEt.toString();
I cant't get all data to display in button when click on button get. please help me.
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DATABASE = "Test";
private static final String TABLE_NAME = "savedata";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_SEX = "sex";
public DBHelper(Context context) {
super(context, DATABASE, null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " +TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_SEX + " TEXT)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" +TABLE_NAME);
onCreate(db);
}
public void Insertdata(Data data){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, data.getName());
values.put(KEY_SEX, data.getSex());
db.insert(TABLE_NAME, null, values);
}
public List<Data> getAllData(){
List<Data> listData = new ArrayList<Data>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " +TABLE_NAME, null);
if (c.moveToFirst()){
do {
Data data = new Data();
data.setId(c.getInt(0));
data.setName(c.getString(1));
data.setSex(c.getString(2));
listData.add(data);
}while (c.moveToNext());
}
return listData;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
SaveData();
getData();
}
public void SaveData(){
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void getData(){
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
You've messed up badly. That's all I can suggest-
1. Create a class (for example "MyClass") that will extend AppCompatActivity and contains the view.
2. You've already created a class named DBHelper for your Database manipulation. It extends SQLiteOpenHelper.
3. Create object of DBHelper class inside the onCreate method of MyClass and access your database. onCreate method in MyClass will be looking similar to this-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Hope that, this might help.
I have created a simple demo in which I have simply stored the two value that is first name and last name in sqlite and display that in list view.But when I tried two add more value like phone no.address,state,country etc . I got error.and it display the message like could not read the row and column data.
please help me two add 9 or 10 value and display in list view.here is my code.
AddActivity.Java
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,phoneNo;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,pno;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
phoneNo=(EditText)findViewById(R.id.phoneNo);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
pno=getIntent().getExtras().getString("Pno");
edit_first.setText(fname);
edit_last.setText(lname);
phoneNo.setText(pno);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
pno=phoneNo.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_PHONENO,pno );
System.out.println("");
if(isUpdate)
{
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
dataBase.close();
finish();
}
}
DisplayAdapter.java
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> phoneNo;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname,ArrayList<String> pno) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.phoneNo = pno;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.phoneTextView = (TextView) child.findViewById(R.id.phoneTextView);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.phoneTextView.setText(phoneNo.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView phoneTextView;
}
}
Database Helper.java
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_PHONENO="pno";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_PHONENO+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
DisplayActivity.java
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_phoneNo = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("Lname", user_phoneNo.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+user_phoneNo.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_phoneNo.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_phoneNo.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PHONENO)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName,user_phoneNo);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Below is an example of storing and fetching data from database.
public class Database extends SQLiteOpenHelper {
public static final String KEY_ID= "id";
public static final String KEY_SURVEY_UPLOAD = "IS_SURVEY_UPLOAD";
public static final String KEY_SURVEY_COMPLETE = "IS_SURVEY_COMPLETE";
public static final String KEY_DEVICE_ID = "DEVICE_ID";
public static final String KEY_LATITUDE = "LATITUDE";
public static final String KEY_LONGITUDE = "LONGITUDE";
public static final String KEY_FILE_ID = "FILE_ID";
public static final String DATABASE_NAME = "DatabaseName";
public static final String DATABASE_TABLE_one = "Table1";
private static final String CREATE_TABLE__NUM = "create table "+DATABASE_TABLE_SURVEY+
" ("+KEY_SURVEY_COMPLETE+" TEXT,"+KEY_FILE_ID+" INTEGER,"+KEY_DEVICE_ID+" TEXT,"+KEY_LATITUDE+" TEXT, "+KEY_LONGITUDE+" TEXT, "+KEY_SURVEY_UPLOAD+" TEXT, "+KEY_SURVEYID+" INTEGER PRIMARY KEY AUTOINCREMENT )";
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
System.out.println("crteate table");
db.execSQL(CREATE_TABLE_SURVEY_CONTENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_one);
onCreate(db);
}
public boolean insertData(SurveyBean bean)
{
System.out.println("insert_SURVEY");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURVEY_COMPLETE, "false");
contentValues.put(KEY_SURVEY_UPLOAD, "0");
contentValues.put(KEY_LATITUDE, bean.getLatitude());
contentValues.put(KEY_LONGITUDE, bean.getLongitude());
contentValues.put(KEY_DEVICE_ID, bean.getDeviceId());
contentValues.put(KEY_FILE_ID, Integer.getInteger(bean.getFileId()));
long id=db.insert(DATABASE_TABLE_SURVEY, null, contentValues);
System.out.println("last inserted ID"+id);
db.close();
return true;
}
public ArrayList<SurveyBean> getAllData(){
ArrayList<SurveyBean> arrayList = new ArrayList<SurveyBean>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cc = db.rawQuery("SELECT *" + " FROM " + DATABASE_TABLE_SURVEY, null);
cc.moveToFirst();
while(cc.isAfterLast() == false){
SurveyBean bean = new SurveyBean();
bean.set_isSurveyComplete(cc.getString(cc.getColumnIndex(KEY_SURVEY_COMPLETE)));
bean.set_isSurveyUpload(cc.getString(cc.getColumnIndex(KEY_SURVEY_UPLOAD)));
bean.set_surveyId(Integer.parseInt(cc.getString(cc.getColumnIndex(KEY_SURVEYID))));
bean.setDeviceId(cc.getString(cc.getColumnIndex(KEY_DEVICE_ID)));
bean.setLatitude(cc.getString(cc.getColumnIndex(KEY_LATITUDE)));
bean.setLongitude(cc.getString(cc.getColumnIndex(KEY_LONGITUDE)));
bean.setFileId(String.valueOf(cc.getInt(cc.getColumnIndex(KEY_FILE_ID))));
arrayList.add(bean);
cc.moveToNext();
}
db.close();
return arrayList ;
}
}
Look i had done a simple app to create a list view from sqlite database in android. Have a look at it.It may help you.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "testdb";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "tbl_details";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('A','vijay','India',20);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('B','ajay','Pakistan',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C','suraj','Bangladesh',30);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D','jayesh','China',35);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('E','ramesh','Nepal',40);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('F','suresh','SriLanka',45);");
}
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ListViewFromSQLiteDB"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ListViewFromSQLiteDB.java
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
}
I have been doing an android database application project recently.When i tried to execute. I cant find the folder 'databases' in the file explorer of the DDMS. I checked the following path /data/data/packagename/databases,but there i could not find databases folder and my database file.
I have attached the code for database helper class
please help me if there is any error that is preventing me from creating the database or is it wrong with my eclipse. Because even some of my existing projects also don't show up with the databases folder inside them.
DBclass.java:
package pack.andyxdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "UniqueID";
public static final String KEY_DEVICETYPE = "Devicetype";
public static final String KEY_RSSI = "RSSI";
private static final String DATABASE_NAME = "DannyZ.db";
private static final String DATABASE_TABLE = "Data";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private static final String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_TIMESTAMP + " INTEGER ,"
+ KEY_UNIQUEID + " INTEGER, " + KEY_DEVICETYPE + " TEXT, " + KEY_RSSI + " INTEGER PRIMARY KEY )";
//CREATE TABLE `DannyZ` (
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertrecord(int timestamp, int uniqueID,String Device, int RSSI) throws SQLException{
// Log.d("", col1);
// Log.d("", col2);
ContentValues IV = new ContentValues();
IV.put(KEY_TIMESTAMP, timestamp);
IV.put(KEY_UNIQUEID, uniqueID );
IV.put(KEY_DEVICETYPE, Device != "");
IV.put(KEY_RSSI, RSSI );
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col1, String col2,String col3,String col4) {
ContentValues values = new ContentValues();
values.put(KEY_TIMESTAMP, col1);
values.put(KEY_UNIQUEID, col2);
values.put(KEY_DEVICETYPE, col3);
values.put(KEY_RSSI, col4);
try {
odb.update(DATABASE_TABLE, values, KEY_RSSI + "=" + rowID, null);
} catch (Exception e) {
}
}
public boolean delete() {
return odb.delete(DATABASE_TABLE, null, null) > 0;
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE + "ORDER BY "+KEY_RSSI, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID, KEY_DEVICETYPE, KEY_RSSI }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID,KEY_DEVICETYPE }, KEY_RSSI + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
also my MainActivity.java code is here. Here i try to insert the data into database by making use of submit button. When i hit submit button the app does not stay for long time and says unfortunately myapp has stopped.my curious concern has been is my database being created or not?
please do help me thanks
MainActivity:
public class MainActivity extends Activity {
private ListView list_lv;
private EditText txt1;
private EditText txt2;
private EditText txt3;
private EditText txt4;
private Button btn1;
private Button btn2;
private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
private ArrayList<String> collist_3;
private ArrayList<String> collist_4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_1 = new ArrayList<String>();
collist_2 = new ArrayList<String>();
collist_3 = new ArrayList<String>();
collist_4 = new ArrayList<String>();
items();
// getData();
}
private void items() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
txt3 = (EditText) findViewById(R.id.editText3);
txt4 = (EditText) findViewById(R.id.editText4);
// list_lv = (ListView) findViewById(R.id.dblist);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getData();
viewData();
}
private void viewData() {
Intent i = new Intent(MainActivity.this, viewActivity.class);
startActivity(i);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
protected void submitData() {
int a = Integer.parseInt( txt1.getText().toString());
int b = Integer.parseInt( txt2.getText().toString());
String c = txt3.getText().toString();
int d = Integer.parseInt( txt4.getText().toString());
db = new DBclass(this);
long num = 0;
try {
db.open();
num = db.insertrecord(a, b,c,d);
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Error Duplicate value"+e,2000).show();
} finally {
//getData();
}
if (num > 0)
Toast.makeText(this, "Row number: " + num, 2000).show();
else if (num == -1)
Toast.makeText(this, "Error Duplicate value", 4000).show();
else
Toast.makeText(this, "Error while inserting", 2000).show();
}
}
Create object of helper class in your activity onCreate method for creating the database file in android app
DBclass db=new DBclass(context);
Hope this will help.
here is the LogCat
I can't post image so i put it in google drive
link here
////////And here is the DB///////
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDB {
public static final String TABLE_USER = "User";
public static final String ID = "ID";
public static final String USERNAME = "USERNAME";
public static final String PASSWORD = "PASSWORD";
public static final String CHKPASSWORD = "CHKPASSWORD";
public static final String SEX = "SEX";
public static final String eat = "eat";
public static final String drink = "drink";
public static final String smoke = "smoke";
public static final String conctrolweigh = "conctrolweigh";
public static final String blosuger = "blosuger";
public static final String hospital = "hospital";
private Context Context = null;
public static final String Education = "Education";
public static class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "diabetes.db";
private static final int DATABASE_VERSION = 1;
//usertable
public DatabaseHelper(Context context, CursorFactory factory) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public static final String TABLE_USER_CREATE =
"CREATE TABLE " + TABLE_USER
+ "("
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ USERNAME + " text , "
+ PASSWORD+ " text ,"
+ CHKPASSWORD+ " text ,"
+ SEX+ " text ,"
+ eat + " text , "
+ drink + " text, "
+ smoke + " text, "
+ conctrolweigh + " text, "
+ blosuger + " text, "
+ hospital + " text, "
+ Education + " text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
// 每次成功打開資料庫後首先被執行
}
#Override
public synchronized void close() {
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_USER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROPB TABLE IF EXISTS " + TABLE_USER);
onCreate(db);
}
}
public DatabaseHelper dbHelper;
public SQLiteDatabase db;
public UserDB(Context context){
this.Context = context;
DatabaseHelper openHelper = new DatabaseHelper(this.Context);
this.db = openHelper.getWritableDatabase();
}
public UserDB open() throws SQLException{
dbHelper = new DatabaseHelper(Context);
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
//add user
public void insertEntry(String ID, String PWD,String CHPW,String SEX,String eat,String drink,String smoke,String conctrolweigh,String blosuger,String hospital,String Education){
if (PWD.equals(CHPW)){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME", ID);
newValues.put("PASSWORD", PWD);
newValues.put("CHKPASSWORD", CHPW);
newValues.put("SEX", SEX);
newValues.put("eat", eat);
newValues.put("drink", drink);
newValues.put("smoke", smoke);
newValues.put("conctrolweigh", conctrolweigh);
newValues.put("blosuger", blosuger);
newValues.put("hospital", hospital);
newValues.put("Education", Education);
db.insert(TABLE_USER, null, newValues);
}else{
}
}
public String getSinlgeEntry(String userName) {
Cursor cursor = db.query("User", null, " USERNAME=?",
new String[] { userName }, null, null, null);
if (cursor.getCount() < 1) // UserName Not Exist
return "Not Exist";
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}
}
//////here is the Activity//////////
public class SelfteachingActivity extends Activity {
Button btnselback,tvartical ,tvfood,tvhealth,tvexcise;
TextView tvid,tvstore,tveat,tvhospital,tvblosuger,tvconctrolweigh,tvdrink,tvsmoke,tvSEX,tvEducation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfteaching);
findViews();
setListeners();
//openDatabase();
String username= (this.getIntent().getExtras().getString("username"));
tvstore.setText(username);
tvid.setText(tvstore.getText().toString());
query();
}
private void query() {
UserDB helper = new UserDB(this);
SQLiteDatabase db = helper.getReadableDatabase();
helper.open();
if(helper.getReadableDatabase() == null){
Log.i("Log Activity Test", "helper is null!!!!!!!!!");
}
String user = tvstore.getText().toString();
try {
Log.i("Log Activity Test", "start db!!");
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
if(cursor!=null){
int rows_num = cursor.getCount();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Integer Id = cursor.getInt(cursor.getColumnIndex("id"));
tvSEX.setText(cursor.getString(cursor.getColumnIndex("SEX")));
tvhospital.setText(cursor.getString(cursor.getColumnIndex("hospital")));
tvblosuger.setText(cursor.getString(cursor.getColumnIndex("blosuger")));
tvdrink.setText(cursor.getString(cursor.getColumnIndex("drink")));
tvconctrolweigh.setText(cursor.getString(cursor.getColumnIndex("conctrolweigh")));
tvsmoke.setText(cursor.getString(cursor.getColumnIndex("smoke")));
tvEducation.setText(cursor.getString(cursor.getColumnIndex("Education")));
tveat.setText(cursor.getString(cursor.getColumnIndex("eat")));
cursor.moveToNext();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
private long exitTime = 0;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
if((System.currentTimeMillis()-exitTime) > 2000){
Toast.makeText(getApplicationContext(), "再按一次返回鍵退出", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void findViews(){
btnselback = (Button)findViewById(R.id.buttonselback);
tvartical = (Button)findViewById(R.id.buttonartical);
tvfood = (Button)findViewById(R.id.buttonfood);
tvhealth = (Button)findViewById(R.id.buttonhealth);
tvexcise = (Button)findViewById(R.id.buttonescise);
tvid = (TextView)findViewById(R.id.tVsid);
tvstore = (TextView)findViewById(R.id.tvstore);
tveat = (TextView)findViewById(R.id.tveat);
tvhospital= (TextView)findViewById(R.id.tvhospital);
tvblosuger= (TextView)findViewById(R.id.tvblosuger);
tvconctrolweigh= (TextView)findViewById(R.id.tvconctrolweigh);
tvdrink= (TextView)findViewById(R.id.tvdrink);
tvsmoke= (TextView)findViewById(R.id.tvsmoke);
tvSEX= (TextView)findViewById(R.id.tvSEX);
tvEducation= (TextView)findViewById(R.id.tvEducation);
}
private void setListeners(){
//回上一頁
btnselback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, LoginActivity.class);
intent.putExtra("username", username );
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//衛教文章
tvartical.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ArticalActivity.class);
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("username", username );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//食物衛教
tvfood.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, FoodActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//健康衛教
tvhealth.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, HealthActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//運動衛教
tvexcise.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ExciseActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.selfteaching, menu);
return true;
}
}
Problem:
1.i don't get any data from SQL but no crash
what is the problem with my code?
the program stop in here
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
and say null pointer , i check the db and is null , i don't know how this happen.
plz help me
Method that you call
SQLiteDatabase db = helper.getReadableDatabase();
returns your null due to your code:
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}