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);
}
Related
I'm working on a code snippet for performing CRUD operations in Sqlite DB in Android Studio. I created a listView to hold two attributes, i.e., name and job but the application is getting crashed at runtime. It says:
Sqlite Exception: no such column( code 1) "name" Found.
I've searched for the solution but every solution I've checked is a failed one. My DB browser shows the table contains the column. Do I need to add SELECT FROM ...query to my code? If it is, then where should I put the code?
my code as below:
DatabaseHelper.class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "USERS";
public static final String _ID = "_id";
public static final String DESC = "occupation";
public static final String SUBJECT = "name";
SQLiteDatabase myDb;
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
"(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SUBJECT + "TEXT NOT NULL,"
+ DESC + "TEXT"+ ")" ;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long insert(String name, String desc) {
myDb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
long id = myDb.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
myDb.close();
return id;
}
public Cursor read(){
SQLiteDatabase myDb = this.getWritableDatabase();
String[] columns = new String[] {DatabaseHelper._ID,DatabaseHelper.SUBJECT,DatabaseHelper.DESC};
Cursor cursor = myDb.query(DatabaseHelper.TABLE_NAME,columns,null,null,null,null,null);
if(cursor!=null){
cursor.moveToFirst();
}
myDb.close();
return cursor;
}
}
MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button addUser;
ArrayList<String> list;
ArrayAdapter<String> adapter;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addUser = findViewById(R.id.add_button);
list = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.populate_list, R.id.name, list);
dbManager = new DatabaseHelper(this);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addAccount();
}
});
}
public void addAccount() {
Intent intent = new Intent(MainActivity.this, AddUser.class);
startActivityForResult(intent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
final String name = intent.getStringExtra("name");
final String occupation = intent.getStringExtra("occupation");
ListView listView = findViewById(R.id.parentLayout);
dbManager.read();
list.add(name);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, UpdateActivity.class);
i.putExtra(name, "username");
i.putExtra(occupation, "occupation");
startActivity(i);
}
});
}
}
}
AddUser.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddUser extends AppCompatActivity {
EditText userName, job;
Button submitButton, cancelButton;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
dbManager = new DatabaseHelper(this);
userName = findViewById(R.id.userText);
job = findViewById(R.id.occupation);
submitButton = findViewById(R.id.submit_button);
cancelButton = findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddUser.this, MainActivity.class);
startActivity(intent);
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String name = userName.getText().toString();
String desc = job.getText().toString();
intent.putExtra(name, "name");
intent.putExtra(desc, "occupation");
dbManager.insert(name, desc);
setResult(1, intent);
finish();
}
});
}
}
You can try using a rawquery like this :
String sql = " SELECT * FROM " + TABLE_NAME + " WHERE " + ONE_COLUMN_NAME + "=?" + " AND " + PERHAPS_ANOTHER_COLUMN + " =?";
ArrayList<YourKindOfObject> array = new ArrayList<>();
Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{firstParameter, secondParameter});
while (cursor.moveToNext()) {
YourKindOfObject yourKindOfObject = new YourKindOfObject();
yourKindOfObject.setOneThing(cursor.getString(cursor.getColumnIndex(ColumnName));
yourKindOfObject.setOneOtherThing(cursor.getString(cursor.getColumnIndex(ColumnName1)));
array.add(yourKindOfObject);
}
cursor.close();
return array;
I am creating an android application that consists of a list view populated by the data from the database.
Here I need to delete the data from the database as well as the list view and refresh the list view.
I used both notifyOnDataSetChanged() and notifyOnDataSetInvalidated() but
it wont work for me please help me with this
package com.developer.milanandroid;
import android.app.ActionBar;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.gc.materialdesign.widgets.Dialog;
import com.milan.emptylayout.EmptyLayout;
import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.swipemenulistview.SwipeMenu;
import com.milan.swipemenulistview.SwipeMenuCreator;
import com.milan.swipemenulistview.SwipeMenuItem;
import com.milan.swipemenulistview.SwipeMenuListView;
import com.milan.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.processbutton.lib.milan.ActionProcessButton;
public class DatabaseListView extends Activity implements OnCompleteListener {
MediaPlayer media_player;
ActionProcessButton fetch_database;
SwipeMenuListView database_results;
LoginDataBaseAdapter logindatabase_adapter;
SimpleCursorAdapter cursoradapter;
Cursor cursor;
TextView username_txt,password_txt;
String user_name_string,password_string;
String text;
Dialog dialog;
private EmptyLayout empty_layout;
View.OnClickListener emptyClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databaselistview);
View.OnClickListener mErrorClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
fetch_database.setText("Checking...");
empty_layout.showLoading();
ProgressGenerator pg = new ProgressGenerator(DatabaseListView.this);
pg.start(fetch_database);
}
};
emptyClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DatabaseListView.this, "Try again button clicked", Toast.LENGTH_LONG).show();
}
};
ActionBar actionbar = getActionBar();
actionbar.hide();
View v;
LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
username_txt = (TextView)linear.getChildAt(0);
password_txt = (TextView)linear.getChildAt(0);
user_name_string = username_txt.getText().toString();
password_string = password_txt.getText().toString();
fetch_database = (ActionProcessButton)findViewById(R.id.Button_Fetch_from_Database);
database_results = (SwipeMenuListView)findViewById(R.id.listview_database);
final ProgressGenerator progressGenerator = new ProgressGenerator(DatabaseListView.this);
logindatabase_adapter = new LoginDataBaseAdapter(DatabaseListView.this);
empty_layout = new EmptyLayout(DatabaseListView.this, database_results);
empty_layout.setErrorButtonClickListener(mErrorClickListener);
fetch_database.setMode(ActionProcessButton.Mode.PROGRESS);
fetch_database.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
progressGenerator.start(fetch_database);
fetch_database.setText("Checking...");
fetch_database.setEnabled(false);
empty_layout.showLoading();
media_player = MediaPlayer.create(DatabaseListView.this, R.raw.retrievingfromdatabase);
media_player.start();
String[] from = {LoginDataBaseAdapter.USER_NAME,LoginDataBaseAdapter.USER_PASSWORD};
int[] to = {R.id.txt_username,R.id.txt_pasword};
cursor = logindatabase_adapter.feching_Data();
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
cursoradapter.notifyDataSetChanged();
//registerForContextMenu(database_results);
}
});
SwipeMenuCreator swipe_list_view = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
SwipeMenuItem open_swipemenu = new SwipeMenuItem(DatabaseListView.this);
open_swipemenu.setBackground(new ColorDrawable(Color.rgb(0x9B,0x33,0xF0)));
open_swipemenu.setWidth(dp2px(90));
open_swipemenu.setIcon(R.drawable.databasedelete);
menu.addMenuItem(open_swipemenu);
}
};
database_results.setMenuCreator(swipe_list_view);
database_results.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
switch(index) {
case 0:
dialog = new Dialog(DatabaseListView.this, "Delete Record", "Do you want to delete Record from database");
dialog.setCancelable(false);
dialog.setOnAcceptButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cursor = (Cursor) database_results.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(LoginDataBaseAdapter.ID));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_NAME));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_PASSWORD));
logindatabase_adapter.deleteEntry(item_id);
//database_results.removeViewAt(position);
//cursoradapter.notifyDataSetChanged();
database_results.invalidateViews();
}
});
dialog.show();
}
return false;
}
});
}
protected int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getResources().getDisplayMetrics());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.database_list_view, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onComplete() {
if(cursor!=null && cursor.getCount()>0){
database_results.setAdapter(cursoradapter);
fetch_database.setEnabled(false);
fetch_database.setText("SUCCESS");
}
else{
/*fetch_database.setEnabled(false);
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
final Dialog dialog_database = new Dialog(DatabaseListView.this, "Database Records", "No Records was found in the database");
dialog_database.setOnAcceptButtonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog_database.cancel();
}
});
dialog_database.show();*/
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
empty_layout.showError();
}
}
}
This is my LoginDatabase adpater:
package com.developer.milanandroid;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
public class LoginDataBaseAdapter
{
//Database name
static final String DATABASE_NAME = "MilanloginRegistration.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
public static final String TABLE_NAME="MilanLoginregistration";
public static final String ID="_id";
public static final String USER_NAME="USERNAME";
public static final String USER_PASSWORD ="PASSWORD";
static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
"( " +ID+" integer primary key autoincrement,"+"USERNAME text not null,"+USER_PASSWORD+" text not null); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public LoginDataBaseAdapter opentoRead() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getReadableDatabase();
return this;
}
public LoginDataBaseAdapter opentoWrite() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getWritableDatabase();
return this;
}
public void Close(){
dbHelper.close();
}
public void insertEntry(String username,String password)
{
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",username);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("MilanLoginregistration",null,newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteAll(){
return db.delete(TABLE_NAME, null, null);
}
public void deleteEntry(int id){
//String id=String.valueOf(ID);
db.delete(TABLE_NAME, ID+"="+id, null);
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
}
public Cursor queue_all(){
String[] columns = new String[]{ID,"USERNAME","PASSWORD"};
Cursor cursor_queue_all =db.query(TABLE_NAME, columns, null, null, null, null, null);
return cursor_queue_all;
}
public Cursor feching_Data(){
String[] columns = {ID,USER_NAME,USER_PASSWORD};
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, columns,null,null,null,null,null);
return cursor;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
//cursor.close();
return password;
}
public String checkSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()>=1) // UserName Exist
{
cursor.close();
return "NOT EXIST";
}
// cursor.close();
return "";
}
public void updateEntry(String user_name,String pasword)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", user_name);
updatedValues.put("PASSWORD",pasword);
String where="USERNAME = ?";
db.update("MilanLoginregistration",updatedValues, where, new String[]{user_name});
}
/*public void Display(View v){
Cursor c = db.rawQuery("select * from MilanloginRegistration", null);
admin_settings_child.text_fetched_database_results.setText("");
c.moveToFirst();
do{
String username = c.getString(c.getColumnIndex("USERNAME"));
String password = c.getString(1);
admin_settings_child.text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");
}while(c.moveToNext());
}*/
}
Kindly post the code of your adapter as well. in the above code you are deleting the data from other adapter and notifying other adapter for data set changed. i.e in following lines I can't see where cursoradapter is actually being updated.
logindatabase_adapter.deleteEntry(item_id);
cursoradapter.notifyDataSetChanged();
cursoradapter.notifyDataSetInvalidated();
also you can try this.
listview.getAdapter().notifyDataSetChanged();
For proper implementing datasetchanged functionality you need to create custom adapter other wise you just setlist adapter every time your data is being changed.i.e
listeview.setAdapter(modifiedAdapter);
listview.getAdapter.notifyDataSetChanged();
Edit 1:
as you are using simple cursor adapter you need to add following lines after deleting the entry:
logindatabase_adapter.deleteEntry(item_id);
cursor = logindatabase_adapter.feching_Data();
//database_results.removeViewAt(position);
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
database_results.setAdapter(cursoradapter);
database_results.getAdapter().notifyDataSetChanged();
Use the notifyDataSetChanged() method on the adapter like this:
final ArrayAdapter adapter = ((ArrayAdapter) getListAdapter());
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
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.
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 " + );";
I have the following two files:
podatkovna_baza.java
package com.example.ultimate.basketball.stats;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class podatkovna_baza extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "baza5";
public podatkovna_baza(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase baza5) {
/*
* Create the employee table and populate it with sample data.
* In step 6, we will move these hardcoded statements to an XML document.
*/
String sql = "CREATE TABLE IF NOT EXISTS ekipe4 (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ime_ekipe TEXT, " +
"kratko_ime TEXT, " +
"kraj TEXT, " +
"slika TEXT )";
baza5.execSQL(sql);
ContentValues values = new ContentValues();
values.put("ime_ekipe", "Drustvo partizan");
values.put("kratko_ime", "DRP");
values.put("kraj", "Mirna");
values.put("slika", "jajaja");
baza5.insert("ekipe4", null, values);
}
#Override
public void onUpgrade(SQLiteDatabase baza5, int oldVersion, int newVersion) {
baza5.execSQL("DROP TABLE IF EXISTS ekipe4");
onCreate(baza5);
}
}
osnovni_meni.java
package com.example.ultimate.basketball.stats;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class osnovni_meni extends Activity {
protected SQLiteDatabase baza5;
protected Cursor cursor;
protected ListAdapter adapter;
protected ListView ekipe_list;
protected EditText searchtext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osnovni_meni);
baza5 = (new podatkovna_baza(this)).getWritableDatabase();
//searchtext = (EditText) findViewById (R.id.searchText);
//searchText = (EditText) findViewById (R.id.searchText);
//employeeList = (ListView) findViewById (R.id.list);
}
public void hello(View view) {
//cursor = baza2.rawQuery("SELECT ime_ekipe, kratko_ime, kraj FROM ekipe2" , null);
ekipe_list = (ListView) findViewById (R.id.lista);
cursor = baza5.query("ekipe4", null, null, null, null, null,
"_id" + " ASC");
adapter = new SimpleCursorAdapter(
this,
R.layout.ekipe_layout,
cursor,
new String[] {"_id","kratko_ime","kraj"},
new int[] {R.id.ime_ekipe,R.id.kratko_ime,R.id.kraj});
ekipe_list.setAdapter(adapter);
String sadas=adapter.toStr
}
public void delete_byID(int id) {
baza5.delete("ekipe4", "_id"+"="+id, null);
}
public void delete_by_ime_ekipe(String ime) {
baza5.delete("ekipe4", "kraj"+"="+ime, null);
}
public int deleteAll() {
return baza5.delete("ekipe4", null, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_osnovni_meni, menu);
return true;
}
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
finish();
}
public void vibriraj()
{
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(30);
}
public void vpisi(View view)
{
ContentValues values1 = new ContentValues();
//values1.put("_id", "1");
values1.put("ime_ekipe", "Chicago Bulls");
values1.put("kratko_ime", "CHI");
values1.put("kraj", "Chicago");
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
}
public void vpisi_ekipo(View view)
{
vibriraj();
EditText novo_ime_ekipe = (EditText) findViewById (R.id.novo_ime_ekipe);
EditText novo_kratko_ime_ekipe = (EditText) findViewById (R.id.novo_kratko_ime_ekipe);
EditText novo_kraj_ekipe = (EditText) findViewById (R.id.novo_kraj_ekipe);
EditText novo_slika_ekipe = (EditText) findViewById (R.id.novo_slika_ekipe);
ContentValues values1 = new ContentValues();
values1.put("ime_ekipe", (novo_ime_ekipe.getText()).toString());
values1.put("kratko_ime", (novo_kratko_ime_ekipe.getText()).toString());
values1.put("kraj", (novo_kraj_ekipe.getText()).toString());
values1.put("slika", (novo_slika_ekipe.getText()).toString());
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
setContentView(R.layout.edit_teams);
}
}
Now I want to for example delete a row I select (get ID from list and corresponding ID from database) or edit a row. How do I do this? It's pretty easy to delete or edit a SQLite entry if you know the id from a database, but I do not.
Sorry for my English, as you can see, it's not my first language.
ekipe_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// your code here
}
});
Here in "position" you get the id of the item you've clicked.
So you need only to convert the id in ListView to the id in database.
Otherwise you will need to create custom adapter instead of SimpleCursorAdapter, and override the getView() method.
in the select query you have mentioned "SELECT * FROM ANSWER WHERE ID="
But you have to mention as " "SELECT * FROM answer WHERE ID"
Because table name is answer not ANSWER