Making a dynamic ListView clickable to change activity - android

My android app currently populates a ListView (in MainActivity) with the contents of a sqlite table. I would like to be able to click one of the created ListView Items and have it change activities to my EditNote activity, but also pass the database record relating to that ListView into EditNote, and populate the EditTexts.
My MainActivity is populates the ListView on load:
public class MainActivity extends ListActivity{
DatabaseHelper dbh;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
ArrayList<String[]> searchResult = new ArrayList<String[]>();
//EditText searchTitle = (EditText) findViewById(R.id.searchC);
listItems.clear();
searchResult = dbh.fetchNotes("");
//searchResult = dbh.fetchNotes(searchTitle.getText().toString());
String title = "", note = "";
for (int count = 0 ; count < searchResult.size() ; count++) {
note = searchResult.get(count)[1];
title = searchResult.get(count)[0];
listItems.add(title);
}
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void addNote(View v){
Intent newActivity = new Intent (this, AddingNote.class);
startActivity(newActivity);
finish();
}
}
My database class used to create the table and select statement:
public class DatabaseHelper {
private static final String DATABASE_NAME = "noteDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "note";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT NOT NULL, " +
"note TEXT NOT NULL); ";
public DatabaseHelper(Context ctx) {
this.dbContext = ctx;
}
public DatabaseHelper open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createNote(String title, String note) {
ContentValues initialValues = new ContentValues();
initialValues.put("title", title);
initialValues.put("note", note);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public boolean updateNote(long rowId, String title, String note) {
ContentValues args = new ContentValues();
args.put("title", title);
args.put("note", note);
return mDb.update(TABLE_NAME, args, "_id=" + rowId, null) > 0;
}
public void deleteAll() {
mDb.delete(TABLE_NAME, null, null);
}
public void deleteRecord(long rowID) {
mDb.delete(TABLE_NAME, "_rowId=" + rowID, null);
}
public ArrayList<String[]> fetchNotes(String title) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"_id", "title",
"note"}, null, null,
null, null, "_id");
int titleColumn = mCursor.getColumnIndex("title");
int noteColumn = mCursor.getColumnIndex("note");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(titleColumn);
myArray.get(pointer)[1] = mCursor.getString(noteColumn);
//increment our pointer variable.
pointer++;
} while (mCursor.moveToNext()); // If possible move to the next record
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "id", "forename", "surname", "age" }, null, null, null, null, "surname desc");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0).toString();
results.get(counter)[1] = cursor.getString(1).toString();
results.get(counter)[2] = cursor.getString(2).toString();
results.get(counter)[3] = cursor.getString(3).toString();
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My list view XML (within activity_main.xml):
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/container" >
</ListView>
I'm pretty new to android development, so any help will be gratefully appreciated. Thank you.

Set an onClickListener to your ListView and start an Intent pointing to your EditNote activity which gets the data using:
getIntent().getStringExtra(...);
Example:
MainActivity:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(this, EditNote.class);
i.putExtra("listItem", listItems[position]);
startActivity(i);
}
});
EditNote:
String listItem = getIntent().getStringExtra("listItem");
Is this what you're looking for?

Related

ListView onItemLongClick view isSelected always returns False

