How to cast the value of SQLiteDatabase.execSQL to a String? - java

I'm developing a small android notes app using java. Everything seems to be working fine except that I'm getting an error while trying to cast the instance SQLiteDatabase.execSql obj to a String. The purpose of doing this is that, it will allow user to update their data. In the custom adapter class (obBind method) I've set a tag, which means I've the id of each itemView even in my MainActivity. What I want it to do is when a user left swipes a particular item then his/her data should be set (editText.setText) in the edittext and if he/she clicks on the add button, the data should be updated.
Please refer to the codes for better understand-ability
CustomAdapter Class:
package com.example.myapplication20;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
Context mContext;
Cursor mCursor;
CustomAdapter (Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
}
#NonNull
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.single_item_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) {
if (!mCursor.moveToPosition(position)) {
return;
}
String value = mCursor.getString(mCursor.getColumnIndex(TableDetailsClass.Collection.TABLE_COLUMN));
Long id = mCursor.getLong(mCursor.getColumnIndex(TableDetailsClass.Collection._ID));
holder.mTextView.setText(value);
holder.itemView.setTag(id);
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
TextView uTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.textView);
uTextView = itemView.findViewById(R.id.updateTextView);
}
}
public void swapCursor (Cursor newCursor) {
if (mCursor != null) {
mCursor.close();
}
mCursor = newCursor;
if (newCursor != null) {
notifyDataSetChanged();
}
}
}
MainActivity Class:
package com.example.myapplication20;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.CollapsibleActionView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private Button addButton;
private RecyclerView mRecyclerView;
private SQLiteDatabase mDataBase;
MyOpenHelperClass myOpenHelperClass;
CustomAdapter mCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOpenHelperClass = new MyOpenHelperClass(this);
mDataBase = myOpenHelperClass.getWritableDatabase();
mEditText = findViewById(R.id.editText);
addButton = findViewById(R.id.button);
mCustomAdapter = new CustomAdapter(this, getAllItems());
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mCustomAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItems();
}
});
// Swipe delete
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
removeItem( (Long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(mRecyclerView);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
updateItem( (Long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(mRecyclerView);
}
private void addItems () {
if (mEditText.getText().toString().trim().length() == 0) {
return;
}
String textToBeAdded = mEditText.getText().toString();
ContentValues cv = new ContentValues();
cv.put(TableDetailsClass.Collection.TABLE_COLUMN, textToBeAdded);
mDataBase.insert(TableDetailsClass.Collection.TABLE_NAME, null, cv);
mCustomAdapter.swapCursor(getAllItems());
mEditText.getText().clear();
}
public Cursor getAllItems () {
return mDataBase.query(TableDetailsClass.Collection.TABLE_NAME,
null,
null,
null,
null,
null,
TableDetailsClass.Collection.TIMESTAMP + " DESC"
);
}
public void removeItem (Long id) {
mDataBase.delete(TableDetailsClass.Collection.TABLE_NAME,
TableDetailsClass.Collection._ID + "=" + id, null);
mCustomAdapter.swapCursor(getAllItems());
Toast.makeText(this, "Item deleted!", Toast.LENGTH_SHORT).show();
}
public void updateItem (long id) {
String val = mDataBase.execSQL("SELECT * FROM " + TableDetailsClass.Collection.TABLE_NAME + " WHERE " +
TableDetailsClass.Collection._ID + "=" + id);
mEditText.setText(val); // The line I'm getting the error in. Says cannot cast void to string.
ContentValues cv = new ContentValues();
cv.put(TableDetailsClass.Collection.TABLE_COLUMN, mEditText.getText().toString());
mDataBase.update(TableDetailsClass.Collection.TABLE_NAME, cv,
TableDetailsClass.Collection._ID + "=" + id, null);
mCustomAdapter.swapCursor(getAllItems());
}
}
SQLiteOpenHelper Class:
package com.example.myapplication20;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class MyOpenHelperClass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myapp.db";
public static final int DATABASE_VERSION = 1;
public MyOpenHelperClass(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_QUERY = "CREATE TABLE " +
TableDetailsClass.Collection.TABLE_NAME + "(" +
TableDetailsClass.Collection._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TableDetailsClass.Collection.TABLE_COLUMN + " TEXT NOT NULL, " +
TableDetailsClass.Collection.TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" + ");";
db.execSQL(SQL_CREATE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TableDetailsClass.Collection.TABLE_NAME);
onCreate(db);
}
}
Any kind of help will be really appreciated.

