android sqlite getting distinct name and * amounts - android

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

Related

Alert dialog delete a row on ListView Item click

Good Day Guys..Need some help here..i got troubled from deleting the selected row in my list view..i want to use an alert dialog for confirmation to delete the selected row..and to edit also..i am a beginner and i have tried searching for answers to this problem and also tried relating it to other problems but i still didn't get it...
My DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper implements Filterable{
// private static final String COLUMN_NAME="ageing_column";
private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ContractClass.NewInfo.TABLE_NAME+"("+ ContractClass.NewInfo.ITEM_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ContractClass.NewInfo.DESCRIPTION+" TEXT, "+
ContractClass.NewInfo.CATEGORY+" TEXT,"+ ContractClass.NewInfo.MONTHONE+" TEXT, "+ ContractClass.NewInfo.REMIND_AT+" TEXT, "+ ContractClass.NewInfo.QTY+" TEXT, "+
ContractClass.NewInfo.LOCATION+" TEXT );";
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context1=context;
Log.e("DATABASE OPERATIONS", "Database created / opened....");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created....");
}
public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(ContractClass.NewInfo.LOCATION,location);
contentValues.put(ContractClass.NewInfo.DESCRIPTION,description);
contentValues.put(ContractClass.NewInfo.CATEGORY,category);
contentValues.put(ContractClass.NewInfo.MONTHONE,monthOne);
contentValues.put(ContractClass.NewInfo.REMIND_AT,remind);
contentValues.put(ContractClass.NewInfo.QTY,quantity);
db.insert(ContractClass.NewInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
db.close();
}
public Cursor getInformations(SQLiteDatabase db)
{
Cursor cursor;
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
cursor=db.query(ContractClass.NewInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
{
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
String selection = ContractClass.NewInfo.LOCATION+" LIKE? ";
String [] sargs={location};
Cursor cursor=sqLiteDatabase.query(ContractClass.NewInfo.TABLE_NAME,projections,selection,sargs,null,null,null);
return cursor;
}
public String[] SelectAllData()
{
try
{
String arrData[]=null;
SQLiteDatabase db;
db=this.getReadableDatabase();
String strSQL=" SELECT "+ ContractClass.NewInfo.LOCATION+" FROM "+ ContractClass.NewInfo.TABLE_NAME;
Cursor cursor =db.rawQuery(strSQL,null);
if(cursor !=null)
{
if(cursor.moveToFirst())
{
arrData=new String[cursor.getCount()];
int i=0;
do
{
arrData[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
}
}
cursor.close();
return arrData;
}catch(Exception e){
return null;
}
}
public void delete_byID(int id){
sqLiteDatabase.delete(ContractClass.NewInfo.TABLE_NAME, ContractClass.NewInfo.ITEM_ID + "=" + id, null);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public Filter getFilter() {
return null;
}
}
THis is My MAin Class..
public class ViewListsActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
ListDataAdapter listDataAdapter;
ListView listView;
Cursor cursor;
EditText delete_txt;
String deletetxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_lists_activity);
listView = (ListView) findViewById(R.id.search_listView);
listDataAdapter = new
ListDataAdapter(getApplicationContext(),R.layout.row_layout);
databaseHelper = new DatabaseHelper(getApplicationContext());
databaseHelper = new DatabaseHelper(this);
delete_txt = (EditText) findViewById(R.id.delete_text);
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
listView.setAdapter(listDataAdapter);
if (cursor.moveToFirst()) {
do {
String description, category, month1,remind,qty,location;
description = cursor.getString(0);
category = cursor.getString(1);
month1 = cursor.getString(2);
qty=cursor.getString(3);
remind=cursor.getString(4);
location = cursor.getString(5);
DataProvider dataProvider = new DataProvider(description,
category, month1,qty,remind,location);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View
view, int position, long id) {
return false;
}
});
}
public void ToSearchBtn(View view)
{
Intent intent=new Intent(this,ThirdActivitySearchAllData.class);
startActivity(intent);
}
public void ToAddNewItemBtn(View view)
{
Intent intent=new Intent(this,SecondActivitySaveData.class);
startActivity(intent);
}
}
My List Adapter Class
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
}
public void add(Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =convertView;
LayoutHandler layoutHandler;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
row.setTag(layoutHandler);
}else
{
layoutHandler=(LayoutHandler)row.getTag();
}
DataProvider dataProvider= (DataProvider) this.getItem(position);
layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
layoutHandler.CATEGORY.setText(dataProvider.getCategory());
layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
layoutHandler.REMIND.setText(dataProvider.getRemindAt());
layoutHandler.QTY.setText(dataProvider.getQuantity());
layoutHandler.LOCATION.setText(dataProvider.getLocation());
return row;
}
}
You can use ALERT DIALOG for showing confirmation popup, with YES/NO option both for delete and edit, and based on options selected in ALERT DIALOG you can perform further operations
In the below link you can find the sample code
How do I display an alert dialog on Android?

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,.

Updating SQL row with OnItemLongClick doesn't work

Can anybody please have a look at my code and tell me where I am wrong? I don't get errors, unfortunately the row that is long pressed and new value is provided is not being updated unless I specify exact row number. I need to be able to update the row that is clicked. I tried everything and up to today I didn't manage to get any help. I am beginner in Android development.
Here is the code of MyDB:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" ,
new String[]{ Double.valueOf(rowId).toString() })>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the code with the dialog, where I should update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
private long rowId;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
long rowId = adapter.getItemId(position); //Will return the clicked item
saveItToDB(rowId);
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
// public void notifyDataSetChanged();
dismiss();
try {
saveItToDB(rowId);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB(long rowId) {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), rowId);
dba.close();
((TextView) editText).setText("");
}
}
And here is the Diary Adapter:
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
i found first problem at your DB class
update this method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
To
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, new String[]{Constants.TITLE_NAME ,Constants.CONTENT_NAME}, null,
null, null, null, null);
return c;
}

Making a dynamic ListView clickable to change activity

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?

How to update row that is clicked?

After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}

Categories

Resources