SQLite Update not working in android - java

I've been trying to update my data in sqlite android, but it doesn't work. Also, there is also no error message shown in the logcat.
Here are my codes:
Dbadapter.java:
public boolean updateEntry(SalesItemInformationLV testing)
{
ContentValues values = new ContentValues();
try {
values.put(ENTRY_NAME, testing.getItemname());
values.put(ENTRY_TEL, testing.getCostprice());
values.put(ENTRY_SELLINGPRICE, testing.getSellingprice());
values.put(ENTRY_QTYSOLD, testing.getItemquantity());
values.put(ENTRY_DATESOLD, testing.getDatesold());
values.put(ENTRY_STAFFDISCOUNT, testing.getStaffdiscount());
}
catch (SQLiteException e)
{
Log.w(MYDBADAPTER_LOG_CAT, "Update failed!" + e.toString());
}
// updating row
int returnvalue = _db.update(DATABASE_TABLE, values, KEY_ID + " = ?", new String[] { String.valueOf(testing.getId()) });
return returnvalue==1 ? true : false;
}
MyItems.java:
public boolean updateDatabase(SalesItemInformationLV testing2, Context c)
{
MyDbAdapter db = new MyDbAdapter(c);
db.open();
boolean rowIDofUpdatedEntry = db.updateEntry(testing2);
db.close();
return rowIDofUpdatedEntry;
}
ListView.java, which passes saleitem2 object intent to Edit.java:
MyItems mi2;
private ArrayList<SalesItemInformationLV> displayiteminfo2;
mi2 = MyItems.getInstance();
displayiteminfo2 = mi2.retrieveAllForlist2(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SalesItemInformationLV saleitem2 = displayiteminfo2.get(position);
String namevalue = saleitem2.getItemname();
Intent myintent = new Intent(ListSaleItemActivity.this, EditSaleActivity.class);
myintent.putExtra("array", saleitem2);
startActivity(myintent);
Edit.java which will use the update method from Items.java:
Bundle extras = this.getIntent().getExtras();
final SalesItemInformationLV sale1 = (SalesItemInformationLV)extras.getSerializable("array");
final int id1 = extras.getInt("itemID");
btnSaveChanges.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mc.updateDatabase(sale1, getApplicationContext());
}}
I have been trying to figure out, and I think there could be something wrong in my Dbadapter.java, but i am not sure. Please advise me on how to solve this thanks!

Related

How to create delete method in SQLite for deleting single item not the whole checklist?

I'll post only relevant code.
This is Activity which adds checklist to database.
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
ArrayList<String> itemList;
ArrayList<String> stateList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView() {
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.requestFocus();
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view) {
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
} else
checklistHelper.setStatus("0");
itemList.add(etChecklistItem.getText().toString());
stateList.add(checklistHelper.getStatus());
}
StringBuilder stringBuilder = new StringBuilder();
for (String items : itemList) {
stringBuilder.append(items);
stringBuilder.append("\n");
}
StringBuilder stringBuilder1 = new StringBuilder();
for (String state : stateList) {
stringBuilder1.append(state);
stringBuilder1.append("\n");
}
String items = stringBuilder.toString();
String state = stringBuilder1.toString();
dbHelper.insertChecklist(state, items, DateTime.date(), DateTime.time(), System.currentTimeMillis());
finish();
break;
}
return true;
}
}
This is insert checklist method in SQLiteHelper class.
public boolean insertChecklist(String status, String content, String date, String time, long now){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(CHECKLIST_STATUS, status);
c.put(CHECKLIST_CONTENT, content);
c.put(CHECKLIST_DATE, date);
c.put(CHECKLIST_TIME, time);
c.put(CHECKLIST_NOW, now);
long id = sqLiteDatabase.insert(CHECKLIST_TABLE, null, c);
Log.d("check", "checklist inserted -> ID = " + id);
return true;
}
This is the delete method for deleting the whole checklist, not for individual items.
public void deleteChecklist(long id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CHECKLIST_TABLE, CHECKLIST_ID + " =? ", new String[] {String.valueOf(id)});
}
Here I want a method like above, but only for deleting selected item, like this image.. Look at this image.
look this image

how to get the items name from listview after using intent with sqlite?

