Android application - Logging causing error - android

Hi I am working with my application project.. It just happen that after I click on the login button, an error message pops out saying that Sorry! The application has stopped unexpectedly. Please try again. What is the error of this? please help thanks
This was my code for the data base of the user..
package com.gomez.android;
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 dbuser{
public static final String user_name = "username";
public static final String user_password = "password";
public static final String row_id = "_id";
private static final String TAG = "UdbAdapter";
private DatabaseHelper UdbHelper;
private SQLiteDatabase Udb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table pages (_id integer primary key autoincrement, "
+ "username text not null, password text not null);";
private static final String DATABASE_NAME = "UserAccount";
private static final String DATABASE_TABLE = "User";
private static final int DATABASE_VERSION = 1;
private Context context = null;
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 pages");
onCreate(db);
}
}
public dbuser(Context cntxt) {
this.context = cntxt;
UdbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
Udb = UdbHelper.getWritableDatabase();
}
public void close() {
UdbHelper.close();
}
public long createaccount(String username, String password)
{
Udb = UdbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(user_name, username);
initialValues.put(user_password, password);
return Udb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password)throws SQLException
{
Cursor mCursor = Udb.rawQuery(DATABASE_TABLE, new String[]{username,password});
if (mCursor != null){
if(mCursor.getCount() > 0){
return true;
}
}
return false;
}
}
and this was my login page code.....
package com.gomez.android;
import com.gomez.android.dbuser;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends Activity{
//Declare views
private EditText uname;
private EditText pword;
private Button btnlogin;
private Button btncancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set Activity Layout
setContentView(R.layout.login);
//Get EditText and Button References
uname = (EditText)findViewById(R.id.username);
pword = (EditText)findViewById(R.id.password);
btnlogin = (Button)findViewById(R.id.login_enter);
btncancel = (Button)findViewById(R.id.cancel);
//set Click Listener
btnlogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check Login
final String username = uname.getText().toString();
final String password = pword.getText().toString();
dbuser users = new dbuser(login.this);
users.open();
if(users.Login(username, password)){
if(username.equalsIgnoreCase(username)&& password.equalsIgnoreCase(password))
{
Toast.makeText(login.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
Intent i = new Intent(login.this, firstpage.class);
startActivity(i);
}
else{
Toast.makeText(login.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
users.close();
}
}
});
btncancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//close application
finish();
}
});
}
}

I can't be sure what the problem is with your code since you didn't provide any information from the LogCat, but it is possible that getWriteableDatabase() is returning a cached database when running the application (I often ran into this problem when implementing and testing a database for the first time).
To ensure this is not the problem, go to Settings -> Applications -> Manage Applications -> [Your Application] -> Clear Data, before running the application from Eclipse. This is an easy way to ensure you are working with your most up-to-date implementation during the early stages of implementing/testing the database.
This very well might not be the problem, but it is one of those things that you wouldn't expect to be the issue (which often leads to hours of frustration), so I thought I'd bring it up :).

Related