public void updateItem (long id) {
Cursor cursor = mDataBase.rawQuery("SELECT * FROM " + TableDetailsClass.Collection.TABLE_NAME + " WHERE " +
TableDetailsClass.Collection._ID + "= ?", new String[]{String.valueOf(id)});
if (cursor != null && cursor.moveToFirst()) {
String val = cursor.getString(cursor.getColumnIndex(TableDetailsClass.Collection.TABLE_COLUMN));
mEditText.setText(val);
cursor.close();
}
...
}

Related

Java: How to update the Recycler View every time I delete an item?

I seem to be stuck with this problem where I want to update the Recycler View in real-time. Meaning I want the recycler view to update its list when a user swipes to delete a row.
As you can see in the code below I have tried to use NotifyDataSetChange() in the DatabaseAdapter java class but I only get the error "RecyclerViewAdapter.notifyDataSetChanged() on a null object reference".
I have both googled the error above and how to update Recycle view in real-time but none of the solutions I found worked. Please help me because I am losing it with this problem.
NamesAdapter.Java
package com.example.myapplication.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.DatabaseAdapter;
import com.example.myapplication.R;
import org.w3c.dom.NameList;
import java.util.ArrayList;
import java.util.List;
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
Context context;
List<Names> namesList;
RecyclerView rvPrograms;
final View.OnClickListener onClickListener = new MyOnClickListner();
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView rowID;
TextView rowName;
TextView rowAmount;
TextView rowDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Store the item sub-views in member variables
rowID = itemView.findViewById(R.id.idTextView);
rowName = itemView.findViewById(R.id.nameTextView);
rowAmount = itemView.findViewById(R.id.amountEditText);
rowDate = itemView.findViewById(R.id.dateTextView);
}
}
public NamesAdapter(Context context, List<Names> namesList, RecyclerView rvPrograms){
this.context = context;
this.namesList= namesList;
this.rvPrograms = rvPrograms;
}
#NonNull
#Override
public NamesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.recycler_list, viewGroup, false);
view.setOnClickListener(onClickListener);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NamesAdapter.ViewHolder holder, int i) {
Names name = namesList.get(i);
holder.rowID.setText(""+name.getId());
holder.rowName.setText(name.getName());
holder.rowAmount.setText(name.getAmount());
holder.rowDate.setText(name.getDate());
holder.itemView.setTag(name.getId());
}
#Override
public int getItemCount() {
return namesList.size();
}
private class MyOnClickListner implements View.OnClickListener {
#Override
public void onClick(View v) {
int itemPosition = rvPrograms.getChildLayoutPosition(v);
String item = namesList.get(itemPosition).getName();
Toast.makeText(context, item, Toast.LENGTH_SHORT).show();
}
}
}
DatabaseAdapter.Java
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
List<Names> namesList = new ArrayList<>();
NamesAdapter na;
public DatabaseAdapter(Context context) {
helper = new DatabaseHelper(context);
db = helper.getWritableDatabase();
}
public int deleteData(String name){
String whereArgs[] = {name};
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_Name+ "=?", whereArgs);
return count;
}
public int removeItem (long id){
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_ID+ "="+ id, null);
//na.notifyDataSetChanged();
return count;
}
public int updateAmount(String name, String amount){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Amount, amount);
String whereArgs[] = {name};
int count = db.update(DatabaseHelper.Table_Name, contentValues, DatabaseHelper.Key_Name + "=?", whereArgs);
return count;
}
public String searchData(String sname){
String columns[] = {DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
String selectionArgs[] = {sname};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, DatabaseHelper.Key_Name + "=?", selectionArgs, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
String name = cursor.getString(index1);
String amount = cursor.getString(index2);
buffer.append(name + " " + amount + "\n");
}
return buffer.toString();
}
// This is for the Toast dispaly
public String getAllData(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, null, null );
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
int amount = cursor.getInt(index3);
buffer.append(rowid + " " + name + " " + amount + "\n");
}
return buffer.toString();
}
public List<Names> getAllNames(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount, DatabaseHelper.Key_Date};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, DatabaseHelper.Key_ID+" DESC",null );
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
Double amount = cursor.getDouble(index3);
int index4 = cursor.getColumnIndex(DatabaseHelper.Key_Date);
String date = cursor.getString(index4);
Names names = new Names(rowid, name, amount, date);
namesList.add(names);
}
return namesList;
}
public long insertData (String name, Double amount, String date){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Name, name);
contentValues.put(DatabaseHelper.Key_Amount, amount);
contentValues.put(DatabaseHelper.Key_Date, date);
long id = db.insert(DatabaseHelper.Table_Name, null ,contentValues);
return id;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String Database_Name = "Demoze.db";
private static final String Table_Name = "salary";
private static final int Database_Version= 10;
private static final String Key_ID = "_id";
private static final String Key_Name = "name";
private static final String Key_Amount = "amount";
private static final String Key_Date = "date";
private static final String Create_table = "create table "+Table_Name+
" ("+Key_ID+" integer primary key autoincrement, "+Key_Name+
" text, "+Key_Amount+ " real, "+Key_Date+" text)";
private static final String Table_Drop = "drop table if exists "+Table_Name;
private Context context;
public DatabaseHelper(#Nullable Context context) {
super(context, Database_Name, null, Database_Version);
this.context = context;
Toast.makeText(context, "Constructor Called", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Create_table);
Toast.makeText(context, "OnCreate Called", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Toast.makeText(context, "OnUpgrade Called", Toast.LENGTH_SHORT).show();
db.execSQL(Table_Drop);
onCreate(db);
} catch (SQLException e) {
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
}
SpendingActivity.Java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class SpendingActivity extends AppCompatActivity {
DatabaseAdapter databaseAdapter;
EditText crud;
RecyclerView rvPrograms;
NamesAdapter namesAdapter;
RecyclerView.LayoutManager layoutManager;
List<Names> namesList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spending_list);
databaseAdapter = new DatabaseAdapter(this);
namesList = databaseAdapter.getAllNames();
rvPrograms = findViewById(R.id.rvDBdata);
rvPrograms.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvPrograms.setLayoutManager(layoutManager);
namesAdapter = new NamesAdapter(this, namesList, rvPrograms);
rvPrograms.setAdapter(namesAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(rvPrograms);
crud = findViewById(R.id.crudEditText);
String data = databaseAdapter.getAllData();
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
public void Home (View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void Search (View view){
String name = crud.getText().toString().trim();
String result = databaseAdapter.searchData(name);
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
public void Update (View view) {
String amount = crud.getText().toString().trim();
databaseAdapter.updateAmount("taxi", amount);
}
public void Delete (View view) {
String name = crud.getText().toString().trim();
databaseAdapter.deleteData(name);
}
}
In your NamesAdapter you could expose a method called deleteItem:
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
...
public void deleteItem(int position){
namesList.remove(position);
notifyItemRemoved(position);
}
}
Inside of onSwiped() method, you need to call NameAdapter' deleteItem method:
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
namesAdapter.deleteItem(position);
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
Recycleview adapterclass
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
ArrayList<String> animalNames
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
animalNames.remove(position);
adapter.notifyItemRemoved(position);
}
}

