Listview isn't updating in Fragment - java

I know for sure that the updateFromDatabase() function works, I've used print statements to see that the entries put into mCoordinatesArray are there and not empty strings. However when I restart the app, the fragment never populates the list view with items in the database. I think it has something to do with the Fragment Lifecycle, but I have no idea.
Additionally, when I don't restart the app and run it for the first time the list view runs fine. When I rotate or restart the app, the list view no longer populates.
public class LocalFragment extends Fragment{
private ListView mLocalList;
private ArrayAdapter<String> adapter;
private ArrayList<String> mCoordinatesArray;
private BroadcastReceiver mBroadcastReceiver;
private LocationBaseHelper mDatabase;
private DateFormat dateFormat;
private String dateString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_local,container,false);
// SQLite Setup
mDatabase = new LocationBaseHelper(getActivity());
mLocalList = (ListView) v.findViewById(R.id.lv_local);
mCoordinatesArray = new ArrayList<>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
if(!mDatabase.size().equals("0")){
updateFromDatabase();
}
mLocalList.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
if(mBroadcastReceiver == null){
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss a");
dateString = dateFormat.format(new Date());
String[] data = intent.getStringExtra("coordinates").split(" ");
mDatabase.insertEntry(dateString,data[0],data[1]);
System.out.println(mDatabase.size());
mCoordinatesArray.add(dateString + " " + data[0] + " " + data[1]);
adapter.notifyDataSetChanged();
}
};
}
getActivity().registerReceiver(mBroadcastReceiver, new IntentFilter("location_update"));
}
#Override
public void onDestroy() {
super.onDestroy();
if(mBroadcastReceiver!=null){
getActivity().unregisterReceiver(mBroadcastReceiver);
}
}
// THIS METHOD CAN BE USED TO UPDATE THE ARRAY HOLDING COORDINATES FROM THE LOCAL DATABASE
private void updateFromDatabase(){
//mCoordinatesArray.clear();
mCoordinatesArray = mDatabase.getEntireDatabase();
adapter.notifyDataSetChanged();
}
}
Here's my Helper class, just in case, but I don't think the problem is here.
public class LocationBaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String D​A​T​A​B​A​S​E​_​N​A​M​E​ = "locationBase.db";
public LocationBaseHelper(Context context) {
super(context, D​A​T​A​B​A​S​E​_​N​A​M​E​, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + LocationTable.NAME + " (" +
LocationTable.Cols.DATE_TIME + " text, " +
LocationTable.Cols.LATITUDE + " text, " +
LocationTable.Cols.LONGITUDE + " text )"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertEntry(String date_time, String latitude, String longitude){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(LocationTable.Cols.DATE_TIME,date_time);
content.put(LocationTable.Cols.LATITUDE,latitude);
content.put(LocationTable.Cols.LONGITUDE,longitude);
db.insert(LocationTable.NAME,null,content);
}
public ArrayList<String> getEntireDatabase(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
ArrayList<String> values = new ArrayList<>();
do{
String value = (String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.DATE_TIME)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LATITUDE)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LONGITUDE));
values.add(0,value);
}while(cursor.moveToNext());
return values;
}
public String size(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
return cursor.getString(0);
}
}

By calling mCoordinatesArray = mDatabase.getEntireDatabase(); you are changing the reference of mCoordinatesArray, and adapter is still holding the old reference, so it does not see any changes.
Instead of creating new instance of mCoordinateArray, you should rather just update values it contains, something like:
mCoordinateArray.clear();
mCoordinateArray.addAll(mDatabase.getData());
adapter.notifyDataSetChange();
That way you are changing the data that is referenced by adapter, instead of creating completely new set of data which the adapter is not aware of.

Try to recreate your ArrayAdapter instead of using .notifyDataSetChanged():
// update Data
mCoordinatesArray = mDatabase.getEntireDatabase();
// create new adapter with new updated array
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
// set adapter for the listview
mLocalList.setAdapter(adapter);