i have two listviews each one of them is in different activity i want to send an item from the first listview to the other one by long click on it im using intent, im using string file to get the data it sends the item perfectly but its not saved to sqlite i dont know where is the problem please take a look at my code
First Activity(Main Activity):
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l);// THIS ADDED
startActivity(intent);
fav_name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, fav_name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
Second Activity(cc):
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
manageFavouritesListView();
if (fav_id==0){
}
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (getDataInCurrentLocaleById.moveToFirst()) {
fav_name = getDataInCurrentLocaleById.getString(getDataInCurrentLocaleById.getColumnIndex(FAVOURITES_COL_NAME));
}
getDataInCurrentLocaleById.close();
}
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}
Db_Sqlite:
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
public String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
i dont where is the problem please help me thank you in advance
You should notify the adapter that data changed.
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
favourites_adapter.notifyDataSetChanged();
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Error in getting value from textviews in getIntent.getParcelableExtra

I was working with android project these days, and It will finish soon, but I got stuck in my project. First, I want to create search activity which will be used for searching movies. The searching activity runs well, but whenever it comes to adding the selected movie, it shown me the error code below:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.idstream.pojo.Movies.setTitle(java.lang.String)' on a null object reference
at com.example.idstream.search.MoviesDetailActivity.addFavorite(MoviesDetailActivity.java:96)
at com.example.idstream.search.MoviesDetailActivity.access$100(MoviesDetailActivity.java:19)
at com.example.idstream.search.MoviesDetailActivity$1.onClick(MoviesDetailActivity.java:78)
This code has an error in this area:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
I've tried to add the selected movie to database in other activity, but it didn't mention any error. But when I tried to save the selected movie to database, it turns out an error. I also tried to send it to a toast, which I wanna make sure whether the value that I sent was successfully retrieved. The toast is successfully get the data.
Here is my SearchFragment.java:
public class SearchMovieFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
ListView lvMovieItems;
EditText txtTitleMovieInput;
ImageView imgMoviesSearch;
Button btnSearchMovie;
AdaptersMovie adaptersMovie;
MovieHelper movieHelper;
Boolean act = true;
Boolean insert = true;
Boolean delete = true;
private View mView;
public SearchMovieFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_search_movie, container, false);
txtTitleMovieInput = (EditText)mView.findViewById(R.id.txtMovieTitle);
String mTitles = txtTitleMovieInput.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitles);
imgMoviesSearch = (ImageView)mView.findViewById(R.id.imgMovies);
btnSearchMovie = (Button) mView.findViewById(R.id.btn_search);
btnSearchMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTitleMovie = txtTitleMovieInput.getText().toString();
if(TextUtils.isEmpty(mTitleMovie)){
return;
}
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitleMovie);
getLoaderManager().restartLoader(0, bundle, SearchMovieFragment.this);
}
});
getLoaderManager().initLoader(0, bundle, SearchMovieFragment.this);
adaptersMovie = new AdaptersMovie(getActivity());
adaptersMovie.notifyDataSetChanged();
lvMovieItems = (ListView)mView.findViewById(R.id.listMovies);
lvMovieItems.setAdapter(adaptersMovie);
lvMovieItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movies item = (Movies)parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), MoviesDetailActivity.class);
intent.putExtra(MoviesDetailActivity.EXTRA_MOVIE, item.getTitle());
intent.putExtra(MoviesDetailActivity.EXTRA_RELEASE, item.getRelease_info());
intent.putExtra(MoviesDetailActivity.EXTRA_LANGUAGE, item.getLanguage());
intent.putExtra(MoviesDetailActivity.EXTRA_OVERVIEW, item.getDescription());
intent.putExtra(MoviesDetailActivity.EXTRA_PHOTOS, item.getPhotos());
startActivity(intent);
}
});
return mView;
}
#NonNull
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, #Nullable Bundle args) {
String temp = "";
if (args != null){
temp = args.getString(EXTRA_MOVIE);
}
return new MovieAsyncTaskLoader(getActivity(), temp);
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
adaptersMovie.setData(data);
}
#Override
public void onLoaderReset(#NonNull Loader<ArrayList<Movies>> loader) {
adaptersMovie.setData(null);
}
}
My MoviesDetailActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies_detail);
setTitle("Movie's Details");
tvTitles = findViewById(R.id.movieTitles);
tvReleased = findViewById(R.id.movieRelease);
tvLanguages = findViewById(R.id.movieLanguages);
tvDescription = findViewById(R.id.movieDescriptions);
imageMovies = findViewById(R.id.moviesImage);
progressBar = findViewById(R.id.progressMovie);
fav_moviesBtn = findViewById(R.id.fab_movie);
progressBar.setVisibility(View.VISIBLE);
String mvTitles = getIntent().getStringExtra(EXTRA_MOVIE);
String mvLanguages = getIntent().getStringExtra(EXTRA_LANGUAGE);
String mvOverview = getIntent().getStringExtra(EXTRA_OVERVIEW);
String mvRelease = getIntent().getStringExtra(EXTRA_RELEASE);
String mvPhotos = getIntent().getStringExtra(EXTRA_PHOTOS);
tvTitles.setText(mvTitles);
tvReleased.setText(mvRelease);
tvLanguages.setText(mvLanguages);
tvDescription.setText(mvOverview);
Glide.with(MoviesDetailActivity.this)
.load("https://image.tmdb.org/t/p/w185" + mvPhotos)
.placeholder(R.color.colorFreshOrange)
.dontAnimate()
.into(imageMovies);
movieHelper = new MovieHelper(MoviesDetailActivity.this);
movieHelper.open();
mMoviess = getIntent().getIntExtra(FAVOURITE,0);
fav_moviesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isAdd) {
addFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Ditambahkan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_yes_24_foreground);
} else {
removeFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Dihapuskan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_no_24_foreground);
}
}
});
progressBar.setVisibility(View.GONE);
}
private void addFavorite() {
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.insertMovie(movies);
}
private void removeFavorite() {
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.deleteMovie(getIntent().getStringExtra(EXTRA_MOVIE));
}
}
And this one is my MovieHelper.java:
public Boolean getOne(String name){
String querySingleRecord = "SELECT * FROM " + DATABASE_TABLE + " WHERE " +DatabaseContract.MovieColoumn.TITLE+ " " + " LIKE " +"'"+name+"'" ;
Cursor cursor = database.rawQuery(querySingleRecord,null);
cursor.moveToFirst();
Log.d("cursor", String.valueOf(cursor.getCount()));
if (cursor.getCount() > 0 ){
return true;
}else if(cursor.getCount() == 0){
return false;
}
return false;
}
public long insertMovie(Movies mMovies){
ContentValues args = new ContentValues();
args.put(IDS,mMovies.getId());
args.put(DatabaseContract.MovieColoumn.TITLE,mMovies.getTitle());
args.put(DatabaseContract.MovieColoumn.RELEASE_INFO,mMovies.getRelease_info());
args.put(DatabaseContract.MovieColoumn.LANGUAGE,mMovies.getLanguage());
args.put(DatabaseContract.MovieColoumn.DESCRIPTION,mMovies.getDescription());
args.put(DatabaseContract.MovieColoumn.PHOTOS,mMovies.getPhotos());
return database.insert(DATABASE_TABLE,null,args);
}
I believe the problem is here:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Notice that you're using the same EXTRA_TITLE for both.
I think that what's happening is that getParcelableExtra() is returning null, because the implementation of Bundle (the extras) will catch the ClassCastException:
// ...
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
And then you get a NullPointerException when you try to call setTitle().
Instead, create a new Movies instance yourself:
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Alternatively, you could implement the Parcelable interface in your Movies class, and then you wouldn't have to bother adding all of its fields one by one.

