Updating ListView with texts from EditText through SQLite Database - android

I want to make a Comment bar(an EditText) ,where one's comment will be added to SQLite DB and the comment will be shown in a ListView . I tried doing that but i ended up with a crashing application . On loading to Emulater it says. "Unfortunately ,SQLproj has stopped" . I am shraing what i did . Please help me with it. I am stuck with it since hours
My activity_main.xml (Layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="#+id/edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Please Share Your Valuable Reviews"
/>
<Button
android:id="#+id/button"
android:text="Submit"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
My Pojo class
package com.example.sqlproj;
public class Comment {
public long id;
public String comment;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#Override
public String toString()
{
return comment;
}
}
My SQLiteHelper class:
package com.example.sqlproj;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String Table_Name="Reviews";
public static final String DB_Name="Reviews";
public static final int DB_Version=1;
public static final String Column_Id="_id";
public static final String Column_Name="Comments";
public static final String DB_Create="create table" +Table_Name+ "(" +Column_Id+ "integer primary key autoincrement," +Column_Name+"text not null);";
public MySQLiteHelper(Context context) {
super(context, DB_Name, null, DB_Version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB_Create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Application class:
package com.example.sqlproj;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CommentsDataSource {
public SQLiteDatabase database;
public MySQLiteHelper dbhelper;
public String[] allcolumns= {dbhelper.Column_Id,dbhelper.Column_Name};
public CommentsDataSource(Context context)
{
dbhelper= new MySQLiteHelper(context);
}
public void open()
{
database = dbhelper.getWritableDatabase();
}
public void close()
{
dbhelper.close();
}
public Comment createComment(String comment)
{
ContentValues cv = new ContentValues();
cv.put(dbhelper.Column_Name, comment);
long id= database.insert(dbhelper.Table_Name, null, cv);
Cursor cursor = database.query(dbhelper.Table_Name, allcolumns, null, null, null, null, null);
cursor.moveToFirst();
Comment newcomment = commentSetter(cursor);
return newcomment;
}
public Comment commentSetter(Cursor cursor)
{
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
public List<Comment> getallComments()
{
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(dbhelper.Table_Name, allcolumns, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
Comment comment = commentSetter(cursor);
comments.add(comment);
cursor.moveToNext();
}
cursor.close();
return comments;
}
}
MAIN ACTIVITY CLASS
package com.example.sqlproj;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class MainActivity extends ListActivity {
public CommentsDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> comments= datasource.getallComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, comments);
setListAdapter(adapter);
}
public void onClick(View view)
{
Comment comment=null;
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
EditText edittext = (EditText) findViewById(R.id.edittext);
String com=edittext.getText().toString();
datasource.createComment(com);
adapter.add(comment);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}

add this onCreate(db) in below method. because without calling onCreate(db) your database is not created. because when you use SQLiteOpenHelper then onUpgrade method is called first.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
onCreate(db); // add this line
}

in MySQLiteHelper
fix this :
public static final String DB_Create="create table" +Table_Name+ "(" +Column_Id+ "integer primary key autoincrement," +Column_Name+"text not null);";
to this :
public static final String DB_Create = "create table " + Table_Name + "(" + Column_Id + " integer primary key autoincrement, " + Column_Name + " text not null " + );";

Related

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);

error while retriving data from the database SQLite in android

