How Can I delete item on my SQliteOpenhelper [duplicate] - java

This question already has answers here:
How to delete items from sqlite database with SQLiteOpenHelper class
(2 answers)
Closed 2 years ago.
I save my recyclerview with SQliteopenhelper . I can add item with edittext varibles . I use Itemtouchhelper for swip to delete item . How can ı delete item on SQliteopenhelper . Can you be fast
todoactivity.java
public class todoactivity extends AppCompatActivity {
TextView title;
Button back;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback simpleCallback = 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) {
int positionx = viewHolder.getAdapterPosition();
Listsx.remove(positionx);
adapterx.notifyItemRemoved(positionx);
int id = recyclerView.getChildAt(positionx).getId();
myDBxxx.deleteItem(id);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
DatabaseHelper.java
public class DatabaseHelper4 extends SQLiteOpenHelper {
public static final String DATABASE_NAME4 = "mylistxxx.db";
public static final String TABLE_NAME4 = "mylist_dataxxx";
public static final String COL14 = "iDxxx";
public static final String COL24 = "ITEM1xxx";
public DatabaseHelper4(Context context) {
super(context, DATABASE_NAME4, null, 1);
}
#Override
public void onCreate(SQLiteDatabase dbxxx) {
String createTable = "CREATE TABLE " + TABLE_NAME4 + " (iDxxx INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1xxx TEXT)";
dbxxx.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase dbxxx, int oldVersion, int newVersion) {
dbxxx.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME4);
onCreate(dbxxx);
}
public boolean addDataxxx(String textt) {
SQLiteDatabase dbxxx = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL24, textt);
long result = dbxxx.insert(TABLE_NAME4, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase dbxxx = this.getWritableDatabase();
Cursor dataxxx = dbxxx.rawQuery("SELECT * FROM " + TABLE_NAME4, null);
return dataxxx;
}
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " = " +
iDxxx);
}
}
Adapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
Thats my java classes . My activity is todoactivity . My SQliteopenhelper is DatabaseHelper.java . My Adapter is adapter.java . I can delete item on my recyclerview but ı cant delete item on my database

You can easily delete item from your table by just below code.
//Add method in your database class.
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " =
" + iDxxx);
}
and Just Call this method from where you are deleting item.

Related

Android studio displaying data from sqlite local db

