The delete method of my sql database doesn't remove the entry from the database. It gives a null pointer exception:
10-18 00:44:25.069: E/AndroidRuntime(17968): java.lang.NullPointerException
10-18 00:44:25.069: E/AndroidRuntime(17968): at com.weather.app.LocationDB.deleteLocation(LocationDB.java:98)
public class LocationDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "locationManager";
private static final String TABLE_LOCATIONS = "locations";
private static final String KEY_ID = "id";
private static final String KEY_LOCATION = "location";
private static final String KEY_COUNTRY = "country";
private SQLiteDatabase db;
public LocationDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_LOCATIONS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCATION
+ " TEXT, " + KEY_COUNTRY
+ " TEXT, " + " INTEGER)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void addLocation(LocationName location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LOCATION, location.getTaskName());
values.put(KEY_COUNTRY, location.getTaskCountry());
db.insert(TABLE_LOCATIONS, null, values);
}
public List<LocationName> getAllLocations() {
List<LocationName> locList = new ArrayList<LocationName>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LOCATIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
LocationName task = new LocationName();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setTaskCountry(cursor.getString(2));
// Adding contact to list
locList.add(task);
} while (cursor.moveToNext());
}
return locList;
}
public boolean deleteLocation(long rowId) {
return db.delete(TABLE_LOCATIONS, KEY_ID + "=" + rowId, null) > 0;
}
}
Then entry is not removed even when the app is restarted, the addLocation method for adding a row works fine.
LocationSettings Activity:
public class LocationSettings extends Activity {
protected static LocationDB db;
static List<LocationName> list;
MyAdapter adapt;
private static TextView name;
private ListView listView;
private static final int DLG_EXAMPLE1 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
db = new LocationDB(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.drawer_list_item, list);
listView = (ListView) findViewById(R.id.left_drawer);
listView.setAdapter(adapt);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
db.deleteTask(position);
adapt.remove(adapt.getItem(position));
}
}
});
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setOnTouchListener(touchListener);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
db.deleteTask(position);
adapt.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<LocationName> {
Context context;
List<LocationName> taskList = new ArrayList<LocationName>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<LocationName> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.drawer_list_item,parent, false);
name = (TextView) convertView.findViewById(R.id.text1);
}
LocationName current = taskList.get(position);
name.setText(current.getTaskName());
return convertView;
}
}
}
you forget to initialize db before calling delete method in deleteLocation.
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
Using the suggested following fragment of code from #ρяσѕρєяK:
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
has changed the signature of your method generating that error. I think that
public boolean deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) }) > 0;
}
will solve your problem.
Related
I have an input page which submits 4 strings into the helper. The helper is supposed to get the data and put it into the listView.
When I insert my data, the app doesnt crash but it leads me to the listview page with no rows inflated. The 4 data inputs are all strings and is submitted through a button. I'm not too sure what is wrong with my code. Would appreciate some advice :)
listview code
public class MyActivitiesPage extends AppCompatActivity {
private Cursor model = null;
private ListView list;
private dbHandler helper = null;
private activityAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activities_page);
helper = new dbHandler(this);
list = findViewById(R.id.listView);
model = helper.getall();
adapter = new activityAdapter(this, model, 0);
list.setAdapter(adapter);
}
public static class activityHolder {
private TextView activitytext;
private TextView datetext;
private TextView timetext;
private TextView addresstext;
activityHolder(View row) {
activitytext = row.findViewById(R.id.activitytext);
datetext = row.findViewById(R.id.datetext);
timetext = row.findViewById(R.id.timetext);
addresstext = row.findViewById(R.id.addresstext);
}
void populateFrom(Cursor c, dbHandler helper){
activitytext.setText(helper.getActi(c));
datetext.setText(helper.getDate(c));
timetext.setText(helper.getTime(c));
addresstext.setText(helper.getAddr(c));
}
}
class activityAdapter extends CursorAdapter {
activityAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
public void bindView(View view, Context context, Cursor cursor) {
activityHolder holder = (activityHolder) view.getTag();
holder.populateFrom(cursor, helper);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
activityHolder holder = new activityHolder(row);
row.setTag(holder);
return (row);
}
}
helper code
public class dbHandler extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "handler.db";
private static final int SCHEMA_VERSION = 1;
public dbHandler(#Nullable Context context){
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
//Will be called ones when the database is not created
db.execSQL("CREATE TABLE dbTable ( _id INTEGER PRIMARY KEY AUTOINCREMENT, acti TEXT, date TEXT, time TEXT, addr TEXT );");
}
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
//Will not be called upon until SCHEMA_VERSION increases
//For future upgrades
}
public Cursor getall() {
return (getReadableDatabase().rawQuery("SELECT * FROM dbTable", null));
}
public Cursor getById(String id) {
String[] args = {id};
return (getReadableDatabase().rawQuery("SELECT _id, acti, date, time, addr FROM dbTable WHERE _ID = ?", args));
}
public void insert(String acti, String date, String time, String addr) {
ContentValues cv = new ContentValues();
cv.put("acti", acti);
cv.put("date", date);
cv.put("time", time);
cv.put("addr", addr);
long result = getWritableDatabase().insert("dbTable", "firstvalue", cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
public void updateDetails(String id, String acti, String date, String time, String addr) {
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("acti", acti);
cv.put("date", date);
cv.put("time", time);
cv.put("addr", addr);
getWritableDatabase().update("dbTable", cv, " _ID = ?", args);
}
public String getID(Cursor c) { return (c.getString(0));}
public String getActi(Cursor c) { return (c.getString(1));}
public String getDate(Cursor c) { return (c.getString(2));}
public String getTime(Cursor c) { return (c.getString(3));}
public String getAddr(Cursor c) { return (c.getString(4));}
}```
I am developing an app for listing details in database. The listing is not working. but it is showing in log as fine. Why my recyclerview listling is not working. when i am using bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()) it shows error.
My codes are shown below.
SpeedDialViewActivity.java
public class SpeedDialViewActivity extends AppCompatActivity {
private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_dial_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ViewAdapter(beanList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareData();
}
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "speeddial";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_SPEED_DIAL = "speed_dial_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_SPEED_DIAL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
void addContact(Bean bean) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, bean.getName()); // Contact Name
values.put(KEY_PH_NO, bean.getNumber()); // Contact Phone
values.put(KEY_PH_NO, bean.getSpeeddial()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Bean getBean(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bean bean = new Bean(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return bean;
}
public List<Bean> getAllContacts() {
List<Bean> contactList = new ArrayList<Bean>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean contact = new Bean();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
ViewAdapter.java
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder> {
private List<Bean> beanList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, number, speeddial_number;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
number = (TextView) view.findViewById(R.id.number);
speeddial_number = (TextView) view.findViewById(R.id.speeddialNumber);
}
}
public ViewAdapter(List<Bean> beanList){
this.beanList = beanList;
}
#Override
public ViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.speeddial_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewAdapter.MyViewHolder holder, int position) {
Bean bean = beanList.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
holder.speeddial_number.setText(bean.getSpeeddial());
}
#Override
public int getItemCount() {
return beanList.size();
}
}
Bean.java
public class Bean{
private int id;
private String name;
private String number;
private String speeddial;
public Bean(int id, String name, String number, String speeddial) {
this.id=id;
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean(String name, String number, String speeddial) {
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getSpeeddial() {
return speeddial;
}
public void setSpeeddial(String speeddial) {
this.speeddial = speeddial;
}
}
The error is java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.appname/com.app.appname}: java.util.ConcurrentModificationException
Please help me
You are not adding the contacts you are fetching in the list and not doing notify data set changed. Change your onPrepare() method as follows
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
this.beanList.addAll(beanList);
mAdapter.notifyDatasetChanged();
}
pass the same list in prepareData(beanList) and add items in this list. And change your method to something likeprepareData(List<Bean> beanList>).after successfully adding, simply call mAdapter.notifyDataSetChanged() method so your adapter could know that some items have been added into the list.
You have not mention android:name in application tag in manifest file.
So you simple use context object or use SpeedDialViewActivity.this
DatabaseHandler handler = new DatabaseHandler(mContext);
or
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity{
CountriesDbAdapter myDB = new CountriesDbAdapter(this);
ListView listView;
public String lat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB.open();
myDB.deleteBank();
myDB.insertBank();
listView = (ListView) findViewById(R.id.listView);
toggleView();
WebView webView = (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "android");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/www/bank.html");
}
public void toggleView() {
final Cursor cursor = myDB.fetchBank();
final String[] arr = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
String data = cursor.getString(cursor.getColumnIndex("banks"));
arr[i] = data;
i++;
} while (cursor.moveToNext());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arr);
listView.setAdapter(adapter);
final StringBuffer buffer = new StringBuffer();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this, arr[position], Toast.LENGTH_SHORT).show();
Cursor res = myDB.answerRequest(arr[position]);
if (res.moveToFirst()) {
do {
lat=res.getString(2);
//buffer.append("lat: " + lat + "\n");
// buffer.append("long: " + res.getString(3) + "\n\n");
// showMessage("Data", buffer.toString());
//showMessage();
} while (res.moveToNext());
}
}
});
}
class WebViewJavaScriptInterface {
private Activity activity;
public WebViewJavaScriptInterface(Activity activity) {
this.activity = activity;
}
#JavascriptInterface
public String getData() {
//From Here how can i Return my Updated latitude to javascript file
}
}
CountriesDbAdapter.java
package com.example.student.finalone;
public class CountriesDbAdapter {
public static final String COLUMN_BANK = "banks";
public static final String COLUMN_BANKL = "banksl";
public static final String COLUMN_BANKLG = "bankslg";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "Vijayawada";
private static final String BANK_TABLE = "Bank";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_BANK = "CREATE TABLE if not exists " + BANK_TABLE + " (" + KEY_ROWID + " integer PRIMARY KEY autoincrement," + COLUMN_BANK + "," + COLUMN_BANKL + "," + COLUMN_BANKLG + ");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_BANK);
db.execSQL(DATABASE_BANK);
}
#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 " + BANK_TABLE);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long createBank(String b, double blat,double blong) {
ContentValues initialValues = new ContentValues();initialValues.put(COLUMN_BANK, b);initialValues.put(COLUMN_BANKL, blat);initialValues.put(COLUMN_BANKLG, blong);
return mDb.insert(BANK_TABLE, null, initialValues);
}
public boolean deleteBank() {
int doneDelete = 0;
doneDelete = mDb.delete(BANK_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertBank()
{
createBank("ServicebranchSBI",16.5109,80.651);createBank("StateBankofIndia",16.5011,80.6559);createBank("StateBankOfHyderabad",16.4966,80.6569);
createBank("BankOfBaroda",16.4974,80.6546);createBank("AndhraBank",16.5028,80.6396);createBank("AndhraBank",16.5062,80.648);
}
public Cursor fetchBank() {
String SelectQuery="select * from "+BANK_TABLE;
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor answerRequest(String position) {
String SelectQuery= "SELECT * FROM " + BANK_TABLE + " WHERE " + COLUMN_BANK + "='" + position + "'";
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
// String result="";
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
index.html
<html>
<head>
<script>
var showData = function() {
var data = android.getData();
window.alert("Hello! Data are: " + data + "; first = " + data);
}
</script>
</head>
<body>
<p>Lorem ipsem dolor et ceteris.</p>
<input type="button" value="Display data" onclick="showData()">
</body>
</html>
Iam trying to access the database from MainActivity.java and push it to the html file, Whenever i click on the html button it shows 0's in some cases iam getting error near the double lat declaration
You can achieve it in two ways:
1. Implement the Activity from OnItemClickListener and override onItemClick parallel to onCreate. Define double array a class variable and update that inside onItemClick
public class MainActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
}
2.Create a class MyItemClickListener and implement it from OnItemClickListener. Define double array a class variable
class MyItemClickListener implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
//Update the class member a1dToJson(lat).toString();//Here it returns all 0's
}
}
Change setOnItemClickListener to:
listView.setOnItemClickListener(new MyItemClickListener());
Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.
I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.