Application crashes on Inserting into SQLITE database [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
There goes the code . I just cant figure out what is the problem. I am just taking the email and password as input from user and trying to store into a table named stu. The application crashes on clicking the sign in button which redirects to a next page using "intent" and inserting values into a table.
It would be of great help if problem could be identified that cause app to crash .
Thanks
Database Helper.java
package com.example.zain.smd1;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "student.db";
public static final String Table_name = "stu";
public static final String COL1 = "Id";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASS";
private static final String PASS = "PASS";
private static final String EMAIL = "EMAIL";
public DatabaseHelper(Context context) {
super(context,DB_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_name + " (Id INTEGER PRIMARY KEY AUTOINCREMENT, EMAIL TEXT , PASS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+Table_name);
onCreate(db);
}
public boolean insertdata(String email , String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(EMAIL,email);
content.put(PASS,pass);
long result = db.insert(Table_name,null,content);
if (result==-1){
return false;
}
else
return true;
}
}
Main Activity.java
package com.example.zain.smd1;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText et1,et2;
String email,pass;
RelativeLayout r1;
SharedPreferences sp;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}
public void login(View view){
email = et1.getText().toString();
pass = et2.getText().toString();
if(email.equals("admin")&& pass.equals("admin")){
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
r1.setBackgroundColor(Color.RED);
/*sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor e= sp.edit();
e.putString("name",email);
e.putString("password",pass);
e.apply();*/
boolean ischecked = db.insertdata(et1.getText().toString(),et2.getText().toString());
if(ischecked==true) {
Toast.makeText(getApplicationContext(),
"Added",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
else {
r1.setBackgroundColor(Color.GREEN);
Toast.makeText(getApplicationContext(),
"Invalid password or email",Toast.LENGTH_SHORT).show();
}
/*
String name=sp.getString("name","");
String pass= sp.getString("password","");
et1.setText(name);
et2.setText(pass);
*/
}
}
Application crashes on inserting into SQLite database . I just couldn't figure out whats wrong
Try to uninstall the existing application from your Debugging device and then install it again. Sometimes when you change the structure of your table after installing it and again you are installing then it doesn't create new table.
you should try this...
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add this line in your code..
db = new DatabaseHelper(this);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}

Please tell me what is wrong in the piece of code written below

I have written a piece of code, which populates a database. However, when i execute that code in my android device or emulator, it gives an error "sorry app1 has stopped working" Please help me out to find out what's wrong.
the MainActivity.java file
package cu_coders.app1;
import android.net.Uri;
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;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
public final EditText e=(EditText)findViewById((R.id.text1));
public final file1 f=new file1();
TextView t=(TextView)findViewById(R.id.textView1);
final myDB x=new myDB(this, null, null, 1);
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
Button enter=(Button)findViewById(R.id.button1);
Button delete=(Button)findViewById(R.id.button2);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = e.getText().toString();
f.set_name(s);
x.addItem(f);
t.setText(x.printTable());
}
});
}
}
A CLASS NAMED FILE1.JAVA
package cu_coders.app1;
/**
* Created by user pc on 03-10-2016.
*/
public class file1 {
private int _roll;
private String _name;
public file1() {
}
public file1(String _name) {
this._name = _name;
}
public int get_roll() {
return _roll;
}
public String get_name() {
return _name;
}
public void set_roll(int _roll) {
this._roll = _roll;
}
public void set_name(String _name) {
this._name = _name;
}
}
THE CLASS FOR DATABASE MANAGEMENT-- myDB.java
package cu_coders.app1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by user pc on 03-10-2016.
*/
public class myDB extends SQLiteOpenHelper {
private static int DATABASE_VERSION=1;
private static String DATABASE_NAME="file.db";
private static String TABLE_FILE1="class_cse";
public static String COLUMN_KEY="_key";
public static String COLUMN_NAME="_name";
public myDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+ TABLE_FILE1 + "(" +
COLUMN_KEY + " INTEGER PRIMARY KEY "+
COLUMN_NAME+" TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILE1+";");
onCreate(db);
}
public void addItem(file1 f){
ContentValues cv=new ContentValues();
cv.put(COLUMN_NAME,f.get_name());
SQLiteDatabase db=getWritableDatabase();
db.insert(TABLE_FILE1,null,cv);
db.close();
}
/*public void deletItem(String item){
SQLiteDatabase db=getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE_FILE1+" WHERE "+COLUMN_NAME+" =\" "+ item +"\";");
db.close();
} */
public String printTable(){
String dbstring="";
SQLiteDatabase db=getWritableDatabase();
String query="SELECT * FROM "+TABLE_FILE1+" WHERE 1;";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while(!c.moveToLast()){
if(c.getString(c.getColumnIndex(COLUMN_NAME))!=null) {
dbstring += c.getString(c.getColumnIndex(COLUMN_NAME));
dbstring += '\n';
}
}
db.close();
return dbstring;
}
}
please help me out to find out what is wrong. thank you in advance.
you should change several items i guess...
change myDB Constructor to this :
public myDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and in mainActivity class change all global variable like this :
private EditText e ;
private file1 f ;
private TextView t;
and in oncreate() initial them :
e=(EditText)findViewById((R.id.text1));
f=new file1();
t=(TextView)findViewById(R.id.textView1);