I cant seem to find any solutions to this problem on the internet. basically im working on an app that lets the user create workouts and view them and I'm struggling with the view part.
My database is all set up with user input using the fields exercise, sets and reps, the user creates a workout and the contents of the table used to build it are copied to a new one and the table is cleared to take in new input.
I want to create a recycler view using the table names, pass the selected item name to the next fragment and use the users selection to determine what data will be shown in the next recycler view.
Is this possible and if so please show me how, I'm supposed to have this app ready in a couple of days for an assignment
any help would be appreciated, thanks - Ian
To clairfy, you would like to make list of the list?
Use one to many relationship or map using room.
I have done such implementation days ago feel free to ask.
https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR3P_rK8OeOpBpP9jgbL8FqxEKPXPvOaFwFiCMy4pIpblg_aF_9QloavHpM
https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR22XINRNxTs3b_KOleeYwjGuIwjUA90S3tvpMWkf1dKYjvDDo5qWAbLfoE
To get previous ID or name just use simple Bundle of position(or ID) of specific element from first recyclerview and use it in the second to display the right data.
Is this possible and if so please show me how.
It is possible.
Here's a working demo that shows how.
First the class that extends SQLiteOPenHelper, as is typically used, namely DatabaseHelper in this example:-
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "thedatabase.db";
public static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
private DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
private static volatile DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(MyTable.CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old_version, int new_version) {
}
public long insertMyTableRow(Long id, String item_name) {
ContentValues cv = new ContentValues();
cv.put(MyTable.COL_ITEM_NAME,item_name);
if (id != null && id == 0) {
cv.put(MyTable.COl_ID,id);
}
return db.insertWithOnConflict(MyTable.TABLE_NAME,null,cv,SQLiteDatabase.CONFLICT_IGNORE);
}
#SuppressLint("Range")
public MyTable[] getAllMyTableRowAsArrayOfMyTable() {
MyTable[] rv = new MyTable[0];
Cursor csr = db.query(MyTable.TABLE_NAME,null,null,null,null,null,null);
if (csr.getCount() > 0) {
rv = new MyTable[csr.getCount()];
}
int idx = 0;
while (csr.moveToNext()) {
rv[idx++] = new MyTable(
csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),
csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)
)
);
}
csr.close();
return rv;
}
#SuppressLint("Range")
public MyTable getAMyTableById(long id) {
MyTable rv = new MyTable(-1,"NOT FOUND");
Cursor csr = db.query(MyTable.TABLE_NAME,null,MyTable.COl_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new MyTable(csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)));
}
csr.close();
return rv;
}
}
class MyTable {
public static final String TABLE_NAME = (MyTable.class.getSimpleName()).toLowerCase();
public static final String COl_ID = TABLE_NAME + BaseColumns._ID;
public static final String COL_ITEM_NAME = TABLE_NAME + "_item_name";
// and so on
public static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"("
+ COl_ID + " INTEGER PRIMARY KEY"
+ "," + COL_ITEM_NAME + " TEXT UNIQUE "
// and so on
+ ")";
long id;
String itemName;
MyTable(long id, String item_name) {
this.id = id;
this.itemName = item_name;
}
}
The activity that will be called MainActivity2 being passed a unique identifier of the clicked item via an Intent Extra :-
public class MainActivity2 extends AppCompatActivity {
public static final String INTENT_EXTRA_MYTABLE_ID = "ie_mytable_id";
DatabaseHelper dbHelper;
TextView itemName;
Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
itemName = this.findViewById(R.id.item_name);
done = this.findViewById(R.id.done);
dbHelper = DatabaseHelper.getInstance(this);
itemName.setText((dbHelper.getAMyTableById(this.getIntent().getLongExtra(INTENT_EXTRA_MYTABLE_ID,-99))).itemName);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
An Adapter TheAdapter etc for the RecyclerView, including Item Click and Item Long Click listeners. Clicking an item Toasts details. Long clicking starts the second activity which displays the clicked item:-
public class TheAdapter extends RecyclerView.Adapter<TheAdapter.ViewHolder> {
private MyTable[] localData;
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textView1;
private final TextView textView2;
public ViewHolder(View view) {
super(view);
textView1 = (TextView) view.findViewById(android.R.id.text1);
textView2 = (TextView) view.findViewById(android.R.id.text2);
}
public TextView getTextView1() {
return textView1;
}
public TextView getTextView2() {
return textView2;
}
}
public TheAdapter(MyTable[] thedata) {
localData = thedata;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.getTextView1().setText(String.valueOf(localData[position].id));
holder.getTextView2().setText(localData[position].itemName);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(
view.getContext(),
"You clicked the Item named "
+ localData[holder.getAdapterPosition()].itemName
+ " the ID is " + String.valueOf(localData[holder.getAdapterPosition()].id),
Toast.LENGTH_SHORT
).show();
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(view.getContext(),MainActivity2.class);
intent.putExtra(MainActivity2.INTENT_EXTRA_MYTABLE_ID,localData[holder.getAdapterPosition()].id);
view.getContext().startActivity(intent);
return true;
}
});
}
#Override
public int getItemCount() {
return localData.length;
}
}
Finally the first/initial activity MainActivity :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
RecyclerView myTableList;
TheAdapter adapter;
MyTable[] theDataToBeDisplayed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTableList = this.findViewById(R.id.mytable_list);
dbHelper = DatabaseHelper.getInstance(this);
addSomeTestingData();
setupOrRefreshMyTableList();
}
private void setupOrRefreshMyTableList() {
theDataToBeDisplayed = dbHelper.getAllMyTableRowAsArrayOfMyTable();
if (adapter == null) {
adapter = new TheAdapter(theDataToBeDisplayed);
myTableList.setAdapter(adapter);
myTableList.setLayoutManager(
new LinearLayoutManager(this)
);
} else {
/* handle changed data here */
}
}
private void addSomeTestingData() {
for (int i=0; i < 100; i++) {
dbHelper.insertMyTableRow(null, "A" + String.valueOf(i));
}
}
}
When run:-
When an Item (e.g. A10 (whos' id is 11)) is Long clicked :-
Clicking DONE returns to the first activity.

SQLiteException: unknown database

I made a custom Adapter for my ListView following this tutorial.
But when I run my app on my device, it gives an error when it's starting.
The error appears when the onCreate() method of the MainActivity tries to call the getData() method of the NotesDbHelper class.
Can you help me?
MainActivity.java
public class MainActivity extends Activity
{
private EditText mEditText;
private Button mButton;
NotesCustomAdapter notesCustomAdapter = null;
ListView listView = null;
NotesDbHelper database = null;
ArrayList<Notes> notes = null;
/** Called when the activity is first created.
* #param savedInstanceState */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
database = new NotesDbHelper(this);
notes = database.getData();
notesCustomAdapter= new NotesCustomAdapter(this,R.layout.notes_details,notes);
listView = (ListView) findViewById(R.id.simpleListView);
listView.setAdapter(notesCustomAdapter);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
database.insertNote(input);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
database.deleteNote(which);
notes.remove(positionToRemove);
notesCustomAdapter.remove(String.valueOf(positionToRemove));
notesCustomAdapter.notifyDataSetChanged();
}});
adb.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
NotesDbHelper.java
public class NotesDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Notes.db";
public static final String NOTES_TABLE_NAME = "Notes.user";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NAME = "n_text";
public NotesDbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + NOTES_TABLE_NAME +
"(_id integer primary key AUTOINCREMENT NOT NULL," + NOTES_COLUMN_NAME +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_NAME);
onCreate(db);
}
public boolean insertNote(String text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.insert(NOTES_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList<Notes> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Notes> notes = new ArrayList<Notes>();
Cursor result = db.rawQuery("select * from "+ NOTES_TABLE_NAME , null);
while(result.moveToNext()){
notes.add( new Notes(result.getString(result.getColumnIndex(NOTES_COLUMN_NAME))));
}
return notes;
}
public boolean updateNotes(int id, int text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.update(NOTES_TABLE_NAME, contentValues, "id = ? ", new String[]{Integer.toString(id)});
return true;
}
public Integer deleteNote(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(NOTES_TABLE_NAME,
"id = ? ",
new String[]{Integer.toString(id)});
}
}
Notes.java
public class Notes {
String text;
public Notes(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
NotesCustomAdapter.java
public class NotesCustomAdapter extends ArrayAdapter{
private Context context;
private ArrayList<Notes> notes;
public NotesCustomAdapter(Context context, int textViewResourceId, ArrayList objects) {
super(context,textViewResourceId, objects);
this.context= context;
notes=objects;
}
private class ViewHolder
{
TextView text;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.notes_details, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Notes textNotes = notes.get(position);
holder.text.setText(textNotes.getText());
return convertView;
}
}
LogCat
the first line says:
java.lang.RuntimeException: Unable to start activity ComponentInfo{agenda.com/agenda.com.MainActivity}: android.database.sqlite.SQLiteException: unknown database Notes (code 1): while compiling: create table Notes.user(_id integer primary key AUTOINCREMENT NOT NULL,n_text)
Why Notes.user? You're putting an unnecessary dot. Go compare to the link you've referenced.
Just use Notes or UserNotes

My Recyclerview list stopped working after implementing SQLite database

I'm building a to do list app. I'm learning SQLite databases and I'm trying to save the user input into an SQLite database table and also display it in my recyclerview list. When I did this without the SQLite, it worked so the problem is obviously with my implementation of the database table. The app is supposed to add the data into the list per button click:
addingItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(itemsInput.getText() != null){
items.add(new todo(itemsInput.getText().toString()));
itemsInput.setText("");
}else {
Toast.makeText(MainActivity.this, "Please enter something to do", Toast.LENGTH_SHORT).show();
}
itemAdapter.notifyDataSetChanged();
}
});
But now it does not do that. The app does not crash. The problem is just that my list shows absolutely no data. The following are my relevant Java files:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase sqLiteDatabase;
private List<todo> items = new ArrayList<>();
private ItemAdapter itemAdapter;
private RecyclerView listItemsRecyclerView;
EditText itemsInput;
Button addingItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemsInput = (EditText)findViewById(R.id.to_do_editText);
addingItems = (Button)findViewById(R.id.to_do_btn);
listItemsRecyclerView = (RecyclerView) findViewById(R.id.to_do_list);
ToDoListDatabaseHelper databaseHelper = new ToDoListDatabaseHelper(this);
sqLiteDatabase = databaseHelper.getWritableDatabase();
items = new ArrayList<>();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
listItemsRecyclerView.setLayoutManager(layoutManager);
listItemsRecyclerView.setItemAnimator(new DefaultItemAnimator());;
itemAdapter = new ItemAdapter(items);
listItemsRecyclerView.setAdapter(itemAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
}
});
addingItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(itemsInput.getText().length() > 0){
addNewToDo(itemsInput.getText().toString());
itemsInput.setText("");
}else {
Toast.makeText(MainActivity.this, "Please enter something to do", Toast.LENGTH_SHORT).show();
}
itemAdapter.notifyDataSetChanged();
}
});
}
private List<todo> getAllToDos(){
Cursor cursor = sqLiteDatabase.rawQuery("select * from " + ToDoContract.ToDoEntry.TABLE_NAME, new String[]{});
List<todo> todos = new ArrayList<>();
todo todo;
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_NAME));
int priority = cursor.getInt(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_PRIORITY));
int timestamp = cursor.getInt(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_TIMESTAMP));
todo = new todo(name);
todos.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
}
return todos;
}
private long addNewToDo(String name){
ContentValues cv = new ContentValues();
cv.put(ToDoContract.ToDoEntry.COLUMN_TODO_NAME, name);
return sqLiteDatabase.insert(ToDoContract.ToDoEntry.TABLE_NAME, null, cv);
}
}
My custom adapter:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<todo> todoList;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView toDoTextView;
public ViewHolder(View itemView) {
super(itemView);
toDoTextView = (TextView) itemView.findViewById(R.id.to_do);
}
}
public ItemAdapter(List<todo> todoList) {
this.todoList = todoList;
}
#Override
public ItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ItemAdapter.ViewHolder holder, int position) {
todo toDo = todoList.get(position);
holder.toDoTextView.setText(toDo.getToDo());
}
#Override
public int getItemCount() {
return todoList.size();
}
}
I ran unit tests on my SQLite classes so there is no issue with them.
You should not use Cursor as the data source for Adapter.Why don't you just fetch data(todos) from cursor then put the data into Adapter? As we known, cursor should be CLOSED at the end of data reading. You should code like that:
private List<todo> getAllToDos() {
Cursor cursor = sqLiteDatabase.rawQuery("select * from " + ToDoContract.ToDoEntry.TABLE_NAME, new String[]{});
List<todo> todos = new ArrayList<>();
todo todo;
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_NAME));
int priority = cursor.getInt(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_PRIORITY));
int timestamp = cursor.getInt(cursor.getColumnIndex(ToDoContract.ToDoEntry.COLUMN_TODO_TIMESTAMP));
todo = new todo(name);
todo.setPriority(priority);
todo.setTimestamp(timestamp);
todos.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
}
return todos;
}
And your ItemAdapter will be simpler.
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<todo> todoList;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView toDoTextView;
public ViewHolder(View itemView) {
super(itemView);
toDoTextView = (TextView) itemView.findViewById(R.id.to_do);
}
}
public ItemAdapter(List<todo> todoList) {
this.todoList = todoList;
}
#Override
public ItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ItemAdapter.ViewHolder holder, int position) {
todo toDo = todoList.get(position);
holder.toDoTextView.setText(toDo.getToDo());
}
#Override
public int getItemCount() {
return todoList.size();
}
}
There are some other changes.But I think you can fix them as I told you above.If you have any other question about that, please tell me.I will help you.
Try this
public void update()
{
cursor.requery();
notifyDataSetChanged();
}