Access a function from another class

i have 4 classes in my app cardclick.java , DatabaseHelper.java , homeframgment.java and recyclerAdapterhomesubjectList.java
I have a function populateArrayList(); in homefragment in which i want to call every time onclick(){present in recyclerAdapterHomesubjectList} is called. can someone help me in achieving that
homefragment::
package com.example.app100.RecylerAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app100.R;
import com.example.app100.Subject;
import com.example.app100.card_click;
import com.example.app100.ui.home.HomeFragment;
import java.util.ArrayList;
public class RecyclerAdapterHomeSubjectList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Subject> subject;
private Context context;
public RecyclerAdapterHomeSubjectList(ArrayList<Subject> a, Context context){
this.subject = a;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.card_home_subject, parent, false);
return new ViewHolder(view) {
};
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.home_card_subject_imageview);
switch (position % 3) {
case 2:
imageView.setBackgroundResource(R.drawable.back1);
break;
case 1:
imageView.setBackgroundResource(R.drawable.back2);
break;
case 0:
imageView.setBackgroundResource(R.drawable.back3);
break;
}
Subject data = subject.get(position);
String name = data.subject_name;
TextView subject_name = holder.itemView.findViewById(R.id.home_card_subject_name);
subject_name.setText(name);
}
#Override
public int getItemCount() {
return subject.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context , card_click.class);
intent.putExtra("name" , subject.get(getAdapterPosition()).subject_name);
intent.putExtra("class_good" , subject.get(getAdapterPosition()).class_attended);
intent.putExtra("class_missed" , subject.get(getAdapterPosition()).class_missed);
intent.putExtra("credits",subject.get(getAdapterPosition()).credits);
context.startActivity(intent);
}
}
}
DatabaseHelper::
package com.example.app100;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String table_name = "SUBJECT_LIST";
private static final String COL0 = "ID";
private static final String COL1 = "NAME";
private static final String COL2 = "CREDITS";
private static final String COL3 = "CLASS_ATTENDED";
private static final String COL4 = "CLASS_MISSED";
public DatabaseHelper(#Nullable Context context) {
super(context, table_name, null, 6);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + table_name + "("+
COL0+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL1 + " TEXT, " +
COL2 + " INTEGER, "+
COL3 + " INTEGER, "+
COL4 + " INTEGER);";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table_name);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
boolean addData(String name, int credit , int good , int bad){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1 , name);
contentValues.put(COL2 , credit);
contentValues.put(COL3 , good);
contentValues.put(COL4 , bad);
long result = db.insert(table_name , null , contentValues);
return result != -1;
}
public Cursor getdata(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM SUBJECT_LIST;";
return db.rawQuery(query , null);
}
void append_data(String str, String name , int goodbad) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(str, goodbad);
int count = db.update(table_name, contentValues, "NAME = ?", new String[]{name});
Log.d(TAG, "blue button is pressed");
System.out.println(count);
}
}
cardclick:
package com.example.app100;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
public class card_click extends AppCompatActivity {
TextView attendace_info;
ProgressBar progressBar;
TextView credits;
TextView progress_percent;
int bad;
int good;
Button add;
Button minus;
ImageButton performance;
String name;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_click);
databaseHelper = new DatabaseHelper(this);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
performance = findViewById(R.id.card_click_performance_add);
progress_percent = findViewById(R.id.card_click_progress_bar_percent);
attendace_info = findViewById(R.id.card_click_attendance_text);
progressBar = findViewById(R.id.card_click_progress_bar);
credits = findViewById(R.id.card_click_credits_show);
add = findViewById(R.id.card_click_add_button);
minus = findViewById(R.id.card_click_minus_button);
Intent intent = getIntent();
good = intent.getIntExtra("class_good", 0);
bad = intent.getIntExtra("class_missed", 0);
name = intent.getStringExtra("name");
credits.setText(String.valueOf(intent.getIntExtra("credits", 0)));
display();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
good++;
databaseHelper.append_data("CLASS_ATTENDED", name , good);
display();
Cursor data = databaseHelper.getdata();
while(data.moveToNext()){
int a = data.getInt(3);
if( a > 0)
System.out.println("database has been updated");
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bad++;
databaseHelper.append_data("CLASS_MISSED", name, bad);
display();
Cursor data = databaseHelper.getdata();
while(data.moveToNext()){
int b = data.getInt(4);
if( b > 1)
System.out.println("database has been updated");
}
}
});
performance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(card_click.this, add_performace.class);
startActivity(intent1);
}
});
}
void display(){
int per = 100;
if(good+bad != 0)
per = (int)(good*100.0)/(good+bad);
String str = "You have atttended "+ (good) +
" out of " + (good + bad) +
" classes";
attendace_info.setText(str);
progressBar.setProgress(per);
progress_percent.setText(String.valueOf(per));
}
}
RecyclerAdapterHomeSubjectList:
package com.example.app100.RecylerAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app100.R;
import com.example.app100.Subject;
import com.example.app100.card_click;
import com.example.app100.ui.home.HomeFragment;
import java.util.ArrayList;
public class RecyclerAdapterHomeSubjectList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Subject> subject;
private Context context;
public RecyclerAdapterHomeSubjectList(ArrayList<Subject> a, Context context){
this.subject = a;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.card_home_subject, parent, false);
return new ViewHolder(view) {
};
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.home_card_subject_imageview);
switch (position % 3) {
case 2:
imageView.setBackgroundResource(R.drawable.back1);
break;
case 1:
imageView.setBackgroundResource(R.drawable.back2);
break;
case 0:
imageView.setBackgroundResource(R.drawable.back3);
break;
}
Subject data = subject.get(position);
String name = data.subject_name;
TextView subject_name = holder.itemView.findViewById(R.id.home_card_subject_name);
subject_name.setText(name);
}
#Override
public int getItemCount() {
return subject.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context , card_click.class);
intent.putExtra("name" , subject.get(getAdapterPosition()).subject_name);
intent.putExtra("class_good" , subject.get(getAdapterPosition()).class_attended);
intent.putExtra("class_missed" , subject.get(getAdapterPosition()).class_missed);
intent.putExtra("credits",subject.get(getAdapterPosition()).credits);
context.startActivity(intent);
}
}
}
just import the class name and you can use the function from it. (function and the class should be public to use)