You can put this method in your fragment and call from activity that attach to fragment.
public void updateList(List<?> result) {
if (multimediaListRent.size()>0) {
multimediaGridView.setAdapter(gridMediaListAdapter);
multimediaListRent.clear();
}
gridMediaListAdapter.notifyDataSetChanged();
}

Related

Deleting an item from a listview with SQLite

I have a problem with deleting items from my database in listview. This is my code from my helper to delete data:
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + DB_TABLE + " WHERE " + COL1 + " = '" + id +"'" + " AND "
+ COL2 + " = '" + name +"'";
db.execSQL(query);
}
It views the data with this code
private void viewData() {
Cursor cursor = bh.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Nothing to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
listItem.add(cursor.getString(1));
}
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItem);
lv.setAdapter(adapter);
}
But the problem is I have no idea how to delete it from database
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//It supposed to be deleted
}
});
Thank you in advance
In short you are presneting a list that is a single string extracted from the database.
Your delete is expecting two values. The id and the name (the listed value). Both values are not available from the single string that is listed.
If COL2 were UNIQUE (i.e. the same value would never be used) then you could easily just delete based upon this value but frequently names are not unique in which case it would be impossible to derive the id from the name. You would either have to use an ArrayList of objects (such an object containing both the id and the name) or have another array containing the id's that is in sync with the array of names.
I'd suggest using a CursorAdapter which :-
caters for Cursors and most especially provides the id as the 4th parameter to the onItemClick (for other adapters it is the same as the 3rd parameter i.e. the position).
NOTE the id column MUST be named _id.
Has all the rows in the Cursor used as the source available.
Has the Cursor appropriately positioned when onItemClick (and also onItemLongClick) is called.
Example
The following is an example based upon your code.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String DB_TABLE = "mytable";
public static final String COL1 = BaseColumns._ID; //<<<<<<<<<IMPORTANT uses the _id column
public static final String COL2 = "mynamecolumn";
public DatabaseHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_TABLE +
"(" +
COL1 + " INTEGER PRIMARY KEY," +
COL2 + " TEXT " +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insert(String name) {
ContentValues cv = new ContentValues();
cv.put(COL2,name);
return this.getWritableDatabase().insert(DB_TABLE,null,cv);
}
public int delete(long id) {
SQLiteDatabase db = this.getWritableDatabase();
// ID WILL BE UNIQUE so that's enough to IDentify a row
return db.delete(DB_TABLE,COL1 + "=?", new String[]{String.valueOf(id)});
}
public Cursor viewData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(DB_TABLE,null,null,null,null,null,null);
}
}
The above should be similar to what you have BUT note the name _id (obtained via the constant BaseColumns._ID) for COL1.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper bh;
Cursor csr;
ListView lv;
SimpleCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = this.findViewById(R.id.myListView);
bh = new DatabaseHelper(this);
addSomeDataIfNone(); //<<<<< Add some testing data
manageListView(); //<<<<< Manage the LIstView
}
private void manageListView() {
csr = bh.viewData();
if (adapter == null) {
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
csr,
new String[]{DatabaseHelper.COL2},
new int[]{android.R.id.text1},
0
);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bh.delete(id); //<<<<< uses the 4th parameter
manageListView(); //<<<<< refresh the ListView as the data has changed
}
});
} else {
adapter.swapCursor(csr);
}
}
private void addSomeDataIfNone() {
if(DatabaseUtils.queryNumEntries(bh.getWritableDatabase(),DatabaseHelper.DB_TABLE) > 0) return;
bh.insert("Name 1");
bh.insert("Name 2");
bh.insert("Name 3");
}
#Override
protected void onDestroy() {
csr.close(); // Done with the Cursor so close it
bh.close(); // Done with the Database as this is the Main Activity
super.onDestroy();
}
}
Note how this is also quite similar BUT
uses the SimpleCursorAdapter as the source for the ListView. It iself uses a Cursor as the source for the data.
does not create a new Adapter each time the data is viewed
automatically refreshes the ListView when an item is clicked and thus deleted.
uses the id to delete the clicked item as that is all that is needed to unqiuely identify a row.
Results
When first run :-
When clicking Name 2 :-

