Beginner level SQLite Android App no print result - java

this app Able to run however it cannot print the data from the database,
i also dont know if the data is able to insert or not.
This is MainActivity.java
package com.zikri.sqlitetuto3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText dataET;
Button addB, delB;
TextView dataTV;
MyDBHandler dbHandler;
String getProduct;
Products products;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAndroidApp();
}
public void startAndroidApp(){
dbHandler = new MyDBHandler(this,null,null,1);
dataET = (EditText) findViewById(R.id.dataET);
addB = (Button) findViewById(R.id.addB);
delB = (Button) findViewById(R.id.delB);
dataTV = (TextView) findViewById(R.id.dataTV);
getProduct = dataET.getText().toString();
PrintProduct();
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddProduct(getProduct);
}
});
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DelProduct(getProduct);
}
});
}
public void PrintProduct(){
dataTV.setText(dbHandler.PrintProduct());
dataET.setText("");
}
public void AddProduct(String p){
products = new Products(p);
dbHandler.AddProduct(products);
PrintProduct();
}
public void DelProduct(String p){
dbHandler.DelProduct(p);
PrintProduct();
}
}
This is MyDBHandler.java
package com.zikri.sqlitetuto3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "products.db";
private static final String PRODUCT_TABLE = "product";
private static final String COL_ID = "id";
private static final String COL_PRODUCTNAME = "product_name";
public MyDBHandler(Context context,
String name,SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+PRODUCT_TABLE+" ("+
COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_PRODUCTNAME+" TEXT"+");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
String query = "DROP IF EXIST "+PRODUCT_TABLE;
db.execSQL(query);
onCreate(db);
}
public void AddProduct(Products products){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_PRODUCTNAME,products.get_productname());
db.insert(PRODUCT_TABLE,null,values);
db.close();
}
public void DelProduct(String product){
SQLiteDatabase db = getWritableDatabase();
String query = "DELETE FROM "+PRODUCT_TABLE+
"WHERE "+COL_PRODUCTNAME+" = "+product+";";
db.execSQL(query);
db.close();
}
public String PrintProduct(){
SQLiteDatabase db = getWritableDatabase();
String printproductstring = "";
String query = "SELECT * FROM "+PRODUCT_TABLE+";";
Cursor cur = db.rawQuery(query,null);
cur.moveToFirst();
while(cur.moveToNext()){
printproductstring =
printproductstring+cur.getString(cur.getColumnIndex("product_name"));
printproductstring = printproductstring + "\n";
}
db.close();
return printproductstring;
}
}
This is Product.java
package com.zikri.sqlitetuto3;
public class Products {
private int _ID;
private String _productname;
public Products() {}
public Products(String productname) {
this._productname = productname;
}
public void set_ID(int _ID) {
this._ID = _ID;
}
public int get_ID() {
return _ID;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public String get_productname() {
return _productname;
}
}
this is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.zikri.sqlitetuto3.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/dataET" />
<Button
android:text="INSERT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/dataET"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/addB" />
<Button
android:text="Delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/addB"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/delB" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/dataTV" />

it it very difficult to see database in android is stoered or not you can see eror on logcate if no error means it is stored but not every time .if you want still you have to see in devide manager its difficult onother solution tack one rooted mobile and intrall root brouser go to android folder inside android folder go to dada inside again go to data and then your package name then database then see there is any file which name related to your database copy this into pc and download sqllite brouser . this long process you can do you will get 100% chance to get database file.if it is created

You should take input when the button is clicked otherwise getProduct will always be empty
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
AddProduct(getProduct);
}
});
and do the same while deletion
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
DelProduct(getProduct);
}
});
Furthermore you can confirm the successful insertion of data by the return value of insert which is long type and defined as
the row ID of the newly inserted row, or -1 if an error occurred
so use it
long id = db.insert(PRODUCT_TABLE,null,values);
// you can now check the value of id through Logs or Toast
db.close();

Related

