Using same class for 2 xml files that uses database - java

I would like to implement a database which consists of 2 tables, number and receivernumber. In fact, I have 2 xml files, one using number table, another using receivernumber. However, the code below only allows the first table to be used for both of the xmls.
Previously, I have tried implementing 2 different sets of class files, as stated below. But it crashes the entire app instead. So I tried changing to using the same class file with the receivernumber table being number2 instead. Now, both of the activity/xml file uses the first database but not the second. Please advice. Thanks in advance.
Note: there are no error logs available as it is working. Just that the table used for both activities are the same, but it's supposed to be different.
Set_numbers_to_forward.java
import java.util.ArrayList;
import java.util.List;
import com.example.awkwardpanda_redirectcall.DBAdapter;
import com.example.awkwardpanda_redirectcall.CallAdapter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
public class Set_numbers_to_forward extends Activity {
Context mContext;
ArrayAdapter<String> adapter;
List<String> adapterData;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_numbers_to_forward);
mContext = this;
ListView list = (ListView) findViewById(R.id.number_list);
adapterData = new ArrayList<String>();
DBAdapter db = new DBAdapter(this);
// ---get all contacts---
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst()) {
do {
adapterData.add(c.getString(1));
} while (c.moveToNext());
}
db.close();
adapter = new CallAdapter(this,
R.layout.set_numbers_to_forward_editable, adapterData);
list.setAdapter(adapter);
} // end onCreate
public void onCreate2(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_number_to_receive);
mContext = this;
ListView list = (ListView) findViewById(R.id.receiver_number);
adapterData = new ArrayList<String>();
DBAdapter db = new DBAdapter(this);
// ---get all contacts---
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst()) {
do {
adapterData.add(c.getString(1));
} while (c.moveToNext());
}
db.close();
adapter = new CallAdapter(this,
R.layout.set_number_to_receive_editable, adapterData);
list.setAdapter(adapter);
} // end onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addbtn, menu);
return true;
}
public boolean onCreateOptionsMenu2(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addbtn2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("New Phone Number");
builder.setMessage("Enter Phone Number :");
final EditText input = new EditText(Set_numbers_to_forward.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.insertContact(input.getText().toString());
db.close();
adapterData.add(input.getText().toString());
adapter.notifyDataSetChanged();
}
});
builder.create().show();
return true;
}
public boolean onOptionsItemSelected2(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("New Phone Number");
builder.setMessage("Enter Phone Number :");
final EditText input = new EditText(Set_numbers_to_forward.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.insertContact2(input.getText().toString());
db.close();
adapterData.add(input.getText().toString());
adapter.notifyDataSetChanged();
}
});
builder.create().show();
return true;
}
}
DBAdapter.java
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.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "hpnumberID";
public static final String KEY_NAME = "hpNumber";
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID2 = "hpnumberID";
public static final String KEY_NAME2 = "hpNumber";
private static final String DATABASE_NAME = "HPnumberDB";
private static final String DATABASE_TABLE = "number";
private static final String DATABASE_TABLE2 = "receivernumber";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table number (hpnumberID integer primary key autoincrement, "
+ "hpNumber text not null);";
private static final String DATABASE_CREATE2 =
"create table receivernumber (hpnumberID integer primary key autoincrement, "
+ "hpNumber text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE2);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE2);
onCreate(db);
}
} // end DatabaseHelper class
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String hpNumber)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, hpNumber);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertContact2(String hpNumber)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME2, hpNumber);
return db.insert(DATABASE_TABLE2, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long hpnumberID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + hpnumberID, null) > 0;
}
public boolean deleteContact2(long hpnumberID)
{
return db.delete(DATABASE_TABLE2, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null,
null, null, null);
}
public Cursor getAllContacts2()
{
return db.query(DATABASE_TABLE2, new String[] {KEY_ROWID2, KEY_NAME2}, null, null,
null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long hpnumberID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME}, KEY_ROWID + "=" + hpnumberID, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact2(long hpnumberID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE2, new String[] {KEY_ROWID2,
KEY_NAME2}, KEY_ROWID2 + "=" + hpnumberID, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long hpnumberID, String hpNumber)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, hpNumber);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + hpnumberID, null) > 0;
}
public boolean updateContact2(long hpnumberID, String hpNumber)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME2, hpNumber);
return db.update(DATABASE_TABLE2, args, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}
} // end DBAdapter class
CallAdapter.java
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CallAdapter extends ArrayAdapter<String> {
Context mContext;
List<String> list;
public CallAdapter(Context context, int resource, List<String> list) {
super(context, resource, list);
// TODO Auto-generated constructor stub
mContext = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater
.inflate(R.layout.set_numbers_to_forward_editable, parent,
false);
TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
ImageView discardButton = (ImageView) rowView
.findViewById(R.id.number_discard_button);
ImageView editButton = (ImageView) rowView
.findViewById(R.id.number_edit_button);
hpNumber.setText(list.get(position));
discardButton.setTag(position);
editButton.setTag(position);
editButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String position = v.getTag().toString();
createDialog(position, list);
}
});
discardButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createDeleteDialog(v.getTag().toString(), list);
}
});
return rowView;
}
public View getView2(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater
.inflate(R.layout.set_number_to_receive_editable, parent,
false);
TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
ImageView discardButton = (ImageView) rowView
.findViewById(R.id.number_discard_button);
ImageView editButton = (ImageView) rowView
.findViewById(R.id.number_edit_button);
hpNumber.setText(list.get(position));
discardButton.setTag(position);
editButton.setTag(position);
editButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String position = v.getTag().toString();
createDialog(position, list);
}
});
discardButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createDeleteDialog(v.getTag().toString(), list);
}
});
return rowView;
}
public void createDialog(String position, List<String> list) {
final long hpnumberID = Long.parseLong(position) + 1;
final int viewPosition = Integer.parseInt(position);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Edit");
final EditText input = new EditText(mContext);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setText(list.get(viewPosition));
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.updateContact(hpnumberID, input.getText().toString());
db.close();
((Set_numbers_to_forward)
mContext).adapterData.remove(viewPosition);
((Set_numbers_to_forward)
mContext).adapterData.add(viewPosition, input
.getText().toString());
((Set_numbers_to_forward)
mContext).adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
builder.create().show();
}
public void createDeleteDialog(String position, List<String> list) {
final int viewPosition = Integer.parseInt(position);
final long hpnumberID = Long.parseLong(position) + 1;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Deleting \"" + list.get(viewPosition) + "\"");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.deleteContact(hpnumberID);
db.close();
((Set_numbers_to_forward)
mContext).adapterData.remove(viewPosition);
((Set_numbers_to_forward)
mContext).adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
builder.create().show();
}
}