I have a class that extends ListFragment and uses a SimpleCursorAdapter. I have created 2 buttons that enables the user to select/deselect all in the list and this works fine. There could be 200 items in the list, so if they wanted to only select 190 of them, they could select all 200 then deselect 10.
The ListView uses setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
The problem is that I want the user to be able to individually deselect a row by long pressing the row. I use a setOnItemLongClickListener on the ListView but the view.isSelected is always returning false even when the row is selected.
Does anyone know why this is happening.
I've put log statements in to prove this fact.
I have also had a look around the net and some posts are saying that a possible problem is that I am using SimpleCursorAdapter and that it is too basic a component.
I'm not particularly good with adapters, lists and touch events, so could anyone point me in the right direction?
I suppose the obvious thing to tackle, is why the isSelected method always returns false.
public class CarerListForGroupMessageFragment extends ListFragment {
private static final String TAG = CarerListForGroupMessageFragment.class.getSimpleName();
RROnCallApplication rrOnCallApp;
Cursor cursor;
ListView listView;
MyAdapter myAdapter;
OnCarerForGroupMessageSelectedListener mListener;
EditText etext;
Button resetSearch;
Button selectAll;
Button deselectAll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rrOnCallApp = (RROnCallApplication) getActivity().getApplicationContext();
cursor = getCarerList(null);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentcarerlistforgroupmessage, container, false);
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] from = new String[]{DBModel.C_CARER_FIRSTNAME, DBModel.C_CARER_LASTNAME, DBModel.C_CARER_PHONENUMBER};
int[] to = {R.id.carerrowfirstname, R.id.carerrowlastname, R.id.carerrowtelno};
myAdapter = (MyAdapter) new MyAdapter(getActivity(),R.layout.carerrow , cursor, from, to);
setListAdapter(myAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setFastScrollEnabled(true);
getListView().setTextFilterEnabled(true);
selectAll = (Button) getActivity().findViewById(R.id.carerlistselectallgroupmessage);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++){
getListView().setItemChecked(i, true);
}
myAdapter.notifyDataSetChanged();
}
});
deselectAll = (Button) getActivity().findViewById(R.id.carerlistdeselectallgroupmessage);
deselectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++) {
getListView().setItemChecked(i, false);
}
myAdapter.notifyDataSetChanged();
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();
boolean ret = false;
if(! view.isSelected()) {
//row in list is not currently selected, so set it as selected
Log.e(TAG, "row postion " + position + " in list is not currently selected");
view.setSelected(true);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
ret = true;
} else {
Log.e(TAG, "row " + position + " in list is currently selected");
view.setSelected(false);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, false);
myAdapter.notifyDataSetChanged();
ret = true;
}
return ret;
}
});
} // End of onActivityCreated
// Container Activity must implement this interface
public interface OnCarerForGroupMessageSelectedListener {
public void onCarerForGroupMessageSelected(String carerId, String carerFirstName, String carerLastName, String carerTelNo ,boolean longClick);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnCarerForGroupMessageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCarerForGroupMessageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.e(TAG, "in onListItemClick");
v.setSelected(true);
//v.setBackgroundColor(Color.parseColor("#FF0000"));
TextView carerName = (TextView) getView().findViewById(R.id.textviewcarername);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, false);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
}
private class MyAdapter extends SimpleCursorAdapter {
#SuppressWarnings("deprecation")
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public
View getView(int position, View convertView, ViewGroup parent) {
Log.e(TAG, "inside myadapter getview");
View v = super.getView(position, convertView, parent);
if(v == null)
return null;
Log.e(TAG, "clicked the listview!");
//Cursor c = (Cursor)getItem(position);
// String tagScanTime = c.getString(c.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
// ((TextView)v.findViewById(R.id.rowcarername)).setText(name + " signed " + status +" at ");
return v;
}
}} //end of CarerListFragment
[EDIT 1]
DBModel class
public class DBModel {
private static final String TAG = DBModel.class.getSimpleName();
// table carer column names
public static final String C_CARER_ID_INDEX = BaseColumns._ID;
public static final String C_CARER_ID = "carerid";
public static final String C_CARER_FIRSTNAME = "carerfirstname";
public static final String C_CARER_LASTNAME = "carerlastname";
public static final String C_CARER_PHONENUMBER = "carerphonenumber";
public static final String C_CARER_EMAIL = "careremail";
Context context;
DBHelper dbhelper;
RROnCallApplication rrOnCallApplication;
public DBModel(Context context) {
this.context = context;
dbhelper = new DBHelper();
rrOnCallApplication = (RROnCallApplication) context.getApplicationContext();
}
/**
* inner class to create/open/upgrade database
*
* #author matt
*
*/
private class DBHelper extends SQLiteOpenHelper {
// database name and version number
public static final String DB_NAME = "roadrunneroncall.db";
public static final int DB_VERSION = 3;
// table names
public static final String TABLECARER = "carer";
public DBHelper() {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "SQLiteOpenHelper oncreate ");
String sqlToCreateCarerTable = String
.format("create table %s ( %s INTEGER primary key, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)",
TABLECARER, C_CARER_ID_INDEX, C_CARER_ID, C_CARER_FIRSTNAME,
C_CARER_LASTNAME, C_CARER_PHONENUMBER, C_CARER_EMAIL);
db.execSQL(sqlToCreateCarerTable);
Log.e(TAG, "oncreate " + sqlToCreateCarerTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}//end of onUpgrade
}//end of DBHelper
public SQLiteDatabase getDB(){
return dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
}
public void deleteTableCarer() {
// open database
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
// delete contents of table
db.delete(DBHelper.TABLECARER, null, null);
// close database
// db.close();
}
public void insertIntoCarer(ContentValues cv) {
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
db.insertWithOnConflict(DBHelper.TABLECARER, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
// db.close();
}
public Cursor queryAllFromCarer() {
// open database
SQLiteDatabase db = dbhelper.getReadableDatabase(RROnCallApplication.getSecretKey().toString());
return db.query(DBHelper.TABLECARER, null, null, null, null, null, null);
}
Please check this code.
if(!getListView().isItemChecked(position))
instead of
if(! view.isSelected())
And keep boolean flag value inside DBModel class.

How to read,add Database into ArrayList?

I'm new to Android Studio here. I don't know how to read and add database into Arraylist . Could you guys please help me with it :P ? I have already tried some methods, but It still didn't work #.# .
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "ToDoList.db";
public static final String TABLE_NAME = "ToDoList_Table";
public static final String DATABASE_TABLE = "ToDo_DBTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "TODO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TODO TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String TODO) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, TODO);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public ArrayList<String> getRecords(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> data=new ArrayList<String>();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_2},null, null, null, null, null);
String fieldToAdd=null;
while(cursor.moveToNext()){
fieldToAdd=cursor.getString(0);
data.add(fieldToAdd);
}
cursor.close();
return data;
}
}
public class MainActivity extends AppCompatActivity
{
DatabaseHelper TDdb;
ArrayList<String> todoItems;
ArrayAdapter<String> aTodoAdapter;
ListView lvItems;
EditText editTD;
Button btnAddItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
populateArrayItems();
editTD = (EditText) findViewById(R.id.tdEditText);
lvItems = (ListView) findViewById(R.id.lvItems);
btnAddItems = (Button) findViewById(R.id.tdAddItems);
AddData();
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.list_ingredients);
getSupportActionBar().setDisplayUseLogoEnabled(true);
lvItems.setAdapter(aTodoAdapter);
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long id) {
todoItems.remove(position);
aTodoAdapter.notifyDataSetChanged();
return true;
}
});
TDdb = new tdls.todolistapps.DatabaseHelper(this);
}
public void AddData()
{
btnAddItems.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean isInserted = TDdb.insertData(editTD.getText().toString());
if(isInserted = true )
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Items not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void populateArrayItems()
{
todoItems = new ArrayList<String>();
todoItems.add("Item 1");
todoItems.add("Item 2");
todoItems.add("Item 3");
aTodoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.add("Email");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onAddItem(View v)
{
aTodoAdapter.add(editTD.getText().toString());
editTD.setText("");
}
}
Here is the picture, it said that Item Inserted but It won't display :'(
Try replacing following code
if(isInserted = true ){
todoItems.add(editTD.getText().toString());
aTodoAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Items not Inserted", Toast.LENGTH_LONG).show();
}
As you need to update adapter as well after adding data to database.
At First change your getRecords() function like below:
public ArrayList<String> getRecords(){
open();
ArrayList<String> data = new ArrayList<>();
Cursor cursor = db.query(DATABASE_TABLE, new String[]{COL_2}, null, null, null, null, null, null);
if (cursor.moveToFirst()){
do {
data.add(cursor.getString(0));
} while (cursor.moveToNext());
}
close();
return data;
}

how to display data from sqlite in custom listfragment

I want to display data from sqlite database and I will show to listfragment, but until now have not been able to be displayed
Class Barang.java
public class Barang {
private long id;
private String nama_barang;
private String merk_barang;
private String harga_barang;
public Barang()
{
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the nama_barang
*/
public String getNama_barang() {
return nama_barang;
}
/**
* #param nama_barang the nama_barang to set
*/
public void setNama_barang(String nama_barang) {
this.nama_barang = nama_barang;
}
/**
* #return the merk_barang
*/
public String getMerk_barang() {
return merk_barang;
}
/**
* #param merk_barang the merk_barang to set
*/
public void setMerk_barang(String merk_barang) {
this.merk_barang = merk_barang;
}
/**
* #return the harga_barang
*/
public String getHarga_barang() {
return harga_barang;
}
/**
* #param harga_barang the harga_barang to set
*/
public void setHarga_barang(String harga_barang) {
this.harga_barang = harga_barang;
}
#Override
public String toString()
{
return id +" "+ nama_barang +" "+ merk_barang + " "+ harga_barang;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "data_inventori";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nama_barang";
public static final String COLUMN_MERK = "merk_barang";
public static final String COLUMN_HARGA = "harga_barang";
private static final String db_name ="inventori.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID +" integer primary key autoincrement, "
+ COLUMN_NAME+ " varchar(50) not null, "
+ COLUMN_MERK+ " varchar(50) not null, "
+ COLUMN_HARGA+ " varchar(50) not null);";
public DBHelper(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
Log.w(DBHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
DBDataSource.java
public class DBDataSource {
private SQLiteDatabase database;
private DBHelper dbHelper;
private String[] allColumns = { DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAME, DBHelper.COLUMN_MERK,DBHelper.COLUMN_HARGA};
public DBDataSource(Context context)
{
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Barang createBarang(String nama, String merk, String harga) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, nama);
values.put(DBHelper.COLUMN_MERK, merk);
values.put(DBHelper.COLUMN_HARGA, harga);
long insertId = database.insert(DBHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, DBHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Barang newBarang = cursorToBarang(cursor);
cursor.close();
return newBarang;
}
private Barang cursorToBarang(Cursor cursor)
{
Barang barang = new Barang();
barang.setId(cursor.getLong(0));
barang.setNama_barang(cursor.getString(1));
barang.setMerk_barang(cursor.getString(2));
barang.setHarga_barang(cursor.getString(3));
return barang;
}
public ArrayList<Barang> getAllBarang() {
ArrayList<Barang> daftarBarang = new ArrayList<Barang>();
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Barang barang = cursorToBarang(cursor);
daftarBarang.add(barang);
cursor.moveToNext();
}
cursor.close();
return daftarBarang;
}
public Barang getBarang(long id)
{
Barang barang = new Barang();
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, "_id ="+id, null, null, null, null);
cursor.moveToFirst();
barang = cursorToBarang(cursor);
cursor.close();
return barang;
}
public void updateBarang(Barang b)
{
String strFilter = "_id=" + b.getId();
ContentValues args = new ContentValues();
args.put(DBHelper.COLUMN_NAME, b.getNama_barang());
args.put(DBHelper.COLUMN_MERK, b.getMerk_barang());
args.put(DBHelper.COLUMN_HARGA, b.getHarga_barang() );
database.update(DBHelper.TABLE_NAME, args, strFilter, null);
}
public void deleteBarang(long id)
{
String strFilter = "_id=" + id;
database.delete(DBHelper.TABLE_NAME, strFilter, null);
}
}
MasterBarang.java
public class MasterBarang extends ListFragment implements OnItemLongClickListener {
private DBDataSource dataSource;
private ImageButton bTambah;
private ArrayList<Barang> values;
private Button editButton;
private Button delButton;
private AlertDialog.Builder alertDialogBuilder;
public MasterBarang(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masterbarang, container, false);
bTambah = (ImageButton) rootView.findViewById(R.id.button_tambah);
bTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateData.class);
startActivity(intent);
getActivity().finish();
}
});
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
return rootView;
}
public void OnCreate(Bundle savedInstanceStat){
dataSource = new DBDataSource(getActivity());
dataSource.open();
values = dataSource.getAllBarang();
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
final Barang b = (Barang) getListAdapter().getItem(pos);
alertDialogBuilder.setTitle("Peringatan");
alertDialogBuilder
.setMessage("Pilih Aksi")
.setCancelable(false)
.setPositiveButton("Ubah",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
switchToEdit(b.getId());
dialog.dismiss();
}
})
.setNegativeButton("Hapus",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dataSource.deleteBarang(b.getId());
dialog.dismiss();
getActivity().finish();
startActivity(getActivity().getIntent());
}
}).create().show();
return false;
}
public void switchToEdit(long id)
{
Barang b = dataSource.getBarang(id);
Intent i = new Intent(getActivity(), EditData.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("nama", b.getNama_barang());
bun.putString("merk", b.getMerk_barang());
bun.putString("harga", b.getHarga_barang());
i.putExtras(bun);
finale();
startActivity(i);
}
public void finale()
{
MasterBarang.this.getActivity().finish();
dataSource.close();
}
#Override
public void onResume() {
dataSource.open();
super.onResume();
}
#Override
public void onPause() {
dataSource.close();
super.onPause();
}
}
in simple not displayed
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Now run the application.. Cheers !
You are using simple list templete as a list view. But in case of custom list view, you should create your custom list model and "BaseAdapter" for the custom list model.
Below links will help you to make custom list view in easier way.
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
The problem is you are closing your database in onPause() method, so the reference of the database will get destroyed. Then, you again trying to open the database in onResume() method. So here the null pointer exception occurs.
Solution:
change your onResume() method like this.
#Override
public void onResume() {
dataSource = new DBDataSource(getActivity());
dataSource.open();
super.onResume();
}
Now check it and if you got any error please post it here,.