Can any one tell me what is the error in below code related to storing data into sqlite in android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/fl1"
android:gravity="center"
android:background="#android:color/darker_gray">
<ImageView
android:id="#+id/imgback"
android:src="#drawable/background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="#string/back"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ll1"
android:layout_gravity="center"
android:orientation="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10sp"
android:textSize="32sp"
android:hint="#string/Uname"
android:id="#+id/eduname"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:hint="#string/Pword"
android:id="#+id/edpword"
android:inputType="textPassword"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox"
android:text="#string/checkboxtxt"
/>
<ImageButton
android:id="#+id/imglogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/imgbt"
android:layout_toEndOf="#+id/checkbox"
android:layout_toRightOf="#+id/checkbox"
android:onClick="login"
android:src="#drawable/loginkey" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rl2"
android:gravity="end"
>
<ImageButton
android:id="#+id/imgsignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/tvnotamem"
android:layout_toEndOf="#+id/tvnotamem"
android:layout_centerVertical="true"
android:contentDescription="#string/imgsignup"
android:onClick="signup"
android:src="#drawable/sign_up"/>
<TextView
android:id="#+id/tvnotamem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/notamem" />
</RelativeLayout>
</LinearLayout>
</FrameLayout>
MainActivity.java
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
public class MainActivity extends Activity {
EditText eduname,edpword;
CheckBox checkbox;
ImageButton imglogin,imgsignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
init();
}
public void init()
{
eduname = (EditText) findViewById(R.id.eduname);
edpword = (EditText) findViewById(R.id.edpword);
}
public void login(View v)
{
}
public void signup(View v)
{
Intent i = new Intent(this,SignUp.class);
startActivity(i);
}
}
SignUp.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:baselineAligned="true"
android:layout_marginBottom="10dp"
android:background="#drawable/background1">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#FFFFFFFF"
android:id="#+id/edrname"
android:hint="#string/edrname"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#FFFFFFFF"
android:inputType="textPassword"
android:id="#+id/edrpword"
android:hint="#string/edrpword"/>
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#FFFFFFFF"
android:inputType="textPassword"
android:id="#+id/edrconfrmpword"
android:hint="#string/edrconfrmpword"/>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edphoto"
android:textSize="24sp"
android:hint="#string/edbrowsehint"
android:textColor="#FFFFFFFF"
android:layout_weight="1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnbrowse"
android:text="#string/btnbrowse"
android:textSize="24sp"
android:textColor="#FFFFFFFF"
android:layout_weight="1"
android:onClick="browse"/>
</LinearLayout>
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="#+id/submit"
android:onClick="submit"
android:textSize="24sp"
android:layout_marginTop="30dp"
android:text="#string/submit"/>
</LinearLayout>
SignUp.java
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SignUp extends Activity{
static EditText runame,rpword,rconfpword,edphoto;
SQLiteDatabase db;
String addrsoffile;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
init();
}
public void init()
{
runame=(EditText) findViewById(R.id.edrname);
rpword=(EditText) findViewById(R.id.edrpword);
rconfpword=(EditText) findViewById(R.id.edrconfrmpword);
edphoto = (EditText) findViewById(R.id.edphoto);
}
public void browse(View v){
Intent i = new Intent(this,FileChooser.class);
startActivityForResult(i,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1)
{
if(resultCode == RESULT_OK)
{
addrsoffile = data.getStringExtra("GetFileName");
edphoto.setText(addrsoffile);
}
}
}
public void submit(View v)
{
Intent i = new Intent(this,DataHelper.class);
startActivity(i);
}
}
DataBaseHandler.java
package com.example.login;
public class DataBaseHandler {
String uname,pword,confpword;
public DataBaseHandler(){
}
public DataBaseHandler(String uname,String pword,String confpword){
this.uname = uname;
this.pword = pword;
this.confpword = confpword;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPword() {
return pword;
}
public void setPword(String pword) {
this.pword = pword;
}
public String getConfpword() {
return confpword;
}
public void setConfpword(String confpword) {
this.confpword = confpword;
}
}
DataHelper.java
package com.example.login;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class DataHelper extends SQLiteOpenHelper {
public static final String Database_Name = "LoginDetails.db";
public static final int Database_Version = 1;
public static final String Table_Name = "Registration";
int idno = 1;
DataBaseHandler dbh;
SQLiteDatabase db;
Context c;
public DataHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
this.c = context;
dbh = new DataBaseHandler((SignUp.runame).getText().toString(), (SignUp.rpword).getText().toString(), (SignUp.rconfpword).getText().toString());
}
#Override
public void onCreate(SQLiteDatabase db) {
String Sqlquery = "Create table if not exists "+Table_Name+" ("+idno+" integer primary key autoincrement,"+ " uname text not null,"+ " pword text not null,"+" confpword text not null)";
db.execSQL(Sqlquery);
insertEntry(dbh.uname, dbh.pword, dbh.confpword);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop table if Exists "+Table_Name);
}
public void insertEntry(String uname,String pword,String cnfrmpword)
{
ContentValues val = new ContentValues();
val.put("uname", uname);
val.put("pword", pword);
val.put("cnfrmpword", cnfrmpword);
db = getWritableDatabase();
db.insert(Table_Name, null, val);
Toast.makeText(c, "Data inserted Successfully", Toast.LENGTH_LONG).show();
}
}
I got an error at submit button click in SignUp.
when I am trying to execute it. I was unable to understand it.
So If any one help me I will be great full and thanks in advance.
Try Below code , it may Help you for Sign up
Add this code in your Sign up page for Inserting to Sqlite
private EditText fname, lname, email, phone, pass, cpass;
private Button Save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
// for Database
dbHelper = new DataBaseConnector_forsignUp(this);
Signup = (TextView) findViewById(R.id.textView1);
fname = (EditText) findViewById(R.id.editText1);
lname = (EditText) findViewById(R.id.editText2);
email = (EditText) findViewById(R.id.editText3);
phone = (EditText) findViewById(R.id.editText4);
pass = (EditText) findViewById(R.id.editText5);
cpass = (EditText) findViewById(R.id.editText6);
Save = (Button) findViewById(R.id.button1);
Save.setOnClickListener(this);
}
public void onClick(View v) {
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
switch (v.getId()) {
case R.id.button1:
String firstname = fname.getText().toString();
String lastname = lname.getText().toString();
String Email = email.getText().toString();
String phonenumber = phone.getText().toString();
String password = pass.getText().toString();
String confpassword = cpass.getText().toString();
DataBaseConnector_forsignUp dbconnector = new DataBaseConnector_forsignUp(this);
long id = dbconnector.insertData(firstname, lastname, Email,
phonenumber, password, status);
break;
}
}
DataBaseHelper_forsignUp.java
public class DataBaseHelper_forsignUp extends SQLiteOpenHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "firstname";
public static final String KEY_LNAME = "lastname";
public static final String KEY_EMAIL = "email";
public static final String KEY_PHONENUMBER = "Phonenumber";
public static final String KEY_PASSWORD = "Password";
public static final String KEY_CONFPASSWORD = "ConfPassword";
public static final String KEY_UPDATESTATUS = "Status";
public static final String KEY_DATEOFBIRTH="Dateofbirth";
public static final String KEY_LOCATION="Location";
public static final String KEY_ADDRESS="Address";
private static String DATABASE_NAME = "Signup";
public static String TABLE_NAME = "SIGNUP";
// public static final int DATABASE_VERSION = 1;
public DataBaseHelper_forsignUp(Context context, String name,
CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + TABLE_NAME + "("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " firstname TEXT NOT NULL,"
+ " lastname TEXT NOT NULL, "
+ " email TEXT NOT NULL,"
+ " Phonenumber TEXT NOT NULL,"
+ " Password TEXT NOT NULL,"
+ " Dateofbirth TEXT ,"
+ " Location TEXT ,"
+ " Address TEXT ,"
+ " Status TEXT NOT NULL);";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
}
DataBaseConnector_forsignUp.java
public class DataBaseConnector_forsignUp
{
static final String KEY_ROWID = "_id";
static final String KEY_FNAME = "Firstname";
static final String KEY_LNAME = "Lastname";
static final String KEY_EMAIL = "Email";
static final String KEY_PHONENUMBER = "Phonenumber";
static final String KEY_PASSWORD = "Password";
static final String KEY_CONFPASSWORD = "ConfPassword";
static final String KEY_UPDATESTATUS = "Status";
public static final String KEY_DATEOFBIRTH="Dateofbirth";
public static final String KEY_LOCATION="Location";
public static final String KEY_ADDRESS="Address";
private static String DATABASE_NAME = "Signup";
public static String TABLE_NAME = "SIGNUP";
private static final int DATABASE_VERSION = 1;
public SQLiteDatabase database;
private DataBaseHelper_forsignUp dbOpenHelper;
public static String email12="";
public DataBaseConnector_forsignUp(Context context)
{
dbOpenHelper = new DataBaseHelper_forsignUp(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public DataBaseConnector_forsignUp open() throws SQLException
{
database = dbOpenHelper.getWritableDatabase();
return this;
}
/*// Close Database function
public void close()
{
if (dbOpenHelper != null)
dbOpenHelper.close();
}*/
public void close()
{
database.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return database;
}
//inserting the data to db
public long insertData(String firstname, String lastname, String email,String phonenumber,String password,String status)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBaseConnector_forsignUp.KEY_FNAME, firstname);
values.put(DataBaseConnector_forsignUp.KEY_LNAME, lastname);
values.put(DataBaseConnector_forsignUp.KEY_EMAIL, email);
values.put(DataBaseConnector_forsignUp.KEY_PHONENUMBER, phonenumber);
values.put(DataBaseConnector_forsignUp.KEY_PASSWORD, password);
open();
long id = db.insert(DataBaseConnector_forsignUp.TABLE_NAME, null , values);
close();
return id;
}
}
In submit button of SignUp class startActivity calls SQLiteOpenHelper class it is not correct it should call an Activity class.

