onItemClick in list doesnot open selected item in viewpager - android

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
}
}
}

Related

Delete ListiView and SQLite row in Android

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());

ListView onItemLongClick view isSelected always returns False

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

By long clicking on listview delete its contents from SQLite and listview that is clicked

Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.

SearchView in CustomAdapter

I want to implement an SearchView , inside my Listview , which items are getting from database ... I don't know if I have to use an EditText to make the search , or SearchView. If I write some letter , in my listView will be shown only thouse items wich are starting with thouse letters.
MainActivity :
public class MyActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
Toolbar toolbar;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
private CustomCursorAdapter customAdapter;
private PersonDataBaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
View LiniarLayout;
private static final String TAG = MyActivity.class.getSimpleName();
TextView myalbums ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate.setContentView(R.layout.main);
LiniarLayout = (View)findViewById(R.id.LiniarLayout);
//add the Toolbar
Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
myalbums = (TextView) findViewById(R.id.myalbums);
delegate.setSupportActionBar(toolbar);
delegate.setTitle("Photo Album");
toolbar.getBackground().setAlpha(250);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this , drawerLayout,R.string.drawer_open,R.string.drawer_close);
drawerLayout.setDrawerListener(mDrawerToggle);
databaseHelper = new PersonDataBaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
// Database query can be a time consuming task ..
// so its safe to call database query in another thread
// Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "cliker on item" + position);
drawerLayout.closeDrawer(LiniarLayout);
TextView name1 = (TextView) parent.getChildAt(position- listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
String name = name1.getText().toString();
Toast.makeText(MyActivity.this, "You selected ''"+name+" ''",Toast.LENGTH_SHORT).show();
String name2 = "/"+name+"/";
String numeAplicatie = "/PhotoAlbum/";
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+numeAplicatie +name2);
if(!dir.exists()) {
dir.mkdirs();
}
Intent myIntent = new Intent(MyActivity.this, AlbumActivity.class);
myIntent.putExtra("nameAlbum",name2);
myIntent.putExtra("nameAlbum2",name);
startActivity(myIntent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, final long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
TextView name1 = (TextView) parent.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
final String name = name1.getText().toString();
Toast.makeText(MyActivity.this ,"You selected"+" ''"+name+"''", LENGTH_SHORT).show();
builder.setCancelable(false);
builder.setMessage("Are you sure you want to delete ''" + name + "'' ?");
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteSingleRow(id);
customAdapter.changeCursor(databaseHelper.getAllData());
dialog.dismiss();
Toast.makeText(MyActivity.this ,"''" +name+"''"+" deleted",Toast.LENGTH_SHORT).show();
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+"/"+name+"/" );
deleteDir(dir);
}
});
builder.setTitle("Delete Album");
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
Field mDragger = null;//mRightDragger for right obviously
try {
mDragger = drawerLayout.getClass().getDeclaredField(
"mLeftDragger");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
mDragger.setAccessible(true);
ViewDragHelper draggerObj = null;
try {
draggerObj = (ViewDragHelper) mDragger.get(drawerLayout);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Field mEdgeSize = null;
try {
mEdgeSize = draggerObj.getClass().getDeclaredField("mEdgeSize");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
mEdgeSize.setAccessible(true);
int edge = 0;
try {
edge = mEdgeSize.getInt(draggerObj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
mEdgeSize.setInt(draggerObj, edge * 10);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
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();
switch (item.getItemId()){
case R.id.action_setting:
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
//noinspection SimplifiableIfStatement
if(id==android.R.id.home){
if(drawerLayout.isDrawerOpen(LiniarLayout)){
drawerLayout.closeDrawer(LiniarLayout);
}else{drawerLayout.openDrawer(LiniarLayout);
if(databaseHelper.getAllData()==null){
myalbums.setText("Create Album");
}
}
}
return super.onOptionsItemSelected(item);
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
#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"));
customAdapter.changeCursor(databaseHelper.getAllData());
drawerLayout.openDrawer(LiniarLayout);
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
}
Cursor 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))));
}
}
And my DataBaseHelper :
public class PersonDataBaseHelper {
private static final String TAG = PersonDataBaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
private static final String TABLE_NAME = "person_table"; // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String KEY_IMG = "image";
private DatabaseOpenHelper openHelper;
private 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) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
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);
}
public boolean deleteSingleRow(long rowId)
{
return database.delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + rowId, null) > 0;
}
// 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 )";
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
}
}
}

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

Categories

Resources