Deleting an item from RecyclerView + SQLite

So I'm trying to delete an item on a cross button. Now it is being deleted from RecyclerView, but goes crazy with SQLite. If I delete one item, it's all good. But when I delete several items, it, as I said, goes crazy and gets deleted items back outta nowhere without deleting anything then.
Here's my DataAdapted.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Booking> bookings;
private String time;
DBHelper dbHelper;
SQLiteDatabase dataBase;
DataAdapter(Context context, List<Booking> bookings) {
this.bookings = bookings;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public DataAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DataAdapter.ViewHolder holder, int position) {
Booking booking = bookings.get(position);
holder.nameView.setText(booking.getName());
time = booking.getHours() + ":" + booking.getMinutes();
holder.timeView.setText(time);
}
#Override
public int getItemCount() {
return bookings.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameView;
TextView timeView;
ImageView crossImage;
ViewHolder(View view){
super(view);
timeView = view.findViewById(R.id.time_view);
nameView = view.findViewById(R.id.name_view);
crossImage = view.findViewById(R.id.crossImage);
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeAt(getAdapterPosition());
}
});
}
}
public void removeAt(int position) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(position);
}
}
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "bookingsDb";
public static final String TABLE_BOOKINGS = "bookings";
public static final String KEY_ID = "_id";
public static final String KEY_NUMBER = "_numbers";
public static final String KEY_NAME = "_names";
public static final String KEY_HOURS = "_hours";
public static final String KEY_MINUTES = "_minutes";
public static final String KEY_PHONE= "_phones";
Context myContext;
static DBHelper dbHelper;
static SQLiteDatabase database;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_BOOKINGS + "("
+ KEY_ID + " integer primary key,"
+ KEY_NUMBER + " integer,"
+ KEY_NAME + " text,"
+ KEY_HOURS + " text,"
+ KEY_MINUTES + " text,"
+ KEY_PHONE + " text" + ")");
dbHelper = new DBHelper(myContext);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_BOOKINGS);
onCreate(db);
}
public static void delete(int id){
database = dbHelper.getWritableDatabase();
database.delete(TABLE_BOOKINGS, KEY_ID + "=" + id, null);
}
}
And my TableActivity.java if needed
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TableActivity extends AppCompatActivity {
int currentTable;
Button createNewBooking;
List<Booking> bookings;
TextView name;
TextView time;
DataAdapter adapter;
RecyclerView recyclerView;
DBHelper dbHelper;
View.OnClickListener createNewBookingListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TableActivity.this, BookingActivity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
currentTable = MainActivity.getCurrentTable();
createNewBooking = findViewById(R.id.createNewBooking);
createNewBooking.setOnClickListener(createNewBookingListener);
bookings = new ArrayList<>();
dbHelper = new DBHelper(this);
setInitialData();
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new DataAdapter(this, bookings);
recyclerView.setAdapter(adapter);
}
private void setInitialData() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_BOOKINGS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(DBHelper.KEY_NAME);
int hoursIndex = cursor.getColumnIndex(DBHelper.KEY_HOURS);
int minutesIndex = cursor.getColumnIndex(DBHelper.KEY_MINUTES);
int phoneIndex = cursor.getColumnIndex(DBHelper.KEY_PHONE);
do {
bookings.add(new Booking(
currentTable,
cursor.getString(nameIndex),
cursor.getString(hoursIndex),
cursor.getString(minutesIndex),
cursor.getString(phoneIndex)
));
} while (cursor.moveToNext());
} else {
Toast.makeText(this, "Броней нет", Toast.LENGTH_SHORT).show();
}
cursor.close();
dbHelper.close();
}
}
Any ideas, please?
you are giving position for delete, it's not necessary to id will be same as per adapter position.
try this :
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Booking booking = bookings.get(getAdapterPosition());
datatype id = booking.getId();
removeAt(getAdapterPosition(),id);
}
});
public void removeAt(int position, dataType id) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(id);
}