Unfortunately this app has stopped working (SQLiteDatabase) [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have this problem: I wrote an app, but the SQLiteDatabase isn't working.
My database class code:
package com.example.frauprinzssapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class database extends SQLiteOpenHelper{
public static final String DB_NAME = "users.db";
public static final String DB_TABLENAME = "users_table";
public static final String COL_1 = "id";
public static final String COL_2 = "name";
public static final String COl_3 = "class";
public static final String COL_4 = "right";
public database(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+DB_TABLENAME+"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, class TEXT, right INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+DB_TABLENAME);
onCreate(db);
}
public boolean insertdata(String name, String clas){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2, name);
cv.put(COl_3, clas);
cv.put(COL_4, 0);
long result = db.insert(DB_TABLENAME, null, cv);
if (result == -1){
return false;
}else{
return true;
}
}
}
The main code is:
package com.example.frauprinzssapp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
List<String> addusers = new ArrayList<String>();
database myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDb = new database(this);
}
//-----change view voids-----
public void main(View view){
setContentView(R.layout.main);
}
public void adduser(View view){
setContentView(R.layout.adduser);
}
public void removeuser(View view){
setContentView(R.layout.removeuser);
}
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
if (name.toString() == null || clas.toString() == null){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name.toString(), clas.toString());
Toast.makeText(Main.this, "added user "+name.toString()+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}
public void remove(){
}
public void show(){
}
}
I used the
android:onClick="add"
to make so that the add() void runs
please now it just puts random stuff into the sqlite pleaseeeee help
try it....
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
String name1 = name.getText().toString();
String clas1 = clas.getText().toString();
if (name1.equals("") || clas1.equals("")){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name1, clas1);
Toast.makeText(Main.this, "added user "+name1+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}

Getting Force close when I try to open my golf scoreboard application