Android: Retrieving Data and Display in ListView

I am very new to Android development and a bit rusty on my Java so please bear with me. I am trying to accomplish the following:
Upon launching the app all the users courses and info will populate in the main activity and a button option to add a new course will be present. Initially no courses will show until they are added.
Clicking add course will present a new activity and upon saving data entry a new course record will be inserted into the DB. Control will move back to the Main Activity where the listview will refresh with the newly added course. Below are the 4 classes and two layouts I'm working with.
PROBLEM: At this point I'm unsuccessful at confirming that data was inserted and pulling that data back out and displaying it on screen. I think I've identified the issue being that the course_list is not being populated with courses, but since I"m not getting any errors I'm struggling to identify the real problem. Any insight or guidance would be greatly appreciated!
MainActivity.Java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
private ListView courseListView;
private ArrayList<Course> course_list = new ArrayList<Course>();
private ArrayList<String> course_names = new ArrayList<String>();
private ArrayAdapter<String> ap;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
courseListView = (ListView) findViewById(R.id.course_list);
// Init database
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
initAdapter();
}
#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. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when Add Course button is pressed
public void onClick( View v ) {
Intent intent = new Intent(v.getContext(), AddCourseActivity.class);
v.getContext().startActivity(intent);
}
//
private void initAdapter() {
if( course_list.size() != 0) {
course_list.clear();
course_list = db.getCourses();
for (int i = 0; i < course_list.size(); ++i) {
course_names.add(course_list.get(i).getCourseName());
}
ap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, course_names);
courseListView.setAdapter(ap);
}
}
}
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Courses";
public static final String COURSE_TABLE = "MyCourses";
public static final String KEY_COURSE_NUM = "CourseNum";
public static final String KEY_COURSE_NAME = "CourseName";
public static final String KEY_COURSE_DESC = "CourseDesc";
public static final String KEY_DATE = "Date";
public static final String KEY_TIME = "Time";
public static final String KEY_INSTRUCTOR = "Instructor";
private ArrayList<Course> courseList = new ArrayList<Course>();
// Constructor, Create DB
public DatabaseHelper( Context context ) {
super(context, DATABASE_NAME, null, 1) ;
}
// Create the MyCourses table
public void onCreate( SQLiteDatabase db ) {
db.execSQL("CREATE TABLE " + COURSE_TABLE + " (_id INTEGER PRIMARY KEY, "
+ KEY_COURSE_NUM + " TEXT, "
+ KEY_COURSE_NAME + " TEXT, "
+ KEY_COURSE_DESC + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_TIME + " TEXT, "
+ KEY_INSTRUCTOR + " TEXT)");
}
// Upgrade the MyCourses table
public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {
// Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + COURSE_TABLE);
// Create table again
onCreate(db);
}
// Add a new course
public void addCourse( Course course ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_COURSE_NUM, course.getCourseNum());
contentValues.put(KEY_COURSE_NAME, course.getCourseName());
contentValues.put(KEY_COURSE_DESC, course.getCourseDesc());
contentValues.put(KEY_DATE, course.getCourseDate());
contentValues.put(KEY_TIME, course.getCourseTime());
contentValues.put(KEY_INSTRUCTOR, course.getCourseInstructor());
db.insert(COURSE_TABLE, null, contentValues);
db.close();
}
// Get all courses, assign to array of course objects an return array
public ArrayList<Course> getCourses() {
courseList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + COURSE_TABLE, null);
// Loop through cursor, extract data and assign to item Course object
if( cursor.getCount()!=0) {
if( cursor.moveToFirst() ) {
do {
Course item = new Course();
item.setCourseNum(cursor.getString(cursor.getColumnIndex(KEY_COURSE_NUM)));
item.setCourseName(cursor.getString(cursor.getColumnIndex(KEY_COURSE_NAME)));
item.setCourseDesc(cursor.getString(cursor.getColumnIndex(KEY_COURSE_DESC)));
item.setCourseDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
item.setCourseTime(cursor.getString(cursor.getColumnIndex(KEY_TIME)));
item.setCourseInstructor(cursor.getString(cursor.getColumnIndex(KEY_INSTRUCTOR)));
// Add the object to the courseList array of Courses
courseList.add(item);
} while( cursor.moveToNext());
}
}
cursor.close();
db.close();
return courseList;
}
}
Course.java
public class Course {
private String courseNum;
private String courseName;
private String courseDesc;
private String date;
private String time;
private String instructor;
// Empty constructor
public Course() {
}
// Constructor for new course
public Course(Course course) {
this.courseNum = course.courseNum;
this.courseName = course.courseName;
this.courseDesc = course.courseDesc;
this.date = course.date;
this.time = course.time;
this.instructor = course.instructor;
}
// Get courseNum
public String getCourseNum() {
return courseNum;
}
// Set courseNum
public void setCourseNum( String courseNum ) {
this.courseNum = courseNum;
}
// Get courseName
public String getCourseName() {
return courseName;
}
// Set courseName
public void setCourseName( String courseName ) {
this.courseName = courseName;
}
// Get courseDesc
public String getCourseDesc() {
return courseDesc;
}
// Set courseDesc
public void setCourseDesc( String courseDesc ) {
this.courseDesc = courseDesc;
}
// Get date
public String getCourseDate() {
return date;
}
// Set date
public void setCourseDate( String date ) {
this.date = date;
}
// Get time
public String getCourseTime() {
return time;
}
// Set time
public void setCourseTime( String time ) {
this.time = time;
}
// Get instructor
public String getCourseInstructor() {
return instructor;
}
// Set instructor
public void setCourseInstructor( String instructor ) {
this.instructor = instructor;
}
}
AddCourseActivity.java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class AddCourseActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
}
#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_add_course, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when Save button is pressed
public void saveCourse(View v) {
Course c = new Course();
DatabaseHelper db = new DatabaseHelper(this);
EditText num = (EditText) findViewById(R.id.courseNum);
c.setCourseNum(num.getText().toString());
EditText name = (EditText) findViewById(R.id.courseName);
c.setCourseName(name.getText().toString());
EditText desc = (EditText) findViewById(R.id.courseDesc);
c.setCourseDesc(desc.getText().toString());
EditText date = (EditText) findViewById(R.id.courseDate);
c.setCourseDate(date.getText().toString());
EditText time = (EditText) findViewById(R.id.courseTime);
c.setCourseTime(time.getText().toString());
EditText inst = (EditText) findViewById(R.id.courseInstructor);
c.setCourseInstructor(inst.getText().toString());
db.addCourse(c);
// Return to Main Activity
Intent intent = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(intent);
}
// Called when Cancel button is pressed
public void cancel(View v) {
// Return to Main Activity
Intent intent = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(intent);
}
}
Activity_Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="My Courses"
android:textColor="#FFFFFF"
android:textSize="30dp"
android:background="#000000"/>
<Button
android:id="#+id/addCourse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Course"
android:onClick="onClick"/>
<ListView
android:id="#+id/course_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
Activity_Add_Course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Add New Course"
android:textColor="#FFFFFF"
android:textSize="30dp"
android:background="#000000"/>
<EditText
android:id="#+id/courseNum"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course #"/>
<EditText
android:id="#+id/courseName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Name"/>
<EditText
android:id="#+id/courseDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="6"
android:hint="Course Description"/>
<EditText
android:id="#+id/courseDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Date"/>
<EditText
android:id="#+id/courseTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Time"/>
<EditText
android:id="#+id/courseInstructor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Instructor"/>
<Button
android:id="#+id/saveCourse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="saveCourse"/>
<Button
android:id="#+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
android:onClick="cancel"/>
</LinearLayout>