How to delete ListViews items by their ID in sqlite database

I followed the tutorial here : Tutorial todo APP and I would like to customize the code nad build training app. My first change is to delete things by their ID in database ( in the example they are being deleted by names ). Here is my current code responsible for deleting items:
// FUNCTION for DELETING EXERCISE
public void deleteExercise(View view) {
final View parent = (View) view.getParent();
AlertDialog dialog = new AlertDialog.Builder(this)
.setMessage("Are you sure, you want to delete exercise?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView exerciseTextView = (TextView) parent.findViewById(R.id.exercise_name);
String exercise = String.valueOf(exerciseTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(ExerciseContract.ExerciseEntry.TABLE,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME + " = ?",
new String[]{exercise});
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
// UPDATING USER INTERFACE AFTER CHANGES IN DB
private void updateUI() {
ArrayList<String> exerciseList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] projection = {
ExerciseContract.ExerciseEntry._ID,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME,
//ExerciseContract.ExerciseEntry.COL_EXERCISE_DESCRIPTION
};
Cursor cursor = db.query(
ExerciseContract.ExerciseEntry.TABLE, //tablica do zapytań
projection, //zwracane kolumny
null, //columny dla WHERE
null, //wartosci dla WHERE
null,//nie grupuj wierszy
null,//nie filtruj grup
null); //porządek sortowania
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME);
exerciseList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.item_workout,
R.id.exercise_name,
exerciseList);
mWorkoutListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(exerciseList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
What would be the simplest way to do that?
You're not returning the id anywhere, I'd personally recommend a custom adapter. But for a quick way i think the easiest thing to do is delete it when the users click an item in the list view.
Set the lists views onItemClickListener.
mTaskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tasks task =(Tasks) mTaskListView.getItemAtPosition(position);
deleteTask(task.getId());
}
});
For the delete tasks pass in the _id of the clicked item.
public void deleteTask(long id) {
//TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
//String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry._ID + " = ?", new String[]{String.valueOf(id)});
db.close();
updateUI();
}
In the UpdateUI section change this while loop to also retrieve _id.
while (cursor.moveToNext()) {
int title = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
int _id = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
Tasks tasks = new Tasks();
tasks.setId(cursor.getInt(_id));
tasks.setTitle(cursor.getString(title));
taskList.add(tasks);
}
Lastly create a model for your tasks.
package com.aziflaj.todolist.db;
public class Tasks {
String title;
int id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString()
{
return getTitle();
}
}
Also remember to remove the button from the LayoutFile. You could show a dialog before deleting, but this was a quick solution. Ideally i'd recommended creating your own custom adapter. You'll probably have to do that if you wish to keep the button in and delete it that way.
Custom Adapter for List View
Create on common method inside your database helper class.
public boolean deleteRowData(String tableName, String selection, String[] selectionArgs) {
open();
sqLiteDb.delete(tableName, selection, selectionArgs);
close();
return true;
}
// ---opens the database---
public NotesData open() throws SQLException {
DatabaseHelper dbHelper = new DatabaseHelper(context);
sqLiteDb = dbHelper.getWritableDatabase();
sqLiteDb = dbHelper.getReadableDatabase();
if (!sqLiteDb.isReadOnly()) {
// Enable foreign key constraints
sqLiteDb.execSQL("PRAGMA foreign_keys = ON;");
}
return this;
}
// ---closes the database---
public void close() {
if (sqLiteDb != null && sqLiteDb.isOpen()) {
sqLiteDb.close();
}
}
Now onClick of listView Item do this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteAlertDialog(position); // Common method for delete alert dialog
}
});
private void showDeleteAlertDialog(int arrayPosition) {
//delete data from
String title = getResources().getString(R.string.warning);
String message = getResources().getString(R.string.warning_for_delete);
final android.app.Dialog dialog = new Dialog(YourActivity.this, R.style.DialogTheme); //this is a reference to the style above
dialog.setContentView(R.layout.custom_dialog); //I saved the xml file above as custom_dialog.xml
dialog.setCancelable(true);
//to set the message
TextView sub_message = (TextView) dialog.findViewById(R.id.tv_Message);
TextView dialogTitle = (TextView) dialog.findViewById(R.id.tv_Title);
Button btn_Negative = (Button) dialog.findViewById(R.id.btn_Negative);
Button btn_Positive = (Button) dialog.findViewById(R.id.btn_Positive);
btn_Negative.setText("Cancel");
btn_Positive.setText("Delete");
sub_message.setText("Are you sure you want to delete this>");
dialogTitle.setText(title);
//add some action to the buttons
btn_Positive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String selection = YourColumnName + " LIKE ?";
final String[] selectionArgs = {myArrayList.get(arrayPosition).getID()};
mHelper.deleteRowData(YourTableNAME, selection, selectionArgs);
// Now just remove that array position from your arraylist (from activity & adapter arralist too).
myArrayList.remove(arrayPosition);
yourAdapter.yourArrayList.remove(arrayPosition);
notifyDataSetChanged();
}
});
btn_Negative.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}

Categories

Resources