my database helper class is
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;
public class DataHandlerDairy {
public static final String DATE = "date";
public static final String DAIRY = "dairy";
private static final String DATA_BASE_NAME = "mydairy";
private static final String TABLE_NAME = "table_dairy";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE="create table table_dairy (date text primary key," + "dairy text not null);";
DataBaseHelper1 dbhelper1;
Context ct;
SQLiteDatabase db;
public DataHandlerDairy(Context ct)
{
this.ct=ct;
dbhelper1 = new DataBaseHelper1(ct);
}
private static class DataBaseHelper1 extends SQLiteOpenHelper
{
public DataBaseHelper1(Context ct)
{
super(ct,DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try
{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS table_dairy ");
onCreate(db);
}
}
public DataHandlerDairy open()
{
db = dbhelper1.getWritableDatabase();
return this;
}
public void close()
{
dbhelper1.close();
}
public long insertData(String date,String dairy)
{
ContentValues content = new ContentValues();
content.put(DATE, date);
content.put(DAIRY, dairy);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(String date1) throws SQLException
{
Cursor c = db.query(true, TABLE_NAME, new String[] { DATE, DAIRY}, DATE + "=" + date1, null, null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
return c;
}
}
when i try to retrive the data from the database I am getting an error.
I have used the database helper class in the following code.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class Read_Dairy extends Activity {
String date1;
TextView tv1,tv2;
ImageButton imgb1;
Button bt1;
DataHandlerDairy handler3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read__dairy);
tv1=(TextView) findViewById(R.id.readme);
imgb1=(ImageButton) findViewById(R.id.tick);
bt1=(Button) findViewById(R.id.ready);
tv2=(TextView) findViewById(R.id.love);
Bundle bundle = getIntent().getExtras();
date1 = bundle.getString("kanna");
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getdata=" ";
tv2.setText(date1);
String abcd=tv2.getText().toString();
handler3 = new DataHandlerDairy(getBaseContext());
handler3.open();
Cursor c = handler3.returnData(abcd);
if(c.moveToFirst())
{
do
{
getdata=c.getString(1);
}while(c.moveToNext());
}
handler3.close();
if(getdata==null)
{
tv1.setText("no data exists for this date");
}
else
{
tv1.setText(getdata);
}
}
});
imgb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ks = new Intent(Read_Dairy.this,PickYourDate.class);
startActivity(ks);
}
});
Typeface font = Typeface.createFromAsset(getAssets(), "Strato-linked.ttf");
tv1.setTypeface(font);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_read__dairy, menu);
return true;
}
}
I am getting an error while using this and my StackTrace is
FATAL EXCEPTION: main
Process: simple.smile.my_dairy, PID: 4423
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at simple.smile.my_dairy.Read_Dairy$1.onClick(Read_Dairy.java:71)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5315)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:736)
Please tell me where the error is and how to rectify it.
getdata=c.getString(1) is not a good way. Instead use getdata=c.getString(c.getColumnIndex(DataHandlerDairy.DAIRY))

SQLiteAssetHelper and getWritableDatabase

I'm having have some trouble with my Database activity. I am unable to write to the database and view the database using the following code.
my Database activity:
package com.jacob.eindproject;
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.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_PRODUCT);
int iName = c.getColumnIndex(KEY_EENHEID);
int iHotness = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
My SQLView activity:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
SQLite activity:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
I am having my database file(Voedsel.rar), in assets/databases/Voedsel.rar.
To write to your database, try a method like this:
public void insertVoeding(String product, String eenheid, String kcal) {
ourDatabase.execSQL("INSERT INTO Voeding (Product, Eenheid, Kcal) VALUES (?, ?, ?)",
new String[] {product, eenheid, kcal});
}
The question marks are replaced by the values in the string array. Your column names cannot be inserted using the string array, because the execSQL method puts quotation marks around these values. The query will fail if you try.
There are two ways to read from a database (may even be two ways to write to it, too). I personally prefer using raw queries, like this one to get the entire database:
public Cursor getEntireDB() {
return ourDatabase.rawQuery("SELECT * FROM Voeding");
}
You can then use the cursor in a CursorAdapter to create a list.

Trying to develop a list view in Android with data in database