Delete Both row of list items on recyclerView and SQLite database

I am a beginner at programming, I want to make a delete button on every items list on recyclerView. I got some references from stack overflow, and its work for the deleted item only at the activity (layout), but when i run the activity again the The selected item showed again.
I found some related articles on stackoverflow and make the method to delete from the SQLite. But my app crushed "unfortunetly app has stopped" every time I call the delete function.
I hope someone can help me to figure it out.
here is my databasehelper class
public class DatabaseHelperClass extends SQLiteOpenHelper {
Log cat Database
public static String log = "DatabaseHelper";
//Databse version
public static final int DATABASE_VERSION = 1;
//Database name
public static final String DATABSE_NAME = "dbPig";
//Tables Name
public static final String TABLE_PIGINFO = "tb_pigInfo";
//Common and PigInfo Column Names
public static final String KEY_ID = "id";
public static final String KEY_NAMA = "nama";
public static final String KEY_TANGGAL_PENDAFTARAN = "tanggal_pendaftaran";
//table create statement
//table pig Info
public static final String CREATE_TABLE_PIGINFO = "CREATE TABLE "
+ TABLE_PIGINFO + "(" + KEY_ID + " INTEGER," + KEY_NAMA
+ " TEXT," + KEY_TANGGAL_PENDAFTARAN
+ " TEXT" + ")";
public DatabaseHelperClass(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//creating requaired table
db.execSQL(CREATE_TABLE_PIGINFO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PIGINFO);
// create new tables
onCreate(db);
}
public void insertdata(String nama, String tanggal_pendaftaran) {
System.out.print("Tersimpan" + TABLE_PIGINFO);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAMA, nama);
contentValues.put(KEY_TANGGAL_PENDAFTARAN, tanggal_pendaftaran);
db.insert(TABLE_PIGINFO, null, contentValues);
}
public List<PigInfoTable> getdata() {
List<PigInfoTable> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_PIGINFO + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
PigInfoTable pigInfoTable = null;
while (cursor.moveToNext()) {
pigInfoTable = new PigInfoTable();
String nama = cursor.getString(cursor.getColumnIndexOrThrow("nama"));
String tanggal_pendaftaran = cursor.getString(cursor.getColumnIndexOrThrow("tanggal_pendaftaran"));
pigInfoTable.setNama(nama);
pigInfoTable.setTanggal_pendaftaran(tanggal_pendaftaran);
stringBuffer.append(pigInfoTable);
data.add(0, pigInfoTable);
}
for (PigInfoTable mo : data) {
Log.i("Hellomo", "" + mo.getNama());
}
return data;
}
public void delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
String table = TABLE_PIGINFO;
String whereClause = KEY_ID;
String [] whereArgs = new String[] {String.valueOf(position)};
db.delete (table, whereClause, whereArgs);
}
and here my adapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
DatabaseHelperClass databaseHelper;
List <PigInfoTable> pigInfoTablesArrayList;
public RecycleAdapter(List <PigInfoTable> pigInfoTablesArrayList) {
this.pigInfoTablesArrayList = pigInfoTablesArrayList;
}
class Myholder extends RecyclerView.ViewHolder{
private TextView nama, tanggal_pendaftaran;
private Button delete;
public Myholder(View itemView) {
super(itemView);
nama = (TextView) itemView.findViewById(R.id.nama1);
tanggal_pendaftaran = (TextView) itemView.findViewById(R.id.tanggal1);
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itempigview,null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, final int position) {
PigInfoTable pigInfoTable= pigInfoTablesArrayList.get(position);
holder.nama.setText(pigInfoTable.getNama());
holder.tanggal_pendaftaran.setText(pigInfoTable.getTanggal_pendaftaran());
holder.itemView.setClickable(true);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return pigInfoTablesArrayList.size();
}
I am trying some other solution but the same error occurred which's
null object references on
Position
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
at com.example.newbreedy.RecycleAdapter$1.onClick(RecycleAdapter.java:66)
thank you
com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
because you have not initialized the reference of
DatabaseHelperClass databaseHelper;
So Add.
databaseHelper =new DatabaseHelperClass (context);
in your recycler adapter
In your code you are sending adapter position so in place of position send KEY_ID.
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyDataSetChanged();
First you have to initialize your DatabaseHelperClass in your adapter like this,
databaseHelper =new DatabaseHelperClass (context);
Than you need to call the delete function and inform the adapter about the removed item like this,
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());