You don't really have a question in your... question. What I can tell you is that if you setup and use your own ContentProvider it takes care of a lot of what you are doing and makes it simpler. You can read the tutorial on the android documentation here http://developer.android.com/guide/topics/providers/content-provider-creating.html
If you start with that feel free to leave a comment on this answer if you run into any problems with the tutorial and I might be able to help. As it is you are 'reinventing the wheel' and making things difficult for yourself
edit
I've just realised from Tobor's comment there's a content provider buried in there as well - I still recommend following the tutorial above (or finding your own) to clear up the code

Why do you need doubles??
You can't use ArrayAdapter and Activity like this. Also, you don't need two xml files for this. Create an xml layout that contains two views inside and set this view as content view of your activity.
In overrided getView method in your adapter, update these views.
onCreate2 and getView2 methods are not called from anywhere and shouldn't be. In an activity, there can be only one content view.
Please see ArrayAdapter and creating Android Activity and SQLite DBAdapter examples first before starting new development.

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

I have no Idea what's wrong with my SQlite Database

My program was working fine until I decide to modify my DBHelper class, after a few changes every time I modify my program shows me this Log:
E/KernelCpuSpeedReader: Failed to read cpu-freq
java.io.FileNotFoundException: /sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:66)
at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49)
at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002)
at com.android.internal.os.BatteryStatsImpl$MyHandler.handleMessage(BatteryStatsImpl.java:155)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:438)
at java.io.FileInputStream.<init>(FileInputStream.java:76) 
at java.io.FileInputStream.<init>(FileInputStream.java:103) 
at java.io.FileReader.<init>(FileReader.java:66) 
at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49) 
at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002) 
at com.android.internal.os.BatteryStatsImpl$MyHandler.handleMessage(BatteryStatsImpl.java:155) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.os.HandlerThread.run(HandlerThread.java:61) 
at com.android.server.ServiceThread.run(ServiceThread.java:46) 
04-24 05:36:35.369 1299-1313/? E/KernelUidCpuTimeReader: Failed to read uid_cputime
java.io.FileNotFoundException: /proc/uid_cputime/show_uid_stat: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:66)
I don't want to assume or make more changes, this is my final stage of my project please help here is my
DB Helper:
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String VALUES_TABLE_NAME = "values";
public static final String VALUES_COLUMN_ID = "id";
public static final String VALUES_COLUMN_CONDUCTIVITY = "conductivity";
public static final String VALUES_COLUMN_MOISTURE = "moisture";
public static final String VALUES_COLUMN_OXYGEN = "oxygen";
public static final String VALUES_COLUMN_PH = "ph";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table values " +
"(id integer primary key, conductivity text,ph text,oxygen text, moisture text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS values");
onCreate(db);
}
public boolean insertContact (String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("ph", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.insert("values", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from values where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, VALUES_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("phone", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.update("values", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("values",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from values", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(VALUES_COLUMN_CONDUCTIVITY)));
res.moveToNext();
}
return array_list;
}
}
Main Activity:
package com.example.carlos.application1;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.widget.Toast;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
int status = 0;
Button hp_1, HP2, fo, previous, next, MZ, Control, show, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button home = (Button) findViewById(R.id.home);
registerForContextMenu(home);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
Button hp_1 = (Button) findViewById(R.id.hp_1);
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
hp_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = 1;
Bundle bundle = new Bundle();
bundle.putInt("status", status);
Intent intent = new Intent(MainActivity.this, DisplayValues.class);
intent.putExtras(bundle);
startActivity(intent);/*Intent intent = new Intent(first.this, second.class);
Bundle bundle = new Bundle();
bundle.putInt("index", index);
intent.putExtras(bundle);
startActivity(intent); */
}
});
}
#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){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
//dfsdfasdfasdfasd
}
And Display Value class, where I get the entries to my DB:
package com.example.carlos.application1;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayValues extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView conductivity ;
TextView ph;
TextView moisture;
TextView oxygen;
int id_To_Update = 0;
public void backButtonHandler() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
DisplayValues.this);
// Setting Dialog Title
alertDialog.setTitle("Leave the page?");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to leave without saving the Entries?");
// Setting Icon to Dialog
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onBackPressed() {
backButtonHandler();
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
conductivity = (TextView) findViewById(R.id.editTextConductivity);
oxygen= (TextView) findViewById(R.id.editTextOxygen);
moisture = (TextView) findViewById(R.id.editTextMoisture);
ph = (TextView) findViewById(R.id.editTextpH);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String condc = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_CONDUCTIVITY));
String mois = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_MOISTURE));
String oxy = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_OXYGEN));
String phe = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_PH));
/* public static final String DATABASE_NAME = "MyDBName.db";
public static final String VALUES_TABLE_NAME = "values";
public static final String VALUES_COLUMN_CONDUCTIVITY = "conductivity";
public static final String VALUES_COLUMN_MOISTURE = "moisture";
public static final String VALUES_COLUMN_OXYGEN = "oxygen";
public static final String VALUES_COLUMN_PH = "ph";*/
if (!rs.isClosed())
{
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
conductivity.setText((CharSequence)condc);
conductivity.setFocusable(false);
conductivity.setClickable(false);
moisture.setText((CharSequence)mois);
moisture.setFocusable(false);
moisture.setClickable(false);
ph.setText((CharSequence)phe);
ph.setFocusable(false);
ph.setClickable(false);
oxygen.setText((CharSequence)oxy);
oxygen.setFocusable(false);
oxygen.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
}
else{
getMenuInflater().inflate(R.menu.menu_main, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
conductivity.setEnabled(true);
conductivity.setFocusableInTouchMode(true);
conductivity.setClickable(true);
ph.setEnabled(true);
ph.setFocusableInTouchMode(true);
ph.setClickable(true);
moisture.setEnabled(true);
moisture.setFocusableInTouchMode(true);
moisture.setClickable(true);
oxygen.setEnabled(true);
oxygen.setFocusableInTouchMode(true);
oxygen.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,conductivity.getText().toString(), ph.getText().toString(), oxygen.getText().toString(), moisture.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertContact(conductivity.getText().toString(), ph.getText().toString(), oxygen.getText().toString(), moisture.getText().toString())){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}

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

NPE with custom adapter

I am making a custom adapter for list view and got NPE. I have already read other questions but none of them.
Here is the logcat
07-04 06:54:58.036: E/AndroidRuntime(1340): FATAL EXCEPTION: main
07-04 06:54:58.036: E/AndroidRuntime(1340): java.lang.NullPointerException
07-04 06:54:58.036: E/AndroidRuntime(1340): at com.example.amirkh.MainActivity$FastFoodAdapter.getView(MainActivity.java:166)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.AbsListView.obtainView(AbsListView.java:2159)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.onMeasure(ListView.java:1158)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.View.measure(View.java:15518)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.TableRow.measureChildBeforeLayout(TableRow.java:247)
the code works this way. there is a databasehandler that organize database, a fastfood class and main class. in main class the user enteres a fastfood name and it goes to data base. when user clicks on the"show data" tab whole data should be shown.
here is the main class:
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnActionExpandListener;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends TabActivity {
private TabHost myTabHost;
private FastFoodAdapter<String> adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTabHost = getTabHost();
TabHost.TabSpec spec;
// Adding First Tab
spec = myTabHost.newTabSpec("first");
spec.setContent(R.id.inputtab);
spec.setIndicator("Input data");
myTabHost.addTab(spec);
// Adding Second Tab
spec = myTabHost.newTabSpec("second");
spec.setContent(R.id.listView1);
spec.setIndicator("Show data");
myTabHost.addTab(spec);
myTabHost.setCurrentTab(0);
// final List<FastFood> fflist = new ArrayList<FastFood>();
final EditText etname = (EditText) findViewById(R.id.etname);
final EditText etaddress = (EditText) findViewById(R.id.etaddress);
final ListView lv = (ListView) findViewById(R.id.listView1);
final DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
final RadioGroup radiogroup = (RadioGroup) findViewById(R.id.radioGroup1);
final FastFood fastfood = new FastFood();
final RadioButton rbsit = (RadioButton) findViewById(R.id.rbsit);
final RadioButton rbdeli = (RadioButton) findViewById(R.id.rbdeliv);
final RadioButton rbtake = (RadioButton) findViewById(R.id.rbtake);
refreshComponents();
Button save = (Button) findViewById(R.id.btnsave);
Button remove = (Button) findViewById(R.id.btnremove);
// Create context menu
registerForContextMenu(lv);
// end of context menu
// start of save button
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
FastFood ffastfood = new FastFood("", "", "");
ffastfood.setName(etname.getText().toString());
ffastfood.setAddress(etaddress.getText().toString());
etname.setText("");
etaddress.setText("");
if (rbsit.isChecked()) {
ffastfood.setFlag("1");
} else if (rbtake.isChecked()) {
ffastfood.setFlag("2");
} else if (rbdeli.isChecked()) {
ffastfood.setFlag("3");
}
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is saved.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
dbh.addFastFood(ffastfood);
refreshComponents();
}
}); // end of save
// remove
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
EditText etrmvid = (EditText) findViewById(R.id.etrmvid);
dbh.removeFastFood(Integer.parseInt(etrmvid.getText()
.toString()));
etrmvid.setText("");
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is removed.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
refreshComponents();
}
});// end of remove
Context context = getApplicationContext();
// Adapter
}
class FastFoodAdapter<String> extends ArrayAdapter<String> {
public FastFood fastfood = new FastFood();
public FastFoodAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
TextView tv = (TextView) row.findViewById(R.id.txtTitle23);
TextView tv2 = (TextView) row.findViewById(R.id.txtTitle2);
ImageView iv = (ImageView) row.findViewById(R.id.imgIcon);
tv.setText(fastfood.getName());
tv2.setText(fastfood.getAddress());
if (fastfood.getFlag().equals("1"))
iv.setImageResource(R.drawable.sit);
else if (fastfood.getFlag().equals("2"))
iv.setImageResource(R.drawable.ta);
else if (fastfood.getFlag().equals("3"))
iv.setImageResource(R.drawable.deli);
return row;
}
}// /end of adapter
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.contexmenu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}
private void refreshComponents() {
ListView lv = (ListView) findViewById(R.id.listView1);
TextView lblCount = (TextView) findViewById(R.id.lblcount);
DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
List<FastFood> fflist = dbh.getAllFastFoods();
// lv.setAdapter(new FastFoodAdapter<String>(context,
// textViewResourceId, objects))
lv.setAdapter(new FastFoodAdapter<FastFood>(MainActivity.this,
android.R.layout.simple_list_item_1, fflist));
lblCount.setText("Count of all FastFoods are " + dbh.getFastFoodCount());
}
}
here is fastfood class
package com.example.amirkh;
public class FastFood {
private String name;
private String address;
private String flag;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public FastFood(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
}
public FastFood() {
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return (String.format("%s %s ", getName(), getAddress()));
}
}
and the databasehandeler
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandeler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "FastFoodManager";
private static final String TABALE_FASTFOODS = "fastfoods";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_ADDRESS = "address";
private static final String KEY_FLAG = "flag";
public DataBaseHandeler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABALE_FASTFOODS + " ("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, "
+ KEY_ADDRESS + " TEXT, " + KEY_FLAG + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABALE_FASTFOODS);
onCreate(db);
}
// insert a record
public void addFastFood(FastFood fastfood) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, fastfood.getName());
values.put(KEY_ADDRESS, fastfood.getAddress());
values.put(KEY_FLAG, fastfood.getFlag());
db.insert(TABALE_FASTFOODS, null, values);
db.close();
}
// remove a record by ID
public void removeFastFood(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABALE_FASTFOODS, KEY_ID + " =?",
new String[] { String.valueOf(id) });
db.close();
}
// count
public int getFastFoodCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
// db.close();
return cursor.getCount();
}
// get all contacts
public List<FastFood> getAllFastFoods() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
List<FastFood> fflist = new ArrayList<FastFood>();
if (cursor.moveToFirst()) {
do {
FastFood ff = new FastFood();
ff.setId(Integer.parseInt(cursor.getString(0)));
ff.setName(cursor.getString(1));
ff.setAddress(cursor.getString(2));
ff.setFlag(cursor.getString(3));
fflist.add(ff);
} while (cursor.moveToNext());
}
// db.close();
return fflist;
}
}
Thanks for helping
You are getting this NullPointerException because you are trying to compare a null String in this line
fastfood.getFlag().equals("1")
In your adapter you create an object of Food using
public FastFood fastfood = new FastFood();
In the empty constructor of Food class nothing is assigned to any of the member String so when you try to do
fastfood.getFlag().equals("1")
you are trying to call equals method on a null object.
So you get a NullPointerException.
You should use the Food objects from the List that you pass in the FastFoodAdapter constructor.
Your NPE come from:
if (fastfood.getFlag().equals("1"))
So fastfood.getFlag() seems null. You should use setFlag() before or try this comparison:
if ("1".equals(fastfood.getFlag()))