android sqlite getting distinct name and * amounts

I am trying to get a list of names with total amounts from a sqlite db.
It is working in a way that shows a list of all the transactions with the
correct combined total. I also have a table in the same db that has usernames
& phone numbers, but I don't think that would be too useful for this activity.
Also, how do I use the onListItemClick to send the next activity something
that I can use to pull only names from the User the person selected? The ID
is being sent, but I don't know how to use it.
ie:
trans table:
Justin 25
Justin 25
Justin 25
Sophia 80
Hoped results:
Justin 75
Sophia 80
Actual results:
Justin 75
Justin 75
Justin 75
Sophia 80
ListActivity that populates the list (with cursor and TextView link)
public class Totals extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
UserHelper uhelp;
Cursor umodel = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_person);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Totals.this, Detail.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Totals.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.person_row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView amount_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_row);
amount_line = (TextView)row.findViewById(R.id.amount_row);
}
void populateFrom(Cursor c, PaymentHelper helper) {
name_line.setText(helper.getName(c));
amount_line.setText(Integer.toString(helper.sumPerson(c, helper.getName(c))));
}
}
}
SQLiteOpenHelper code to retrieve info
public class PaymentHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "bookkeeping.db";
private static final int SCHEMA_VERSION = 1;
SQLiteDatabase db;
public PaymentHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db = db1;
String sql = "CREATE TABLE IF NOT EXISTS trans (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, date TEXT, amount INT, note TEXT)";
//execute the sql statement
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String name, String date, int amount, String note){
Log.e(name, date + " " + amount);
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
Log.e("Almost", "there");
db.insert("trans", "abc", cv);
Log.e("successfully", "inserted");
}
public Cursor getAll(){
String sql = "SELECT * FROM trans ORDER BY name";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public Cursor getAllNames(){
String sql = "SELECT * FROM users";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public String getName(Cursor c){
return c.getString(c.getColumnIndex("name"));
}
public String getDate(Cursor c){
return c.getString(c.getColumnIndex("date"));
}
public int getAmount(Cursor c){
return c.getInt(c.getColumnIndex("amount"));
}
public String getNote(Cursor c){
return c.getString(c.getColumnIndex("note"));
}
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("trans", "_id=?", args);
}
public Cursor getById(String id){
String[] args = {id};
String sql = "SELECT * FROM trans WHERE _id=?";
Cursor cursor = getReadableDatabase().rawQuery(sql, args);
return cursor;
}
public void update(String id, String name, String date, int amount, String note){
String[] args = {id};
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
getWritableDatabase().update("trans", cv, "_ID=?", args);
}
public int sumPerson(Cursor c, String name){
int total = 0;
// add up totals
String sql = "SELECT amount FROM trans WHERE name=?";
String[] aname = new String[]{name};
getReadableDatabase().rawQuery(sql,aname);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(name.equals(getName(c))){
total += c.getInt(c.getColumnIndex("amount"));
}
}
return total;
}
}
This is the activity that is receiving the ID from Totals:
I would like it to show only one user (which they selected
from the totals page) with all of their transactions.
public class Detail extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.totals:
startActivity(new Intent(this, Totals.class));
break;
case R.id.users:
startActivity(new Intent(this, Users.class));
break;
case R.id.home:
startActivity(new Intent(this, MainMenu.class));
break;
}
return true;
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Detail.this, DeletePayment.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Detail.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView date_line = null;
private TextView amount_line = null;
private TextView note_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_line);
amount_line = (TextView)row.findViewById(R.id.amount_line);
date_line = (TextView)row.findViewById(R.id.date_line);
note_line = (TextView)row.findViewById(R.id.note_line);
}
void populateFrom(Cursor c, PaymentHelper helper) {
Log.e(helper.getName(c), Integer.toString(helper.getAmount(c)));
name_line.setText(helper.getName(c));
date_line.setText(helper.getDate(c));
amount_line.setText(Integer.toString(helper.getAmount(c)));
note_line.setText(helper.getNote(c));
}
}
}
I know this is long...but help would be awesome!
I feel like the "PaymentAdapter" needs to be modified to only
read two names if there is only two names. Should I be utilizing
the "UserHelper" db helper to populate this? but when I do, it only
runs one cursor through, and gets a nullpointerexception error because
it is not moving one of the cursors. Should I be making a PaymentAdapter
within PaymentAdapter to generate use of another cursor?
The following SQL query will give you the desired result:
SELECT name, SUM(amount)
FROM trans
GROUP BY name

