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,.
Related
I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());
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.
I am an amateur android developer and I would like to get user entered items from the database and then display it in a recyclerview list (not ListView) that is in a fragment.
So far I have already created the SQLite database which saves the data into it, I just want to know I can display all this information in the recyclerview. The Java code shown below shows what I want to make but is in a listview instead of a recyclerview.
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "budget10.db";
public static final String TABLE_NAME = "expense_table";
public static final String TABLE_NAME2 = "income_table";
public static final String COL_1 = "_id";
public static final String COL_2 = "_id";
public static final String EXPENSE_AMOUNT = "EXPENSE_AMOUNT";
public static final String EXPENSE_DATE = "DATE";
public static final String EXPENSE_NOTES = "NOTES";
public static final String INCOME_AMOUNT = "INCOME_AMOUNT";
public static final String INCOME_DATE = "DATE";
public static final String INCOME_NOTES = "NOTES";
public static final String INCOME_CATEGORY = "INCOME_CATEGORY";
public static final String EXPENSE_CATEGORY = "EXPENSE_CATEGORY";
public static final String EXPENSE_ACCOUNT = "EXPENSE_ACCOUNT";
public static final String INCOME_ACCOUNT = "INCOME_ACCOUNT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, EXPENSE_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, EXPENSE_CATEGORY TEXT, EXPENSE_ACCOUNT TEXT)");
db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,INCOME_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, INCOME_CATEGORY TEXT, INCOME_ACCOUNT TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
onCreate(db);
}
public boolean insertexpenseData(Double amount_expense, String date_expense, String notes_expense, String category_expense, String expense_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EXPENSE_AMOUNT, amount_expense);
contentValues.put(EXPENSE_DATE, date_expense);
contentValues.put(EXPENSE_NOTES, notes_expense);
contentValues.put(EXPENSE_CATEGORY, category_expense);
contentValues.put(EXPENSE_ACCOUNT, expense_account);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean insertincomeData(Double amount_income, String date_income, String notes_income, String category_income, String income_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INCOME_AMOUNT, amount_income);
contentValues.put(INCOME_DATE, date_income);
contentValues.put(INCOME_NOTES, notes_income);
contentValues.put(INCOME_CATEGORY, category_income);
contentValues.put(INCOME_ACCOUNT, income_account);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getexpenseData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getincomeData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME2, null);
return res;
}
public boolean updateexpenseData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(EXPENSE_AMOUNT, amount);
contentValues.put(EXPENSE_DATE, date);
contentValues.put(EXPENSE_NOTES, notes);
contentValues.put(EXPENSE_CATEGORY, catagory_income);
db.update(TABLE_NAME, contentValues, "_id = ?", new String[]{id});
return true;
}
public boolean updateincomeData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, id);
contentValues.put(INCOME_AMOUNT, amount);
contentValues.put(INCOME_DATE, date);
contentValues.put(INCOME_NOTES, notes);
contentValues.put(INCOME_CATEGORY, catagory_income);
db.update(TABLE_NAME2, contentValues, "_id = ?", new String[]{id});
return true;
}
public Integer deleteexpenseData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "_id = ?", new String[]{_id});
}
public Integer deleteincomeData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME2, "_id = ?", new String[]{_id});
}
public double getNetBudget() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) - (SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netBudget = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netBudget = cursor.getDouble(0);
}
cursor.close();
return netBudget;
}
public double getTotalExpense() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netExpense = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netExpense = cursor.getDouble(0);
}
cursor.close();
return netExpense;
}
public double getTotalIncome() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netIncome = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netIncome = cursor.getDouble(0);
}
cursor.close();
return netIncome;
}
public void deleteAllIncome() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME2, null, null);
db.execSQL("delete from " + TABLE_NAME2);
db.close();
}
public void deleteAllExpense() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
db.execSQL("delete from " + TABLE_NAME);
db.close();
}
}
Fragment ListView that I want to turn into a recyclerview
public class tab2income extends Fragment {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
DecimalFormat formatter = new DecimalFormat("0.00");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) rootView.findViewById(R.id.listViewincome);
mListView.setEmptyView(rootView.findViewById(R.id.empty));
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
incomedata = mDatabaseHelper.getincomeData();
sca = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, incomedata, new String[]{DatabaseHelper.INCOME_AMOUNT}, new int[]{android.R.id.text1}, 0);
mListView.setAdapter(sca);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
public void displayNoteDate(String noteContent, String dateValue,String category, final long noteID,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mDatabaseHelper.deleteincomeData(Long.toString(noteID));
incomedata = mDatabaseHelper.getincomeData();
sca.swapCursor(incomedata);
}
});
builder.show();
}
}
EDIT
This is what I have done so far with the code in the answer from Saurov Bagchi and I have the recyclerview in my xml file and nothing happens when an item is clicked:
Fragment
public class tab2income extends Fragment implements ItemClickListener {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private RecyclerView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = rootView.findViewById(R.id.ListViewincome);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mListView.setLayoutManager(layoutManager);
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
#Override
public void onClick(View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
public void displayNoteDate(String noteContent, String dateValue,String category,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
});
builder.show();
}
}
Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
For RecyclerView you need to create your own custom Adapter.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Then I am just rewriting the populateListView() method
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
You also need to create an Interface for each Item Click.
public interface ItemClickListener {
void onClick (View view, int position);
}
And implement this Interface in your Fragment.
public class tab2income extends Fragment implements ItemClickListener{
//All of your codes
#Override
public void onClick (View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
}
onItemClick doesnot open selected item in viewpager
I have a list view which is populated using a sqlite db with a helperclass
when we click on a item in listview it should open the viewpager class and we can swipe through various details
the viewpager opens but always starts from the first list item
even though I have set the
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
I want to open the viewpager with the item that I have selected and not start from the first entry each time.
here is the listactivity
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private PersonDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new PersonDatabaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Toast.makeText(getApplicationContext(), "aa" + position,
Toast.LENGTH_LONG).show();
//startActivity(new Intent(getApplicationContext(), viepagerActivity.class));
Intent i = new Intent(MyActivity.this, viepagerActivity.class);
i.putExtra("position", position);
MyActivity.this.startActivity(i);
}
});
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this,
databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class),
ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(
data.getExtras().getString("tag_person_name"), data
.getExtras().getString("tag_person_pin"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
adapter
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater
.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view
.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor
.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view
.findViewById(R.id.tv_person_pin);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2))));
}
}
The viewpager
public class viepagerActivity extends Activity {
private List<String> testContactName = new ArrayList<String>();
private List<String> testContactNumber = new ArrayList<String>();
MyAdapter mAdapter;
private PersonDatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
databaseHelper = new PersonDatabaseHelper(this);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
Toast.makeText(getApplicationContext(), "viepager" + index, Toast.LENGTH_LONG)
.show();
try {
getAllContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAllContacts() {
SQLiteDatabase db = databaseHelper.database;
String[] columns = { PersonDatabaseHelper.PERSON_TABLE_COLUMN_ID,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_NAME,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_PIN, };
Cursor cursor = db.query(PersonDatabaseHelper.TABLE_NAME, columns,
null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1)));
String phoneNumber = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2)));
testContactName.add(name);
mAdapter.notifyDataSetChanged();
testContactNumber.add(phoneNumber);
mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return collection == ((View) object);
}
#Override
public Object instantiateItem(View collection, int position) {
Bundle b = getIntent().getExtras();
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewpager_items, null);
TextView contactName = (TextView) view.findViewById(R.id.labelText);
TextView contactNumber = (TextView) view
.findViewById(R.id.answerText);
try {
contactName.setText(testContactName.get(position));
contactNumber.setText(testContactNumber.get(position));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
the helper class
public class PersonDatabaseHelper {
public static final String TAG = PersonDatabaseHelper.class
.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
public static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column
// named "_id"
// is required
// for cursor
public static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
public DatabaseOpenHelper openHelper;
public SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will
// communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform
// database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData(String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData() {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database
// related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( "
+ PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ PERSON_TABLE_COLUMN_NAME + " TEXT, "
+ PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion,
int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks
EDIT: the code is equal at the example but with the field i need to add.
The DisplayActivity
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_address = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("address", user_address.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ user_address.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_address.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
userList.setAdapter(disadpt);
mCursor.close();
}
}
The DisplayAdapter
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> address;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.address = address;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_address.setText(address.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_address;
}
}
The DbHelper
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_ADDRESS="address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
And the AddActivity
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
edit_address=(EditText)findViewById(R.id.address_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
address=getIntent().getExtras().getString("address");
edit_first.setText(fname);
edit_last.setText(lname);
edit_address.setText(address);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
address=edit_address.getText().toString().trim();
if(fname.length()>0 && lname.length()>0 && address.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_ADDRESS,address );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
That's all. I can't find the problem. Helps?
Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));