show data from database to listView Android

I am trying to show all my data from my database into the listview
Code to create database:
DataHander.java
package com.example.testingforstack;
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;
public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "mytable";
public static final String DATA_BASE_NAME = "mydatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
}
public static class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context ctx) {
super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getReadableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String name, String email){
ContentValues content = new ContentValues();
content.put(NAME, name);
content.put(EMAIL, email);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
}
}
mainActivity.java
package com.example.testingforstack;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save, load;
EditText name, email;
DataHandler handler;
String getName, getEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.save);
load = (Button) findViewById(R.id.load);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName = name.getText().toString();
String getEmail = email.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id = handler.insertData(getName, getEmail);
insertSuccess();
//Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getName = "";
getEmail = "";
handler = new DataHandler(getBaseContext());
handler.open();
Cursor C = handler.returnData();
if(C.moveToFirst()){
do{
getName = C.getString(0);
getEmail = C.getString(1);
}while(C.moveToNext());
}
handler.close();
loadSuccess();
//Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
}
});
}
public void insertSuccess()
{
AlertDialog.Builder insertData = new AlertDialog.Builder(this);
insertData.setTitle("Info");
insertData.setMessage("Data Inserted");
insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
insertData.show();
}
public void loadSuccess()
{
AlertDialog.Builder loadData = new AlertDialog.Builder(this);
loadData.setTitle("Info");
loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
loadData.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.main, menu);
return true;
}
}
I have two button save and load. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?
In listview you can use different types of adapters. For database, most appropriate is to use cursorAdapter where you tell which cursor to use. You can also manually walk through elements in DB and save them in some other object in array and then you can have arrayAddapter in which you pass your array of object. In each case you must set binder or override method onCreateView where you tell which parameter go in which child.
You can look this http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html example for more information.

Categories

Resources