showing the content of the table in database a list cannot be undone

I have just started to learn programming and I try to build a simple database for my exercise and I try to show all the content of the table in my database into a list in another layout but I don't know why the content isn't showing up in the list.. please help me ..
here is my apps sample
here is my activity for putting all the content in the list:
package com.DennisTA;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DaftarIstilah extends Activity{
private DataKamus dbhelper;
private SQLiteDatabase db = null;
private ListView listContent = null;
private Cursor kamusCursor = null;
CustomCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbhelper = new DataKamus(this);
setContentView(R.layout.daftaristilah);
listContent = (ListView) findViewById(R.id.list1);
isDataListView();
}
private void isDataListView() {
try {
db = dbhelper.getWritableDatabase();
kamusCursor = db.query("kamus", new String[] { "_id", "inggris",
"arti", "penjelasan" }, "_id>0", null, null, null, null);
// startManagingCursor( jasaCursor);
/*
* Create an array to specify the fields we want to display in the
* list (only the 'inggris,arti,penjelasan' column in this case)
*/
String[] from = new String[] { "inggris", "arti", "penjelasan" };
/*
* and an array of the fields we want to bind those fieiplds to (in
* this case just the textView 'inggris,arti,penjelasan' from our new row.xml
* layout above)
*/
int[] to = new int[] { R.id.inggris, R.id.arti, R.id.penjelasan };
/* Now create a simple cursor adapter.. */
adapter = new CustomCursorAdapter(this, R.layout.baris, kamusCursor,
from, to);
// listView.setAdapter(adapter);
listContent.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
} catch (Exception e) {
}
}
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super (context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.d("NewView", "*****xxx");
View v = inflater.inflate(R.layout.baris, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// 1 is the column where you're getting your data from
String inggris = c.getString(1);
String penjelasan = c.getString(3);
String arti = c.getString(2);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.inggris);
TextView des_text = (TextView) v.findViewById(R.id.penjelasan);
TextView id_text = (TextView) v.findViewById(R.id.arti);
des_text.setText(penjelasan);
id_text.setText(arti);
if (name_text != null) {
name_text.setText(inggris);
}
}
}
}
here is my baris.xml sample :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingBottom="5sp"
android:paddingTop="5sp" >
<TextView
android:id="#+id/inggris"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/arti"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/inggris" />
<TextView
android:id="#+id/penjelasan"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/arti" />
</RelativeLayout>
here is my daftar istilah.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text = "Inggris"
android:textSize="20sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text = "Arti"
android:textSize="20sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView2"
android:text = "Penjelasan"
android:textSize="20sp" />
<ListView android:id="#+id/list1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight = "1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"/>
</RelativeLayout>
here is my class that contain the database:
package com.DennisTA;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataKamus extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbkamus";
public static final String INGGRIS= "inggris";
public static final String ARTI = "arti";
public static final String PENJELASAN = "penjelasan";
//Constructor DataKamus untuk initiate database
public DataKamus(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"inggris TEXT, arti TEXT, penjelasan TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(ARTI, "lari");
cv.put(PENJELASAN, "laufen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "walk");
cv.put(ARTI, "jalan");
cv.put(PENJELASAN, "gehen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "read");
cv.put(ARTI, "membaca");
cv.put(PENJELASAN, "lesen");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
here is my main activity :
package com.DennisTA;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtArti;
private EditText txtPenjelasan;
private DataKamus datakamus = null;
public static final String INGGRIS = "inggris";
public static final String ARTI = "arti";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DataKamus(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtArti = (EditText) findViewById(R.id.txtArti);
txtPenjelasan = (EditText) findViewById(R.id.txtPenjelasan);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtArti.setText(bhsindonesia);
txtPenjelasan.setText(bhsjerman);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Retrieving from database as follows:
String selectQuery = "SELECT * FROM " + Variables.TABLE_ORDER
+ " WHERE " + Variables.TABLE_ORDER_CATEGORY ;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Food_Id", cursor.getString(0));
cart_Array_List.add(map);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
}
Try extending a BaseAdapter and ovverride the following method:
#Override
public int getCount() {
return arraylist.size();
}

Error: deleting all rows instead of 1 row Android

I am currently using Java Eclipse to make an android app. This app has an SQLite database that contains data. I can view this data in a list. And i can also add items to this database fine. I am now tring to delete a specific row from the database. But whenever i try to it deletes all the rows as oppose to the one the user has selected.
Here is my adapter:
package com.example.beer_budget3;
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;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Here is my deleting page:
package com.example.beer_budget3;
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.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
db.open();
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
And here is my XML file for the deleting page:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
I personally think the error is in this line in the adapter:
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
Because i understand you have to be very specific with where you places your spaces and quotations. But i have changed this line of code around a few times and couldn't fix my problem.
Any advice would be much appreciated!
Your function here :
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
should be
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ Pub_Name+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
You specify the column name instead of the value

Unfortunately <app-name> has stopped

I have written a code for an app that is supposed to be for a Virtual Campus tour. I have shared below the various files (3 class files) and 3 xml files and all have no errors in them.
The app has installed on the emulator successfully but throws up the error mentioned in the heading.
I am very new to android and to java so any help will be really appreciated!
Can anyone spot where I have gone wrong?
Code for one class by the name BuildingEdit
package com.example.udbuildingtour;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class BuildingEdit extends Activity {
private EditText mNameText;
private EditText mLatText;
private EditText mLongiText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.building_edit);
setTitle(R.string.edit_building);
mNameText = (EditText) findViewById(R.id.name);
mLatText = (EditText) findViewById(R.id.lat);
mLongiText = (EditText) findViewById(R.id.longi);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String name = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String lat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String longi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mRowId = extras.getLong(BuildingsDbAdapter.KEY_ID);
if (name != null) {
mNameText.setText(name);
}
if (lat != null) {
mLatText.setText(lat);
}
if (longi != null) {
mLongiText.setText(longi);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString(BuildingsDbAdapter.KEY_BUILDINGNAME, mNameText.getText().toString());
bundle.putString(BuildingsDbAdapter.KEY_LAT, mLatText.getText().toString());
bundle.putString(BuildingsDbAdapter.KEY_LONGI, mLongiText.getText().toString());
if (mRowId != null) {
bundle.putLong(BuildingsDbAdapter.KEY_ID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
}
Code for class UDBuildingTour
package com.example.udbuildingtour;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
public class UDBuildingTour extends ListActivity {
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 BuildingsDbAdapter mDbHelper;
private Cursor mBuildingsCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.building_edit);
mDbHelper = new BuildingsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createBuilding();
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.deleteBuilding(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createBuilding() {
Intent i = new Intent(this, BuildingEdit.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 = mBuildingsCursor;
c.moveToPosition(position);
Intent i = new Intent(this, BuildingEdit.class);
i.putExtra(BuildingsDbAdapter.KEY_ID, id);
i.putExtra(BuildingsDbAdapter.KEY_BUILDINGNAME, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_BUILDINGNAME)));
i.putExtra(BuildingsDbAdapter.KEY_LAT, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_LAT)));
i.putExtra(BuildingsDbAdapter.KEY_LONGI, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_LONGI)));
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:
Long rowId = extras.getLong(BuildingsDbAdapter.KEY_ID);
String name = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String lat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String longi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mDbHelper.createBuilding(rowId, name, lat, longi);
fillData();
break;
case ACTIVITY_EDIT:
Long Id = extras.getLong(BuildingsDbAdapter.KEY_ID);
if (Id != null) {
String editName = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String editLat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String editLongi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mDbHelper.updateBuilding(Id, editName, editLat, editLongi);
}
fillData();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.udbuilding_tour, menu);
return true;
}
private void fillData() {
// TODO Auto-generated method stub
// Get all of the rows from the database and create the item list
mBuildingsCursor = mDbHelper.fetchAllBuildings();
startManagingCursor(mBuildingsCursor);
// Create an array to specify the fields we want to display in the list (only BUILDINGNAME)
String[] from = new String[]{BuildingsDbAdapter.KEY_BUILDINGNAME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter building =
new SimpleCursorAdapter(this, R.layout.buildings_row, mBuildingsCursor, from, to);
setListAdapter(building);
}
}
Code for BuildingsDBAdapter
package com.example.udbuildingtour;
import java.io.BufferedReader;
import java.io.FileReader;
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 BuildingsDbAdapter {
public static final String KEY_ID = "_id";
public static final String KEY_BUILDINGNAME = "name";
public static final String KEY_LAT = "lat";
public static final String KEY_LONGI = "longi";
private static final String TAG = "BuildingsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table buildings (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "Buildings";
private static final String DATABASE_TABLE = "UDBuildings";
private static final int DATABASE_VERSION = 1;
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 BuildingsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public BuildingsDbAdapter open() throws SQLException {
// TODO Auto-generated method stub
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean deleteBuilding(long id) {
// TODO Auto-generated method stub
return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
public long createBuilding(Long id, String name, String lat, String longi) {
// TODO Auto-generated method stub
ContentValues initialValues = new ContentValues();
try{
BufferedReader in = new BufferedReader(new FileReader("UDBuildings.txt"));
String s;
while((s = in.readLine()) != null){
String[] var = s.split(":");
//var[0]=ID,var[1]=Name etc etc
initialValues.put(KEY_BUILDINGNAME, var[1]);
initialValues.put(KEY_LAT, var[2]);
initialValues.put(KEY_LONGI, var[3]);
initialValues.put(KEY_ID, var[0]);
}
}catch(Exception e){
e.printStackTrace();
}
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Return a Cursor over the list of all buildings in the database
*
* #return Cursor over all buildings
*/
public Cursor fetchAllBuildings() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_BUILDINGNAME,
KEY_LAT, KEY_LONGI}, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the building that matches the given building id
*
* #param id of building to retrieve
* #return Cursor positioned to matching building, if found
* #throws SQLException if building could not be found/retrieved
*/
public Cursor fetchBuilding(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID,
KEY_BUILDINGNAME, KEY_LAT, KEY_LONGI}, KEY_ID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Update the building using the details provided. The building to be updated is
* specified using the id, and it is altered to use the name and lat, longi
* values passed in
*
* #param id of building to update
* #param name value to set building name to
* #param lat value to set building lat to
* #param longi value to set building longi to
* #return true if the building was successfully updated, false otherwise
*/
public boolean updateBuilding(Long rowId, String editName, String editLat, String editLongi) {
// TODO Auto-generated method stub
ContentValues args = new ContentValues();
args.put(KEY_BUILDINGNAME, editName);
args.put(KEY_LAT, editLat);
args.put(KEY_LONGI, editLongi);
return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
}
xml code for building_edit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name" />
<EditText android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lat" />
<EditText android:id="#+id/lat" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="longi" />
<EditText android:id="#+id/longi" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical" />
<Button android:id="#+id/confirm"
android:text="confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
xml code for buildings_row
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#+id/text1" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
xml code for buildings_list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="no_buildings"/>
</LinearLayout>
androidmanifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udbuildingtour"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.udbuildingtour.UDBuildingTour"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BuildingEdit"></activity>
</application>
</manifest>
android:id="#android:id/list"
and not this...
android:id="#+id/android:list"
in your ListView
I see two problems:
The UDBuildingTour activity is not using buildings_list as the content view. As a result, there is no ListView and the base ListActivity will throw an exception when you call setListAdapter(building); in fill_data. In onCreate(), you should change this:
setContentView(R.layout.building_edit);
to:
setContentView(R.layout.building_list);
As #stir-fried points out, the android:id attribute for the ListView in buildings_list should be #android:id/list, not #+id/android:list (which I'm surprised compiles). For a custom list activity layout, you need to use the predefined Android id for the ListView, not autogenerating your own id. Similarly, the empty-list view should have android:id=#android:id/empty, not #+id/android:empty.

Categories

Resources