Deleting from SQL database android

I have a list view and when the user clicks a specific item a contextual action mode is displayed with only one item in it (that is supposed to delete it). However, when I click it, the database is not updated (the item is still on the list). Could anyone help me ?
In MainActivity:
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
protected Object mActionMode;
int catPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
if(all.size()> 0){
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
}else{
Toast.makeText(MainActivity.this,"No items to display",Toast.LENGTH_LONG).show();
}
entry.close();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
catPos = position;
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MainActivity.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_cat:
// shareCurrentItem();
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.deleteCat(catPos);
List<String> all = entry.getAllCategory();
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
entry.close();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
in Actual Database:
public class CategoryDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public CategoryDatabase(Context c){
ourContext = c;
}
public CategoryDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORY + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String category) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORY, category);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public List<String> getAllCategory() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
List.add(cursor.getString(1));
} while (cursor.moveToNext());
}
return List;
}
public void deleteCat(int catPos) {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + catPos, null);
}
}
Deleting as "entry.deleteCat(catPos);" is not right. If You use Your catPos, which is the position inside the listView, it will not delete the entry from database. You made an INTEGER_PRIMARY_KEY_AUTOINCREMENT inside Your Database, so this Integer will generated automatically and can differ from Your position Integer. What You have to do is, to make a query method inside Your Database where You get even the ID from Your DB-Entry. Then You could call
entry.deleteCat(databaseId);

Categories

Resources