SetAdapter doesn't work

I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..

Passing an object through Activities (Android)

For my software engineering class, we have to incorporate an SQLite database into our application project.
For our application this database class has to be accessible from multiple activities. I have turned the Database class into a singleton and then call
DBInterface database = Database.getInstance(this)
to set a variable to reference the database in order to access its methods in each necessary class and it works. However, we are supposed to utilize dependency injections into our code and my professor has specifically told us that it should be possible to switch from our database class to a stub database we used in a previous iteration by only changing one line of code.
Obviously this means changing the above to
DBInterface database = StubDB.getInstance(this)
However in doing this I still have to make this change in each of the activities that uses the database methods.
So my question is this: is there a way to initialize my database in our init activity and then pass a reference to each necessary activity without the assignment code above?
Relevant Code
Singleton Database Class
public class RecipeDatabase extends Activity implements DBInterface {
private dbHelper Helper;
private static RecipeDatabase sInstance;
private static Context sContext;
public static synchronized RecipeDatabase getInstance(Context context){
if(sInstance == null){
sInstance = new RecipeDatabase(context.getApplicationContext());
}
return sInstance;
}
private RecipeDatabase(Context context){
Helper = new dbHelper(context);
sContext = context;
}
#Override
public void addRecipe(Recipe recipe)
{
String ingredients = recipe.ingredientString();
String directions = recipe.directionString();
SQLiteDatabase db = Helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Recipe.KEY_rID, recipe.getrID());
values.put(Recipe.KEY_mealtype, recipe.getMealType());
values.put(Recipe.KEY_mainingredient, recipe.getMainIngredient());
values.put(Recipe.KEY_description, recipe.getDescription());
values.put(Recipe.KEY_ingredients, ingredients);
values.put(Recipe.KEY_directions, directions);
values.put(Recipe.KEY_notes, recipe.getNotes());
values.put(Recipe.KEY_rating, recipe.getRating());
values.put(Recipe.KEY_cooktime, recipe.getCooktime());
db.insert(Recipe.TABLE, null, values);
db.close();
}
#Override
public void editRecipe(Recipe recipe)
{
SQLiteDatabase db = Helper.getWritableDatabase();
ContentValues values = new ContentValues();
String ingredients = recipe.ingredientString();
String directions = recipe.directionString();
values.put(Recipe.KEY_rID, recipe.getrID());
values.put(Recipe.KEY_mealtype, recipe.getMealType());
values.put(Recipe.KEY_mainingredient, recipe.getMainIngredient());
values.put(Recipe.KEY_description, recipe.getDescription());
values.put(Recipe.KEY_ingredients, ingredients);
values.put(Recipe.KEY_directions, directions);
values.put(Recipe.KEY_notes, recipe.getNotes());
values.put(Recipe.KEY_rating, recipe.getRating());
values.put(Recipe.KEY_cooktime, recipe.getCooktime());
db.update(Recipe.TABLE, values, Recipe.KEY_rID + " = ?", new String[]{String.valueOf(recipe.getrID())});
db.close();
}
#Override
public void deleteRecipe(Recipe recipe)
{
SQLiteDatabase db = Helper.getWritableDatabase();
db.delete(Recipe.TABLE, Recipe.KEY_rID + " = ", new String[]{String.valueOf(recipe.getrID())});
db.close();
}
public ArrayList<Recipe> getList()
{
ArrayList<Recipe> result = new ArrayList<>();
SQLiteDatabase db = Helper.getReadableDatabase();
String selectQuery = "SELECT " + Recipe.KEY_rID + ", " +
Recipe.KEY_name + ", " +
Recipe.KEY_mealtype + ", " +
Recipe.KEY_mainingredient + ", " +
Recipe.KEY_description + ", " +
Recipe.KEY_ingredients + ", " +
Recipe.KEY_directions + ", " +
Recipe.KEY_notes + ", " +
Recipe.KEY_rating + ", " +
Recipe.KEY_cooktime + " FROM " + Recipe.TABLE;
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()) {
do {
ArrayList<String> ingredients = new ArrayList<>(); // Temp Storage
ArrayList<String> directions = new ArrayList<>(); // Temp Storage
String tempIngredient = cursor.getString(cursor.getColumnIndex(Recipe.KEY_ingredients));
String[] temp = tempIngredient.split("- "); //Split up ingredients to individual strings
for(int x=0; x < temp.length; x++) {
ingredients.add(temp[x]);
}
String tempDirection = cursor.getString(cursor.getColumnIndex(Recipe.KEY_ingredients));
temp = tempDirection.split("- ");//split up directions into individual strings
for(int x=0; x < temp.length; x++) {
directions.add(temp[x]);
}
//Get Values for Recipe Object
int rID = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_rID));
String name = cursor.getString(cursor.getColumnIndex(Recipe.KEY_name));
String mealType = cursor.getString(cursor.getColumnIndex(Recipe.KEY_mealtype));
String mainIngredient = cursor.getString(cursor.getColumnIndex(Recipe.KEY_mainingredient));
int rating = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_rating));
String description = cursor.getString(cursor.getColumnIndex(Recipe.KEY_description));
int cooktime = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_cooktime));
String notes = cursor.getString(cursor.getColumnIndex(Recipe.KEY_notes));
//Create new Recipe from Row
Recipe tempRecipe = new Recipe(rID, name, description, mealType, mainIngredient,
rating, cooktime, notes, ingredients, directions);
//Add the recipe to the ArrayList
result.add(tempRecipe);
}while (cursor.moveToNext());
}
//Return the populated ArrayList for use
return result;
}
}
Init Class
public class init extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
//The code to change to switch from stub to database
DBInterface repository = RecipeDatabase.getInstance(this);
//DBInterface repository = new StubDB(this);
ArrayList<Recipe> recipes = repository.getList();
ArrayList<String> recipeDisplay = new ArrayList<>();
for(int i=0; i<recipes.size(); i++) {
recipeDisplay.add(recipes.get(i).getName());
}
ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, recipeDisplay);
ListView lv = this.getListView();
lv.setAdapter(myArrayAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int pos, long id){
super.onListItemClick(l, v, pos, id);
Intent myIntent = new Intent(this, Details.class);
myIntent.putExtra("recipePosition", pos);
startActivity(myIntent);
}
public void shoppingListButton(View view){
startActivity(new Intent(this, ShoppingList.class));
}
public void addRecipeButton(View view){
Intent myIntent = new Intent(this, Edit.class);
myIntent.putExtra("editType", 1); // 1 corresponds to add recipe
startActivity(myIntent);
}
}
One of the Activity Classes that needs the DB methods
public class Details extends ListActivity {
int recipePosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
//want to avoid this call
DBInterface repository = RecipeDatabase.getInstance(this);
recipePosition = getIntent().getIntExtra("recipePosition", 0);
Recipe clickedRecipe = repository.getList().get(recipePosition);
ArrayList<String> recipeDetails = new ArrayList<>();
recipeDetails.add(clickedRecipe.getName());
recipeDetails.add(clickedRecipe.getDescription());
recipeDetails.add("Ingredients:");
for(int i=0; i<clickedRecipe.getIngredients().size(); i++){
recipeDetails.add(clickedRecipe.getIngredients().get(i));
}
recipeDetails.add("Instructions:");
for(int i=0; i<clickedRecipe.getDirections().size(); i++){
recipeDetails.add(clickedRecipe.getDirections().get(i));
}
ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, recipeDetails);
ListView lv = this.getListView();
lv.setAdapter(myArrayAdapter);
}
public void editButton(View view){
Intent myIntent = new Intent(this, Edit.class);
myIntent.putExtra("recipePosition", recipePosition);
myIntent.putExtra("editType", 2); // 2 corresponds to modify recipe
startActivity(myIntent);
}
}
Database Helper Class
public class dbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ROSE.db";
public dbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//Creates the Recipe Table which stores recipes
String CREATE_TABLE_RECIPES = "CREATE TABLE " + Recipe.TABLE +
"(" + Recipe.KEY_rID + " INTEGER PRIMARY KEY, " +
Recipe.KEY_name + " TEXT, " +
Recipe.KEY_mealtype + " TEXT, " +
Recipe.KEY_mainingredient + " TEXT, " +
Recipe.KEY_description + " TEXT, " +
Recipe.KEY_ingredients + " TEXT, " +
Recipe.KEY_directions + " TEXT, " +
Recipe.KEY_notes + " TEXT, " +
Recipe.KEY_rating + " INTEGER, " +
Recipe.KEY_cooktime + " INTEGER )";
db.execSQL(CREATE_TABLE_RECIPES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS recipes" );
onCreate(db);
}
}
Dagger2 is the perfect thing for you. It's really easy to use, just follow the instructions they provide in the docs and you'll love it once you figure it out.
Basically you're going to use
#Inject
DBInterface database;
In every activity, fragment, service, or anywhere you wanna use the database.
Then you will create a DatabaseModule which will have a method that provides the database for injection.
#Singleton
#Provides static DBInterface provideDatabase() {
return new WhateverDatabaseImplementsDBInterface();
}
As you can see, just adding #Singleton will make it a singleton. And now changing the database you use is truly a one line change.
Dagger2 is the greatest thing you will encounter for dependency injection for sure, just setup it correctly, write if you have any trouble (but you shouldn't, with their thorough instructions).
You can use the SQLiteOpenHelper. It will make sure all your activities access the same database. Even if you have different database helper objects in each Activity, they all access the same database.

Start Activity By Listactivity

I'm trying to start a activity everytime an item is clicked on a ListView
i'm using database in my project and using global varaibles in my project
but not able to start GalleryFileActivity activity in project
If you need to know to each of the sections will also provide
Thank you for your continued efforts to advance the perfection
public class DataListView extends ListActivity {
final private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String Path;
final private ArrayList<String> pikh = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final global folder = ((global)getApplicationContext());
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("data is");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
}
public void onListItemClick(
ListView parent, View v, int position,long id, global folder)
{
String pos=results.get(position-1);
super.onListItemClick(parent, v, position, id);
Toast.makeText(this,
"You have selected " + results.get(position-1) ,
Toast.LENGTH_SHORT).show();
folder.setsubfolder (pos);
**startActivity(new Intent(this,GalleryFileActivity.class));**
}
public void onClick(View view) {
ListView lstView = getListView();
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Path, Header FROM resource1 "
, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
Path = c.getString(c.getColumnIndex("Path"));
String Header = c.getString(c.getColumnIndex("Header"));
results.add( Path + " " + Header);
}while (c.moveToNext()) ;
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
The code looks about right.
Sounds like you may not have GalleryFileActivity declared in your manifest.
Check your logcat output - there's probably an exception in there that mentions this.

Categories

Resources