I am quite new androids and seem to have came across a Force close on my app and have no idea how to solve it.
Basically a part of my golf app is a scoreboard that the hole the person is on and the amount of strokes taken.
My code works were you have 2 buttons, add and subtract and change the number that shows up in the EditText. A button is then clicked and submits the number into a listview.I'm now trying to get it so that there is 2 add, subtract buttons and edittext and when both numbers have been entered and button to submit is clicked, will show something like 'Your stroke was 2' 'On hole 1'
Here is the code for it
package com.uhi.myGolfApp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class scoreboard extends Activity implements OnClickListener {
Button buttonPlus1;
Button buttonMinus1;
EditText editScore1;
Button buttonPlus;
Button buttonMinus;
Button buttonOk;
EditText editScore;
ListView scoreCard;
Cursor cursor;
SimpleCursorAdapter adapter;
Integer score=0;
Integer score1=0;
SharedPreferences prefs;
databaseHelper dbHelper;
SQLiteDatabase db;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate UI from XML
setContentView(R.layout.scoreboard);
// Get a hang of UI components
buttonPlus1 = (Button)findViewById(R.id.buttonadd);
buttonMinus1 = (Button)findViewById(R.id.buttonsub);
editScore1 = (EditText)findViewById(R.id.score1);
buttonPlus = (Button)findViewById(R.id.add);
buttonMinus= (Button)findViewById(R.id.subtract);
buttonOk = (Button)findViewById(R.id.enter);
editScore = (EditText)findViewById(R.id.score);
scoreCard = (ListView)findViewById(R.id.scorePosted);
// Add onClick listeners
buttonPlus1.setOnClickListener(this);
buttonMinus1.setOnClickListener(this);
buttonPlus.setOnClickListener(this);
buttonMinus.setOnClickListener(this);
buttonOk.setOnClickListener(this);
// Get preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
// Initialize the database
dbHelper = new databaseHelper(this);
db = dbHelper.getWritableDatabase();
// Load the data (essentially executes a SELECT statement)
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
// Set the list adapter
String[] from = {databaseHelper.colStrokes, databaseHelper.colHole};
int[] to = {R.id.textStroke, R.id.textHole};
adapter = new SimpleCursorAdapter(this, R.layout.golfscores, cursor, from, to);
scoreCard.setAdapter(adapter);
}
#Override
public void onRestoreInstanceState(Bundle inState) {
score = (inState!=null) ? inState.getInt("score",0) : 0;
score1 = (inState!=null) ? inState.getInt("score1",0) : 0;
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("score", score);
outState.putInt("score1", score1);
super.onSaveInstanceState(outState);
}
#Override
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonadd:
score1++;
break;
case R.id.buttonsub:
score1--;
break;
case R.id.add:
score++;
break;
case R.id.subtract:
score--;
break;
case R.id.enter:
// Save in DB
ContentValues values = new ContentValues();
values.put(databaseHelper.colHole, score1);
values.put(databaseHelper.colStrokes, score);
db.insert(databaseHelper.tableName, null, values);
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
adapter.changeCursor(cursor);
score=0;
adapter.changeCursor(cursor);
score1=0;
break;
}
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
}
and the database
package com.uhi.myGolfApp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class databaseHelper extends SQLiteOpenHelper {
// DB constants
private static final String DB_NAME = "scoreboard.db";
private static final int DB_VERSION = 1; // Schema version
// Schema constants
public static final String tableName = "scoreboard";
public static final String colHole = "hole";
public static final String colStrokes = "strokes";
// Constructor
public databaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//create the SQL table and the attributes it will hold
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table "+tableName +
" (_id integer not null primary key autoincrement, "+
colHole + " integer, "+ colStrokes+" integer)";
db.execSQL(sql);
}
// upgrade the database off the old version
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Also I dont know if this is any help but this appears in the LogCat = 'Caused by: java.lang.IllegalArgumentException: column 'hole' does not exist'
Appreciate any help =]
I would guess that you ran your code once, before you added the "hole" column, and that is the database that is being read. You need to delete your app's data (Settings -> Applications -> Your app) so that the newest version of the database is created. If you don't have the option to delete data then uninstall it.

How to use edittext.getText().toString()

I want to make it so that there is a ListView with a Button above it. The users clicks that button, and it opens a dialog with an EditText and an OK and Cancel button. When the user clicks OK, whatever text is entered into the EditText gets put into the SQLiteDatabase, which is reflected in the ListView.
I've already set up my SQLiteDatabase and have set an adapter for the List to show the SQLiteDatabase, but I need to figure out how to use the edittext.getText().toString() method to add to the SQLiteDatabase. I will need a code example.
If you need it, here's my main .java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
SimpleCursorAdapter adapter = null;
final SQLiteDatabase db = dataHelper.selectAll();
Cursor c = db.rawQuery("SELECT DISTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.moveToFirst()) {
String[] columnNames = new String[]{"name"};
int[] list = new int[]{android.R.id.list};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, list);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et.getText().toString();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
Here is my DataHelper class:
package com.gantt.shoppinglist;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public SQLiteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Using the current methods you have, and assuming that you understand the code that you used for the database adapter, just do this:
String item = et.getText().toString();// these two lines are the
dataHelper.insert(item); // only change you have to do
additem.dismiss();
et.setText("");
After doing this, you have to call the notifyDataSetChanged method of your SimpleCursorAdapter object.
A simple sample method for your DataHelper class:
public long createUser(String email, String password, String fullName) {
ContentValues initialValues = new ContentValues();
initialValues.put("email", email);
initialValues.put("password", password);
initialValues.put("fullName", fullName);
return mDb.insert(TABLE_NAME, null, initialValues);
}

Categories

Resources