I have a problem receiving data from my database. As determined in my codes, my database (TBL_MAHRIE) contains three columns (ID , COL_SAL , COL_NERKH). Running my project, I received repeated data in both of spinner and ListView.
Mahrie.java (MY SPINNER LOAD HERE)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Mahrie extends Activity {
private Spinner spinner_sal1, spinner_sal2;
private Button btn_calc;
EditText ed_shakhes_Nekah, ed_shakhes_Motalebe;
TextView tv_res;
float shakhes_Nekah, shakes_Motalebe, final_Res;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie);
ed_shakhes_Motalebe = (EditText) findViewById(R.id.ed_shakhes_Motalebe);
ed_shakhes_Nekah = (EditText) findViewById(R.id.ed_shakes_Nekah);
tv_res = (TextView) findViewById(R.id.tv_res);
// DATABASE
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("1392", "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("1391", "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("1390", "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("1389", "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("1388", "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("1387", "25");
databaseAdapter.insertShakhes(shakhes6);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
List<String> list = new ArrayList<String>();
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
List<Shakhes> data_shakhes = null;
data_shakhes = databaseAdapter.getAllShakhes();
Context context = getApplicationContext();
for (int i = 0; i < data_shakhes.size(); i++) {
list.add((data_shakhes.get(i).getSal()));
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_sal2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner_sal1 = (Spinner) findViewById(R.id.spinner_Sal1);
spinner_sal1
.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner_sal1 = (Spinner) this.findViewById(R.id.spinner_Sal1);
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
btn_calc = (Button) findViewById(R.id.btn_calc);
btn_calc.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shakhes_Nekah = Float.parseFloat(ed_shakhes_Nekah.getText()
.toString());
shakes_Motalebe = Float.parseFloat(ed_shakhes_Motalebe
.getText().toString());
final_Res = shakes_Motalebe / shakhes_Nekah;
tv_res.setText(final_Res + "");
}
});
}
}
2.DataBase Handler.java
package ir.dadpardaz.mahrie_dadpardaz;
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;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ToggleButton;
public class DataBaseHandler {
SQLiteDatabase database;
public DataBaseHandler(Context context) {
ShakhesDatabaseOpenHelper shakhesDatabaseOpenHelper = new ShakhesDatabaseOpenHelper(
context, "shakhsdb.db", null, 1);
database = shakhesDatabaseOpenHelper.getWritableDatabase();
}
public class ShakhesDatabaseOpenHelper extends SQLiteOpenHelper {
public ShakhesDatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
String query = "create table IF NOT EXISTS TBL_MAHRIE (ID INTEGER PRIMARY KEY, COL_SAL TEXT, COL_NERKH TEXT)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
}
}
public long insertShakhes(Shakhes shakhes) {
ContentValues values = new ContentValues();
values.put("COL_SAL", shakhes.getSal());
values.put("COL_NERKH", shakhes.getNerkh());
return database.insert("TBL_MAHRIE", null, values);
}
boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen()) {
return false;
}
Cursor cursor = db
.rawQuery(
"SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
new String[] { "table", tableName });
if (!cursor.moveToFirst()) {
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
Shakhes p = new Shakhes();
if (c.moveToFirst()) {
do {
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
Mahrie_JadvalActivity (My ListView inflate here)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Mahrie_JadvalActivity extends Activity {
ListView personListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie__jadval);
personListView = (ListView) findViewById(R.id.personListView);
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("2392" , "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("2391" , "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("2390" , "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("2389" , "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("2388" , "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("2387" , "25");
databaseAdapter.insertShakhes(shakhes6);
List<Shakhes> shakhes =
databaseAdapter.getAllShakhes() ;
ShakhesListViewAdapter shakhesListViewAdapter = new ShakhesListViewAdapter(this, R.layout.mahrie_list_view_item, shakhes);
personListView.setAdapter(shakhesListViewAdapter);
}
public class ShakhesListViewAdapter extends ArrayAdapter<Shakhes> {
List<Shakhes> data;
Context context;
public ShakhesListViewAdapter(Context context, int resourceId, List<Shakhes> data) {
super(context, resourceId, data);
this.data = data;
this.context = context;
}
#Override
public View getView(final int position, View item, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
item = inflater.inflate(R.layout.mahrie_list_view_item, parent , false);
TextView familyTextView = (TextView) item.findViewById(R.id.familyTextView);
familyTextView.setText(data.get(position).getSal()) ;
//familyTextView.setTypeface(bYekan);
TextView nameTextView = (TextView) item.findViewById(R.id.nameTextView);
nameTextView.setText(data.get(position).getNerkh()) ;
//nameTextView.setTypeface(bYekan);
Button detailsButton = (Button) item.findViewById(R.id.detailsButton);
detailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,
// data.get(position).getSal() + " " + data.get(position).getNerkh(),
// Toast.LENGTH_LONG).show();
Toast.makeText(context,
data.size()+"" + " and ID is " + position + "" ,
Toast.LENGTH_LONG).show();
}
});
//item.startAnimation(animation);
return item;
}
} }
4.Shakhes.java
package ir.dadpardaz.mahrie_dadpardaz;
public class Shakhes {
public int id ;
public static String sal ;
public static String nerkh ;
public Shakhes(int id, String sal, String nerkh) {
super();
this.id = id;
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes(String sal, String nerkh) {
super();
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getNerkh() {
return nerkh;
}
public void setNerkh(String nerkh) {
this.nerkh = nerkh;
}
}
Inside your DataBaseHandler.java , Make the following change
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
if (c.moveToFirst()) {
do {
Shakhes p = new Shakhes();
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
code the line Shakhes p = new Shakhes(); inside do-while loop. Otherwise it will overwrite the old one, and the same will be added in arraylist.
Related
I am a newbie to Android programming.I want to use data inputted into an SQLite database to populate an Android Listview. However, Android keeps highlighting the SimpleCursorAdapter below as error. Can anyone help?
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
Below is the full code:
package com.allmycode.databaseinsertwithlistview;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText GetName,GetPhoneNumber,GetSubject ;
Button Submit ;
String Name, PhoneNumber, Subject ;
Boolean CheckEditTextEmpty ;
String SQLiteQuery;
SQLiteDatabase SQLITEDATABASE;
TextView display;
Cursor cursor;
ListView listView;
//Make these declarations to enable the fetchallitems() method work
public static final String name = "name";
public static final String phone_number = "Phone_number";
public static final String subject = "subject";
private SimpleCursorAdapter dataAdapter;
private static final String demoTable = "demoTable";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);GetName = (EditText)findViewById(R.id.editText1);
GetPhoneNumber = (EditText)findViewById(R.id.editText2);
GetSubject = (EditText)findViewById(R.id.editText3);
listView = (ListView) findViewById(R.id.ListVw);
//display= (TextView) findViewById(R.id.textView) ;
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBCreate();
SubmitData2SQLiteDB();
displayListView();
}
});
}
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("DemoDataBase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS demoTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name String, phone_number String, subject String);");
}
public void SubmitData2SQLiteDB(){
Name = GetName.getText().toString();
PhoneNumber = GetPhoneNumber.getText().toString();
Subject = GetSubject.getText().toString();
CheckEditTextIsEmptyOrNot( Name,PhoneNumber, Subject);
if(CheckEditTextEmpty == true)
{
SQLiteQuery = "INSERT INTO demoTable (name,phone_number,subject) VALUES('"+Name+"', '"+PhoneNumber+"', '"+Subject+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
// addtoTextView();
}
else {
Toast.makeText(MainActivity.this,"Please Fill All the Fields", Toast.LENGTH_LONG).show();
}
}
public void CheckEditTextIsEmptyOrNot(String Name,String PhoneNumber, String subject ){
if(TextUtils.isEmpty(Name) || TextUtils.isEmpty(PhoneNumber) || TextUtils.isEmpty(Subject)){
CheckEditTextEmpty = false ;
}
else {
CheckEditTextEmpty = true ;
}
}
public void ClearEditTextAfterDoneTask(){
GetName.getText().clear();
GetPhoneNumber.getText().clear();
GetSubject.getText().clear();
}
/* void addtoTextView(){
cursor= SQLITEDATABASE.rawQuery("SELECT * FROM demoTable;",null);
if (cursor !=null && cursor.moveToFirst()){
String name;
do{
name = cursor.getString(0);
String pnone_number=cursor.getString(1);
String test2=cursor.getString(2);
String test3 = cursor.getString(3);
display.append(name + " " + pnone_number +" "+test2 +" "+ test3 +"\n");
} while (cursor.moveToNext());
}
display.append("-------------\n");
} */
public Cursor fetchAllItems() {
Cursor mCursor = SQLITEDATABASE.query(this.demoTable, new String[] {this.name,
this.phone_number, this.subject},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private void displayListView()
{
Cursor cursor= fetchAllItems();
//The desired columns to be bound
String[] columns=new String[]{
this.name,
this.phone_number,
this.subject
};
//The XML defined views which the data will be bound to
int[] to = new int[] {
R.id.name,
R.id.phone_number,
R.id.subject,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
}
I am having issues when trying to clear the entries from a Arraylist in Android studio, not matter what code I try the app either does nothing or as with the code below crashes. I'm pulling my hair out with this as in my mind it should work.
I have also tried (not included in the code):
odb.rawquery(" delete from DATABASE_TABLE") //from memory so may not be 100%
This crashed the app and it would not reload, I'm assuming that it was successful in removing the table and not re-creating it?
It will be running on KitKat
Have I missed anything?
This is the last thing I need to make it work so any help or suggestions would be great!
TIA
Main
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
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.SimpleAdapter;
public class MainActivity extends Activity {
private ListView list_lv;
private EditText col2_ed;
private Button sub_btn;
Button del_btn;
private DBclass db;
private ArrayList<String> collist_2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_2 = new ArrayList<String>();
items();
getData();
DeleteData();
}
private void items() {
sub_btn = (Button) findViewById(R.id.submit_btn);
del_btn = (Button) findViewById(R.id.delete_btn);
col2_ed = (EditText) findViewById(R.id.ed2);
list_lv = (ListView) findViewById(R.id.dblist);
sub_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
public void DeleteData(){
del_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.deleteData();
}
});
}
protected void submitData() {
String b = col2_ed.getText().toString();
db = new DBclass(this);
long num;
db.open();
num = db.insertmaster(b);
db.close();
getData();
}
public void getData() {
collist_2.clear();
db = new DBclass(this);
try {
db.open();
Cursor cur = db.getAllTitles();
while (cur.moveToNext()) {
String valueofcol2 = cur.getString(2);
collist_2.add(valueofcol2);
}
}
finally {
db.close();
}
printList();
setDataIntoList();
}
private void printList() {
for (int i = 0; i < collist_2.size(); i++) {
}
}
private void setDataIntoList() {
// create the list item mapping
String[] from = new String[] { "col_2" };
int[] to = new int[] { R.id.col2tv };
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < collist_2.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_2", collist_2.get(i));
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.custom, from, to);
list_lv.setAdapter(adapter);
}
}
DBclass
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public String KEY_ROWID = "_id";
public String KEY_COL2 = "col2";
private String DATABASE_NAME = "mydb";
private String DATABASE_TABLE = "mytable";
private int DATABASE_VERSION = 1;
private Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_COL2 + " VARCHAR(15) )";
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()999
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertmaster(String col2) throws SQLException{
ContentValues IV = new ContentValues();
IV.put(KEY_COL2, col2);
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col2) {
ContentValues values = new ContentValues();
values.put(KEY_COL2, col2);
odb.update(DATABASE_TABLE, values, KEY_ROWID + "=" + rowID, null);
}
public void deleteData(){
odb.delete(DATABASE_TABLE, null,null);
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL2 }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL2 }, KEY_ROWID + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
I think you're not opening the database before trying to delete.
public void DeleteData(){
del_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Try adding these lines
try {
db = new DBclass(this);
db.open();
db.deleteData();
}catch(Exception e){
e.print
}finally{
db.close();
}
}
});
}
Add this in DBclass will delete all data from the particular table
public void deleteAll(){
SQLiteDatabase db = this.getWritableDatabase();
String deleteStmt="DELETE FROM "+TABLE_NAME;
db.execSQL(deleteStmt);
db.close();
}
Deleting a single row or single item (where item is the model class or you can pass the keyId/primarykey )
// Deleting single Item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(item.getKeyId()) });
db.close();
}
Also please refer the below link :
https://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
I exercises have done in a simple list of tasks. Here's the code of my class TODOFragment
package pl.edu.ug.aib.studentizerApp.fragment;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import org.androidannotations.annotations.EFragment;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import pl.edu.ug.aib.studentizerApp.R;
import pl.edu.ug.aib.studentizerApp.todoList.DatabaseHandler;
import pl.edu.ug.aib.studentizerApp.todoList.Task;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#EFragment(R.layout.fragment_todo)
public class TODOFragment extends android.support.v4.app.Fragment {
EditText zadanieTxt, opisTxt, dataTxt, adresTxt;
List<Task> Tasks = new ArrayList<Task>();
ListView TaskListView;
DatabaseHandler dbHandler;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_todo, container, false);
}
#Override
public void onStart() {
super.onStart();
zadanieTxt = (EditText) getView().findViewById(R.id.txtZadanie);
opisTxt = (EditText) getView().findViewById(R.id.txtOpis);
dataTxt = (EditText) getView().findViewById(R.id.txtData);
adresTxt = (EditText) getView().findViewById(R.id.txtAdres);
TaskListView = (ListView) getView().findViewById(R.id.listView);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
TabHost tabHost = (TabHost) getView().findViewById(R.id.baner);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Dodaj zadanie");
tabSpec.setContent(R.id.tabZadanie);
tabSpec.setIndicator("Dodaj Zadanie");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("lista");
tabSpec.setContent(R.id.tabListaZadan);
tabSpec.setIndicator("Lista");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) getView().findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Task task = new Task(dbHandler.getTaskCount(), String.valueOf(zadanieTxt.getText()), String.valueOf(opisTxt.getText()), String.valueOf(dataTxt.getText()), String.valueOf(adresTxt.getText()));
if (!taskExists(task)) {
dbHandler.createZadanie(task);
Tasks.add(task);
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " zostało dodane do listy zadań!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " Zadanie już istnieje", Toast.LENGTH_SHORT).show();
}
});
zadanieTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
addBtn.setEnabled(String.valueOf(zadanieTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
if (dbHandler.getTaskCount() != 0)
Tasks.addAll(dbHandler.getAllTasks());
populateList();
}
private boolean taskExists(Task task) {
String zadanie = task.getZadanie();
int taskCount = Tasks.size();
for (int i = 0; i < taskCount; i++) {
if (zadanie.compareToIgnoreCase(Tasks.get(i).getZadanie()) == 0)
return true;
}
return false;
}
private void populateList() {
ArrayAdapter<Task> adapter = new TaskListAdapter();
TaskListView.setAdapter(adapter);
}
private class TaskListAdapter extends ArrayAdapter<Task> {
public TaskListAdapter()
{
super (TODOFragment.this.getActivity(), R.layout.listview_item, Tasks);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Task currentTask = Tasks.get(position);
TextView zadanie = (TextView) view.findViewById(R.id.zadanie);
zadanie.setText(currentTask.getZadanie());
TextView opis = (TextView) view.findViewById(R.id.opis);
opis.setText(currentTask.getOpis());
TextView data = (TextView) view.findViewById(R.id.data);
data.setText(currentTask.getData());
TextView adres = (TextView) view.findViewById(R.id.adres);
adres.setText(currentTask.getAdres());
return view;
}
}
}
And my DatabaseHandler
package pl.edu.ug.aib.studentizerApp.todoList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kisiel on 2015-06-02.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ZadaniaManager",
TABLE_ZADANIA = "zadania",
KEY_ID = "id",
KEY_ZADANIE = "zadanie",
KEY_OPIS = "opis",
KEY_DATA = "data",
KEY_ADRES = "adres";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_ZADANIA + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ZADANIE + " TEXT," + KEY_OPIS + " TEXT," + KEY_DATA + " TEXT," + KEY_ADRES + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ZADANIA);
onCreate(db);
}
public void createZadanie(Task task) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ZADANIE, task.getZadanie());
values.put(KEY_OPIS, task.getOpis());
values.put(KEY_DATA, task.getData());
values.put(KEY_ADRES, task.getAdres());
db.insert(TABLE_ZADANIA, null, values);
db.close();
}
public Task getTask(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_ZADANIA, new String[] { KEY_ID, KEY_ZADANIE, KEY_OPIS, KEY_DATA, KEY_ADRES }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
Task task = new Task(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
db.close();
cursor.close();
return task;
}
public void deleteTask(Task task) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_ZADANIA, KEY_ID + "=?", new String[] { String.valueOf(task.getId()) });
db.close();
}
public int getTaskCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ZADANIA, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateTask(Task task) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ZADANIE, task.getZadanie());
values.put(KEY_OPIS, task.getOpis());
values.put(KEY_DATA, task.getData());
values.put(KEY_ADRES, task.getAdres());
int rowsAffected = db.update(TABLE_ZADANIA, values, KEY_ID + "=?", new String[] { String.valueOf(task.getId()) });
db.close();
return rowsAffected;
}
public List<Task> getAllTasks() {
List<Task> tasks = new ArrayList<Task>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ZADANIA, null);
if (cursor.moveToFirst()) {
do {
tasks.add(new Task(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return tasks;
}
}
The problem is when you added a second task. The first has been added successfully, when you try to add another message appears:
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " Zadanie już istnieje", Toast.LENGTH_SHORT).show();
I am using a ListView with CursorAdapter to display some information. Depending on the information type the row is different but in reality some items are right and some left.
Here is my Activity
package ;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.QuickContactBadge;
public class ConversationActivity extends BaseActivity implements
OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = ConversationActivity.class
.getSimpleName();
Cursor cursor; // 1
ListView conversationList; // 2
Button sendButton;
EditText newMessageText;
QuickContactBadge badge;
static String ID;
ConversationReceiver conversationReceiver = new ConversationReceiver();
private static final int LOADER_ID = 0x02;
private ConversationAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onStart() {
super.onStart();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conversation);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
// Die Views suchen
conversationList = (ListView) findViewById(R.id.ConversationList);
sendButton = (Button) findViewById(R.id.Conv_buttonSendMessage);
newMessageText = (EditText) findViewById(R.id.Conv_newMessageText);
Intent intent = getIntent();
ID = intent.getStringExtra("ID");
sendButton.setOnClickListener(this);
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
Log.d(TAG, "Erstelle ActionBar fuer ID: " + ID);
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI };
ContentResolver resolver = getContentResolver();
String[] br_projection = new String[] { BaseColumns._ID,
"conv_type", "address", "Profile_ID" };
Cursor ConvCursor = resolver
.query(Uri
.parse("content://.../conversations"),
br_projection, BaseColumns._ID + " = ?",
new String[] { ID }, null);
ActionBar actionBar = getActionBar();
if (ConvCursor.moveToFirst()) {
String number = "";
number = ConvCursor.getString(ConvCursor
.getColumnIndexOrThrow("address"));
Log.v(TAG, "Nummer: " + number);
Uri contactUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactCursor = getContentResolver().query(
contactUri, projection, null, null, null);
Log.v(TAG, "contactCursor.moveToFirst");
if (contactCursor.moveToFirst()) {
// Get values from contacts database:
String ContactName = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
String ContactThumbnailString = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI));
ImageView logo = (ImageView) findViewById(android.R.id.home);
if (ContactThumbnailString != null) {
Uri ContactThumbnailURI = Uri
.parse(ContactThumbnailString);
logo.setImageURI(ContactThumbnailURI);
}
actionBar.setTitle(ContactName);
} else {
actionBar.setTitle(R.string.ContactNoName);
}
actionBar
.setSubtitle(PhoneNumberUtils.formatNumber(number));
}
}
} catch (Exception e) {
Log.e(TAG, "ConvAct Header Info ", e);
}
adapter = new ConversationAdapter(this, cursor);
conversationList.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(conversationReceiver);
}
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = new String[] { BaseColumns._ID, "item_type",
"send", "serverid", "direction", "date", "content", "sender",
"Conv_ID" };
Intent intent = getIntent();
return new CursorLoader(
this,
Uri.parse("content://.../items"),
projection, "Conv_ID = ?", new String[] { intent
.getStringExtra("ID") }, "date ASC");
}
#SuppressLint("NewApi")
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#SuppressLint("NewApi")
public void onLoaderReset(Loader<Cursor> cursorLoader) {
adapter.swapCursor(null);
}
// Wird bei Klicks auf den Button aufgerufen //
public void onClick(View v) {
Log.d(TAG, "Neues Item fuer ID: "+ID);
ContentResolver resolver = getContentResolver();
Cursor convCursor = resolver
.query(Uri
.parse("content://.../conversations/"
+ ID), new String[] { "address" }, null, null,
null);
convCursor.moveToFirst();
ContentValues values = new ContentValues();
values.clear();
values.put("item_type", "tm");
values.put("direction", "out");
values.put("send", "0");
values.put("date", String.valueOf(System.currentTimeMillis()));
values.put("content", newMessageText.getText().toString());
values.put("sender",
convCursor.getString(convCursor.getColumnIndex("address")));
values.put("Conv_ID", ID);
resolver.insert(Uri
.parse("content://.../items"),
values);
newMessageText.setText("");
}
}
Here is a part of my CursorAdapter
package ;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.QuickContactBadge;
import android.widget.TextView;
public class ConversationAdapter extends CursorAdapter {
private static final String TAG = ConversationAdapter.class.getSimpleName();
#SuppressWarnings("deprecation")
public ConversationAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
String item_direction = cursor.getString(cursor
.getColumnIndexOrThrow("direction"));
View v = null;
if (item_direction.equals("out")) {
v = inflater.inflate(R.layout.conversationrow_out, parent, false);
} else if (item_direction.equals("in")) {
v = inflater.inflate(R.layout.conversationrow_in, parent, false);
}
bindView(v, context, cursor);
return v;
}
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public void bindView(View row, Context context, Cursor cursor) {
String item_type = cursor.getString(cursor
.getColumnIndexOrThrow("item_type"));
Log.v(TAG, item_type);
Cursor contactCursor = null;
try {
TextView ConversationText = (TextView) row
.findViewById(R.id.ConversationText);
Log.v(TAG, "message selected");
// Definition
String[] projection;
String number, textContent = "";
Uri ThumbnailURI = null;
String ThumbnailString;
QuickContactBadge ConversationBadge = null;
Log.d(TAG,
"Nachricht mit Inhalt: "
+ cursor.getString(cursor
.getColumnIndexOrThrow("content"))
+ " in Richtung: "
+ cursor.getString(cursor
.getColumnIndexOrThrow("direction")));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI };
ConversationBadge = (QuickContactBadge) row
.findViewById(R.id.ConversationBadge);
} else {
projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };
}
Log.v(TAG, "Lese nun Nutzerdaten");
number = cursor.getString(cursor.getColumnIndexOrThrow("sender"));
Uri contactUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Log.v(TAG, "Nutzerdaten-Query");
contactCursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (contactCursor.moveToFirst()) {
String name = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ConversationBadge.assignContactFromPhone(number, true);
ThumbnailString = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI));
if (cursor.getString(
cursor.getColumnIndexOrThrow("direction")).equals(
"in")
&& ThumbnailString != null) {
ThumbnailURI = Uri.parse(ThumbnailString);
ConversationBadge.setImageURI(ThumbnailURI);
} else {
ConversationBadge.setImageToDefault();
}
}
// textContent = name+": ";
} else {
// textContent = number+": ";
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ConversationBadge.setImageToDefault();
}
}
if (item_type.equals("tm")) {
textContent += (cursor.getString(cursor
.getColumnIndexOrThrow("content")));
}
ConversationText.setText(textContent);
TextView ConversationTime = (TextView) row
.findViewById(R.id.ConversationTime);
long timestamp = cursor.getLong(cursor.getColumnIndex("date"));
ConversationTime.setText(DateUtils
.getRelativeTimeSpanString(timestamp));
} catch (Exception e) {
Log.e(TAG, "bindView ", e);
} finally {
contactCursor.close();
}
}
}
When I open the Activity everything looks fine. Incomming messages appear left-adjusted and outgoing ones are right-adjusted (basicly). When I have a new message i call the above code to requery and update the list. The Content of the new item now appears on the bvottom as I like it but the layout of this last item seems to be the one of the intitial last. The layout for this new item appears on the top.
I would like to post images but I don't have enought reputation points. :(
Thanks
I was researching on how to add tables in an sqlite database for more information but I can't have a grip on how it was truly done.
I have this code:
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "SCORING";
public static final String MYDATABASE_TABLE = "SCORING_TABLE";
public static final String MYDATABASE_TABLE1 = "Assessment";
public static final int MYDATABASE_VERSION = 3;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table SCORING (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT1 + " text not null, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + "text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content1, String content2, String content3){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT1, content1);
contentValues.put(KEY_CONTENT2, content2);
contentValues.put(KEY_CONTENT3, content3);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2, KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE SCORING_TABLE ADD COLUMN Content4 TEXT");
}
}
}
}
and for the second one I'm having a hard time inputting data to the second table
package com.example.database;
import com.example.database.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidSQLite extends Activity {
EditText inputContent2;
TextView textView1, textView2;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
inputContent2 = (EditText)findViewById(R.id.content2);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2, R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int a=Integer.parseInt(textView1.getText().toString());
int b=a+2;
String s1 = String.valueOf(b);
textView1.setText(s1);
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
String data1 = textView1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = textView2.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
}
I personally found using ContentProviders to be a clearer and easier to maintain way to manage multiple tables.
There is a nice article here that explains ContentProviders and other ways of dealing with android database/
http://www.vogella.com/articles/AndroidSQLite/article.html#tutorialusecp