Hi i am trying to populate a list view with data in the database but i am not able to make it out.Here is the code i tried out
VehicleDisplay Class
package com.android.allianz;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class VehicleDisplay extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vehicledisplay);
SQLiteDatabase db = (new DBAdapter.DatabaseHelper(this)).getWritableDatabase();
ListView vehList = (ListView)findViewById(R.id.vehcleList);
Cursor c = db.rawQuery("SELECT P_VEHMD FROM vehicle WHERE P_EMPID = ?",
new String[]{"i82112"});
ListAdapter adap = new SimpleCursorAdapter(
this,
R.layout.vehiclerow,
c,
new String[] {"P_VEHMD"},
new int[] {R.id.vehMdl});
/* vehList.setAdapter(adap);*/
Button bankaccount = (Button) findViewById(R.id.add_vehicle);
bankaccount.setOnClickListener(new View.OnClickListener(){
public void onClick(View z){
Intent bank = new Intent(VehicleDisplay.this,VehicleActivity.class);
startActivity(bank);
}
});
}
}
My Database Class is
DBAdapter Class
package com.android.allianz;
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 DBAdapter
{
public static final String V_EMPID = "P_EMPID";
public static final String V_VEHID = "P_VEHID";
public static final String V_VEHTP = "P_VEHTP";
public static final String V_VEHMD = "P_VEHMD";
public static final String V_REGYR = "P_REGYR";
public static final String V_REGNO = "P_REGNO";
public static final String V_INSNM = "P_INSNM";
public static final String V_INSNO = "P_INSNO";
public static final String V_INSVY = "P_INSVY";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "usersdb";
private static final String DATABASE_TABLE4 = "vehicle";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE4 =
"create table vehicle (P_VEHID integer primary key, "
+ "P_EMPID text, "
+ "P_VEHTP text, "
+ "P_VEHMD text, "
+ "P_REGYR text, "
+ "P_REGNO text, "
+ "P_INSNM text, "
+ "P_INSNO text, "
+ "P_INSVY text );";
private Context context = null;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE4);
}
#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 vehicle");
onCreate(db);
}
}
public void open() throws SQLException
{
db = DBHelper.getWritableDatabase();
}
public void close()
{
DBHelper.close();
}
public Boolean AddVehicle(String P_EMPID,String P_VEHTP, String P_VEHMD,
String P_REGYR, String P_REGNO, String P_INSNM,String P_INSNO, String P_INSVY)
{
Boolean bool = false;
ContentValues initialValues = new ContentValues();
initialValues.put(V_EMPID, P_EMPID);
initialValues.put(V_VEHTP, P_VEHTP);
initialValues.put(V_VEHMD, P_VEHMD);
initialValues.put(V_REGYR, P_REGYR);
initialValues.put(V_REGNO, P_REGNO);
initialValues.put(V_INSNM, P_INSNM);
initialValues.put(V_INSNO, P_INSNO);
initialValues.put(V_INSVY, P_INSVY);
if( db.insert(DATABASE_TABLE4, null, initialValues)> 0)
{
bool = true;
}
else {bool = false;}
return bool;
}
public boolean Vehicle(String vehtype,String vehModel,String purYear,String regisNo,String insurName,String insurNo,String insurVdty) throws SQLException
{
Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE4 + " WHERE P_VEHTP=? AND P_VEHMD=? AND P_REGYR=? AND P_REGNO=? AND P_INSNM=? AND P_INSNO=? AND P_INSVY=?", new String[]{vehtype,vehModel,purYear,regisNo,insurName,insurNo,insurVdty});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
}
The XML used are vehicledisplay.xml and vehiclerow.xml
vehicledisplay xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vehicledisp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:id="#+id/vehcleList" android:layout_height="377dp">
</ListView>
<Button android:id="#+id/add_vehicle" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="#string/addvehicle"></Button>
</LinearLayout>
</ScrollView>
vehiclerow xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/vehMdl" android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
</RelativeLayout>
Please kindly help me on this
The problem that stands out to me here is that your table does not have its primary key column named _id. CursorAdapter uses this column internally to maintain consistency.
You should change the name of P_VEHID to _id (I recommend also adding NOT NULL to its specification) or add an _id column and add an index on P_VEHID. Then change your select statement to read:
SELECT _id, P_VEHMD FROM vehicle WHERE P_EMPID = ?

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