how can i get data from adapter and show in Activity in Android

In my application I want show countries in dialog. In my application has some editTexts in mainActivity, when click on Contry editText show countryDialog and sort countries in this dialog (I get this countries from server).
I want when click on county name, set this country on editText.
my adapter codes:
public class CountryAdapter extends RecyclerView.Adapter {
private List<CountryDatum> mData;
private Context context;
public CountryAdapter(List<CountryDatum> mData, Context context) {
this.mData = mData;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_country, parent, false);
vh = new DataViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public int getItemCount() {
return mData.size();
}
public void add(List<CountryDatum> models) {
mData.addAll(models);
notifyDataSetChanged();
}
public void clear() {
mData.clear();
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView countryListTxt;
public DataViewHolder(View itemView) {
super(itemView);
countryListTxt = (TextView) itemView.findViewById(R.id.countryNameTxt);
}
}
}
Main Activity codes:
public class RegisterActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private String countryName = "";
#BindView(R.id.registerCountryEdtTxt)
EditText countryListEdt;
#BindView(R.id.registerDateBirthEdtTxt)
EditText birthDayEdt;
private CountryAdapter mAdapter;
private List<CountryDatum> models = new ArrayList<>();
private Context context;
private Dialog dialog;
private RecyclerView countryRecyler;
private ProgressBar countryProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Initialize
ButterKnife.bind(this);
context = RegisterActivity.this;
mAdapter = new CountryAdapter(models, context);
}
#OnClick({R.id.registerCountryEdtTxt, R.id.registerCountryInptLay})
void selectCountry() {
getData();
}
#OnClick({R.id.registerDateBirthInptLay, R.id.registerDateBirthEdtTxt})
void selectBirthDay() {
Calendar now = Calendar.getInstance();
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
RegisterActivity.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_1);
datePickerDialog.show(getFragmentManager(), "Datepickerdialog");
}
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: " + dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
birthDayEdt.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
public void getData() {
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_country);
countryRecyler = (RecyclerView) dialog.findViewById(R.id.countryRecyclerView);
countryProgress = (ProgressBar) dialog.findViewById(R.id.countryDialog_progress);
countryRecyler.setLayoutManager(new LinearLayoutManager(context));
countryRecyler.setHasFixedSize(true);
countryProgress.setVisibility(View.VISIBLE);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CountryResponse> call = api.getCountryList();
call.enqueue(new Callback<CountryResponse>() {
#Override
public void onResponse(Call<CountryResponse> call, Response<CountryResponse> response) {
try {
if (response.body() != null) {
models.clear();
models.addAll(response.body().getData());
countryProgress.setVisibility(View.GONE);
countryRecyler.setAdapter(mAdapter);
}
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<CountryResponse> call, Throwable t) {
}
});
dialog.show();
}
}
How can I when click on country names (from adapter), set this name for registerCountryEdtTxt.setText (in mainActivity)? how can I it?
I am amateur, please help me <3
In adapter create on interface to transfer data
public class CountryAdapter extends RecyclerView.Adapter {
public interface onListClickedRowListner {
void onListSelected(int mposition);
}
}
and in adapter constructor
onListClickedRowListner listner;
public CountryAdapter(List<CountryDatum> mData, Context context,onListClickedRowListner listner) {
this.mData = mData;
this.context = context;
this.listner = listner;
}
and in onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
listner.onListSelected(position);
}
});
}
}
and implements this listner in mainActivity
and onListSelected in this method you get position using that position get value from mData and assign to any view in your activity.
public class RegisterActivity extends AppCompatActivity implements
CountryAdapter.onListClickedRowListner {
.
.
.
#Override
public void onListSelected (int listposition){
Log.d("Tag",""+listposition);
}
}
and in you oncreate change like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Initialize
ButterKnife.bind(this);
context = RegisterActivity.this;
mAdapter = new CountryAdapter(models, context,this);
}
Try this solution . In your activity class do this.
countryRecyler.setAdapter(mAdapter,registerCountryEdtTxt);
then in adapter class
private List<CountryDatum> mData;
private Context context;
private EditText mEditText;
public CountryAdapter(List<CountryDatum> mData, Context
context,EditText edittext) {
this.mData = mData;
this.context = context;
mEditText=edittext;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
mEditText.setText(mData.get(position).getName())
}
});
}
}