Android Sqlite can't get records from Listview

I am writing a program that saves to DB and then get infos from the DB using SQLiteOpenHelper.
Problem is I insert text from the edit text but I got nothing to show.
is the problem from the listview? cuz I extend from ArrayAdapter class not from enter code hereCursor adapter? or there is something wrong with my code. Please take a look at my code this is my main Acitvity
package com.perfectapps.fasaven.dbnews;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import DBHelper.DBContract;
import DBHelper.DBModel;
import newsAdapter.NewsMainMenuAdapter;
public class MainActivity extends AppCompatActivity {
Button submitNews;
ListView newsListView;
ArrayList<DBModel> dbmodel = new ArrayList<DBModel>();
EditText titleEditText;
TextView tvTitle;
TextView tvInfo;
EditText infoEditText;
DBContract dbContract;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTitle =(TextView)findViewById(R.id.tvTitle);
tvInfo =(TextView)findViewById(R.id.tvInfo);
submitNews = (Button)findViewById(R.id.submit_news);
newsListView = (ListView)findViewById(R.id.lvNews);
titleEditText = (EditText)findViewById(R.id.etNews);
infoEditText = (EditText)findViewById(R.id.etNewsInfo);
dbContract = new DBContract(this,null,null,1);
NewsMainMenuAdapter customeAdapter = new NewsMainMenuAdapter(getApplicationContext(), R.layout.row_news_element,dbmodel);
newsListView.setAdapter(customeAdapter);
// printDataBase();
submitNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBModel dbModel = new DBModel();
dbModel.setNewsInfos(infoEditText.getText().toString());
dbModel.setNewsTitle(titleEditText.getText().toString());
dbContract.addNews(dbModel);
Toast.makeText(getApplicationContext(),"saved to DB", Toast.LENGTH_LONG ).show();
titleEditText.setText("");
infoEditText.setText("");
// printDataBase();
}
});
}
public void printDataBase(){
DBModel dbModel = new DBModel();
String dbToStringTitle = dbContract.readNewsTitle();
tvTitle.setText(dbToStringTitle);
titleEditText.setText("");
String dbToStringInfo =dbContract.readNewsInfo();
tvInfo.setText(dbToStringInfo);
infoEditText.setText("");
}
}
This is my custom Adapter
package newsAdapter;
import android.support.annotation.LayoutRes;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import DBHelper.*;
import com.perfectapps.fasaven.dbnews.*;
import java.util.ArrayList;
/**
* Created by Salem on 22/12/2017.
*/
public class NewsMainMenuAdapter extends ArrayAdapter{
Context context;
ArrayList<DBModel> newsData;
int resource;
public NewsMainMenuAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<DBModel> newsData) {
super(context, resource, newsData);
this.context =context;
this.newsData = newsData;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_news_element,null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvInfo = (TextView)convertView.findViewById(R.id.tvInfo);
viewHolder.tvTitle = (TextView)convertView.findViewById(R.id.tvTitle);
viewHolder.tvTitle.setText(newsData.get(position).getNewsTitle());
viewHolder.tvInfo.setText(newsData.get(position).getNewsInfos());
//return super.getView(position, convertView, parent);
return convertView;
}
//#Nullable
// #Override
// public DBModel getItem(int position) {
// return super.getItem(position);
//}
class ViewHolder{
TextView tvTitle;
TextView tvInfo;
}
}
Here is my DB helper
package DBHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Salem on 22/12/2017.
*/
public class DBContract extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "newsDB.db";
public static final String TABLE_NAME = "news";
public static final String COLUMN_ID = "_ID";
public static final String COLUMN_NEWS_TITLE = "newstitle";
public static final String COLUMN_NEWS_IMAGE = "newsimage";
public static final String COLUMN_NEWS_INFO= "newsinfo";
public DBContract(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_NAME, factory, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_NAME + " ("
+COLUMN_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NEWS_TITLE+ " TEXT ,"
+COLUMN_NEWS_INFO+ " TEXT );";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public void addNews(DBModel dbModel){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NEWS_TITLE, dbModel.getNewsTitle());
contentValues.put(COLUMN_NEWS_INFO, dbModel.getNewsInfos());
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
}
public String readNewsTitle(){
String readNews = "";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_TITLE+" FROM "+TABLE_NAME +" where 1";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE))!=null);
{
readNews += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE));
readNews +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNews;
}
public String readNewsInfo(){
String readNewsInfo="";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_INFO+" FROM "+TABLE_NAME ;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO))!=null);
{
readNewsInfo += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO));
readNewsInfo +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNewsInfo;
}
}
There is one 4th class that has setters and getters named DBModel
and got XML for main activity which has listview.. but it when I input from edit text it doesn't show there