Contact List not responding in Android M

I am displaying a Contacts From Mobile Contacts using RecyclerView,
here the problem is "when i tried my application to run on Android M it not responding it throws an error
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{3b9a84a 17730:com.strobilanthes.contactdetials/u0a224} (pid=17730, uid=10224) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS"
my Code below:
public class MainAct extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
List<String> phno1 = new ArrayList<String>();
Button select;
private EditText edtContactFilter;
private RecyclerView recyclerView;
private ICEAdapter iceAdapter;
ArrayList<ContactList> contactLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_display);
recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
getAllContacts(this.getContentResolver());
updateCabLsit(contactLists);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
Toast.makeText(MainAct.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
edtContactFilter = (EditText) findViewById(R.id.edt_contact_filter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void getAllContacts(ContentResolver cr) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
contactLists = new ArrayList<ContactList>();
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................." + phoneNumber + " >> " + name);
if (!phno1.contains(phoneNumber)) {
//name1.add(name);
phno1.add(phoneNumber);
ContactList c = new ContactList();
c.setIceName(name);
c.setIceNumber(phoneNumber);
contactLists.add(c);
}
}
phones.close();
} else {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
contactLists = new ArrayList<ContactList>();
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................." + phoneNumber + " >> " + name);
if (!phno1.contains(phoneNumber)) {
//name1.add(name);
phno1.add(phoneNumber);
ContactList c = new ContactList();
c.setIceName(name);
c.setIceNumber(phoneNumber);
contactLists.add(c);
}
}
phones.close();
}
}
public class ICEAdapter extends RecyclerView.Adapter<ICEAdapter.ViewHolder> {
private ArrayList<ContactList> contactLists;
private Context mContext;
public ICEAdapter(Context context, ArrayList<ContactList> contactList) {
this.contactLists = contactList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ice_items, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.txtName.setText(contactLists.get(position).getIceName());
holder.txtNumber.setText(contactLists.get(position).getIceNumber());
}
#Override
public int getItemCount() {
return contactLists == null ? 0 : contactLists.size();
}
public ContactList getItem(int position) {
return contactLists.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtNumber;
CheckBox chkSelect;
public ViewHolder(View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name);
txtNumber = (TextView) itemView.findViewById(R.id.txt_number);
chkSelect = (CheckBox) itemView.findViewById(R.id.chk_select);
}
}
}
private void updateCabLsit(ArrayList<ContactList> contactLists) {
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayout = new LinearLayoutManager(this);
linearLayout.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayout);
iceAdapter = new ICEAdapter(this, contactLists);
recyclerView.setAdapter(iceAdapter);
iceAdapter.notifyDataSetChanged();
}}

Categories