Can not delete the note from the list and from the database in my note app for Android

In my note app for Android, if I press long on a note then chose "Delete" to delete the note, the note still exists in the list, then after I close the app then return to it, the note is gone!
Hint: I am uses the onContextItemSelected method to show the "Delete" option.
How I can delete the note from the list and from the database?!
The MainActivity class which contains the onContextItemSelected method:
package com.twitter.i_droidi.mynotes;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
ListView lv;
NotesDataSource nDS;
List<NotesModel> notesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDS = new NotesDataSource(this);
lv = (ListView) findViewById(R.id.lv);
nDS.open();
notesList = nDS.getAllNotes();
nDS.close();
String[] notes = new String[notesList.size()];
for (int i = 0; i < notesList.size(); i++) {
notes[i] = notesList.get(i).getTitle();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, notes);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent nView = new Intent(this, Second2.class);
nView.putExtra("id", notesList.get(position).getId());
nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(nView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_delete, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
nDS.open();
nDS.deleteNote("id"); // Check...!!!
nDS.close();
Toast nDelete = Toast.makeText(this, R.string.deleted, Toast.LENGTH_LONG);
nDelete.show();
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mainMenuNewNote:
Intent nNote = new Intent(this, Second.class);
startActivity(nNote);
return true;
case R.id.mainMenuAbout:
AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
aboutDialog.setTitle(getString(R.string.about_title));
aboutDialog.setMessage(R.string.about_body);
aboutDialog.setIcon(R.drawable.my_notes);
aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface aboutDialog, int witch) {
// Do Not Do Anything.
}
});
aboutDialog.show();
return true;
case R.id.mainMenuExit:
AlertDialog.Builder exDialog = new AlertDialog.Builder(this);
exDialog.setTitle(R.string.exit_title);
exDialog.setMessage(R.string.exit_body);
exDialog.setIcon(R.drawable.my_notes);
exDialog.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
finish();
}
});
exDialog.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
// Do Not Do Anything.
}
});
exDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The DB class:
package com.twitter.i_droidi.mynotes;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB extends SQLiteOpenHelper {
private static final String DB_NAME = "MyNotes";
private static final int DB_VERSION = 1;
public static final String TABLE_NAME = "MyNotes";
public static final String ID = "id";
public static final String TITLE = "title";
public static final String BODY = "body";
private static final String DB_CREATE = "create table " + TABLE_NAME + " (" + ID + " integer primary key autoincrement, " +
TITLE + " text not null, " + BODY + " text not null)";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
The NotesDataSource class:
package com.twitter.i_droidi.mynotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
DB myDB;
SQLiteDatabase sql;
String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};
public NotesDataSource(Context context) {
myDB = new DB(context);
}
public void open() {
try {
sql = myDB.getWritableDatabase();
} catch (Exception ex) {
Log.d("Error in your database!", ex.getMessage());
}
}
public void close() {
sql.close();
}
public void createNote(String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.insert(myDB.TABLE_NAME, null, note);
}
public NotesModel getNote(int id) {
NotesModel note = new NotesModel();
Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});
if (cursor.getCount() > 0) {
cursor.moveToFirst();
note.setId(cursor.getInt(0));
note.setTitle(cursor.getString(1));
note.setBody(cursor.getString(2));
cursor.close();
}
return note;
}
public void updateNote(int id, String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
}
public void deleteNote(Object id) {
sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
}
public List<NotesModel> getAllNotes() {
List<NotesModel> notesList = new ArrayList<NotesModel>();
StringBuffer selectQuery = new StringBuffer();
selectQuery.append("SELECT * FROM "+ myDB.TABLE_NAME +"");
Cursor cursor = sql.rawQuery(selectQuery.toString(), null);
if(cursor != null && cursor.moveToFirst()) {
do {
NotesModel notes = new NotesModel();
notes.setId(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setBody(cursor.getString(2));
notesList.add(notes);
} while (cursor.moveToNext());
}
cursor.close();
return notesList;
}
}
After removing item from database
Remove the deleted item from
String[] notes
by using
notes.remove(position);
nd call
adapter.notifyDataSetChanged();

Categories

Resources