Storing parsed Rss items within SQLite - java

As my first Android project I'm trying to make an RSS reader app in which Listview items can be saved to SQLite, allowing them to be read offline. However, when trying to return news titles in a listView using a query with SimpleCursorAdapter, the listview displays the text "title", rather than the actual title of the news.
This seems to suggest that the items are not being stored to the database, or that the content values are not being properly assigned.
Can anybody see where i might be going wrong?
Thanks in advance!
RssItem.java
public class RssItem {
protected String _id;
public String title;
protected String link;
protected String page;
protected String completeTextLink;
protected String mainBody;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
//Title get/set
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//Link get/set
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
//CompleteTextLink get/set
public String getCompleteTextLink() {
return completeTextLink;
}
public void setCompleteTextLink(String completeTextLink) {
this.completeTextLink = completeTextLink;
}
//MainBody get/set
public String getMainBody() {
return mainBody;
}
public void setMainBody(String mainBody) {
this.mainBody = mainBody;
}
//Page get/set
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
#Override
public String toString() {
return title;
}}
MainActivity.java
public class MainActivity extends Activity {
private MainActivity local;
private DatabaseHandler db;
//Method to create main application view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//**************************create a button to move to the user's saved feeds screen*****************************
Button myFeedsButton = (Button) findViewById(R.id.myFeedsButton);
myFeedsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this, MyFeedsScreen.class));
}
});
//***************************************************************************************************************
//Create new instance of database handler
db = new DatabaseHandler(this);
//set local ref to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
//start download Rss task - execute method calls the
task.execute("http://feeds.bbci.co.uk/news/rss.xml?edition=uk");
//debug thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
}
//*******************************************************************************************************************
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem>>
{
#Override
protected List<RssItem> doInBackground(String... urls) {
//debug task thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
try {
//create a new reader
RssReader rssReader = new RssReader(urls[0]);
//Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("RssReaderApp", e.getMessage());
}
return null;
}//doInBackground
//is invoked on UI thread after background tasks are complete.
// Results of background task are passed here as a parameter
#Override
protected void onPostExecute(List<RssItem> result)
{
//Gets listview from main.xml
final ListView listItems = (ListView) findViewById(R.id.listMainView);
//Creates a new list adapter - displays an array of strings in listview
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local, android.R.layout.simple_list_item_1, result);
//Set list adapter for listView
listItems.setAdapter(adapter);
//OnItemClick listener set to allow user to access content from title
listItems.setOnItemClickListener(new ListListener(result, local));
//*******************************LONG CLICK FUNCTIONALITY******************************************
//Set new long click listener which should allow item to be stored to db
listItems.setLongClickable(true);
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
try {
db.open();
RssItem item = new RssItem();
item.title = "title";
item.link = "link";
item.completeTextLink ="completeTextLink";
item.page = "page";
db.insertRssItem(item);
db.close();
} catch (SQLException e)
{
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Item saved in My Feeds!", Toast.LENGTH_SHORT).show();
return true;
}
});
}//onPostExecute
}}//class
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "news_db";
public static SQLiteDatabase db;
private static final int DATABASE_VERSION = 32;
protected static final String TABLE_NEWS = "news";
private static final String TAG = "TAG";
private static final String TAG1 = "TAG1";
static String columnTitle = "title";
protected static final String _id = "_id";
//Methods for tables
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_NEWS = "CREATE TABLE " + TABLE_NEWS + "(_id VARCHAR, title TEXT, link TEXT, completeTextLink TEXT, mainBody Text, page TEXT)";
db.execSQL(CREATE_TABLE_NEWS);
Log.w(TAG, "Database has been created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWS);
onCreate(db);
}
public void open() throws SQLException {
db = this.getWritableDatabase();
}
//Method to insert new rssItem object to the database
public void insertRssItem(RssItem rssItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", rssItem._id);
contentValues.put("title", rssItem.title);
contentValues.put("link", rssItem.link);
contentValues.put("mainBody", rssItem.mainBody);
contentValues.put("completeTextLink", rssItem.completeTextLink);
contentValues.put("page", rssItem.page);
db.insert(TABLE_NEWS, "title", contentValues);
Log.d(TAG1, "ITEM SAVED IN DATABASE!!!");
}//insert item method
//Method to return all news for a given item
public List<RssItem> getAllNewsForItem(String page) {
List<RssItem> SavedNewsList = new ArrayList<RssItem>();
Cursor cursor = db.rawQuery("select _id, completeTextLink, title, link, mainBody, page" +
" FROM " + TABLE_NEWS + " where page = ?", new String[]{page});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
RssItem rssItem = new RssItem();
rssItem._id = cursor.getString(0);
rssItem.completeTextLink = cursor.getString(1);
rssItem.title = cursor.getString(2);
rssItem.link = cursor.getString(3);
rssItem.mainBody = cursor.getString(4);
rssItem.page = page;
SavedNewsList.add(rssItem);
cursor.moveToNext();
}
cursor.close();
return SavedNewsList;
}
//get data from database for listview
public Cursor getData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NEWS, null);
return cursor;
}}
MyFeedsScreen.java
public class MyFeedsScreen extends ListActivity {
DatabaseHandler dbHandler;
SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_feeds_screen);
dbHandler = new DatabaseHandler(MyFeedsScreen.this);
displayList();
}
public void displayList() {
dbHandler.getWritableDatabase();
dbHandler = new DatabaseHandler(this);
Cursor cursor = dbHandler.getData();
String from[] = new String[]{dbHandler.columnTitle};
int to[] = new int[]{R.id.textView1};
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to, 0);
ListView lv = getListView();
lv.setAdapter(dataAdapter);
}}

You should call getItemAtPosition(int position) from within your long-press listener. That will get you the Object from the collection that backs the ListView, in this case, the article from your RssReader that the user long-pressed upon. Sorta like:
...
db.open();
RssArticleThing fromList = (RssArticleThing) listItems.getItemAtPosition(position);
RssItem item = new RssItem();
item.title = fromList.title;
...
http://developer.android.com/reference/android/widget/AdapterView.html#getItemAtPosition(int)

Related

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

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

pass data from one activity to another and save it

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

Database refusing to delete item

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.

Android Studio can't insert data into sqlitedatabase

I'm doing a small project for my mobile app subject. I need to link it with sqlitedatabase.
I've been the tutorial at the Youtube, I followed the tutorial step by step. I didn't got any error from the code.
I need to insert the value into the db and display it back but the user input didn't inserted into db so I couldn't display the data from the DB.
I hope someone could help me. I've been stuck for 2 days because of this problem with no error display.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "STUDENT.DB";
//create table
public static final String TABLE_STUDENT = "STUDENT_TABLE";
public static final String COL_STD_ID = "STD_ID";
public static final String COL_STD_NAME = "STD_NAME";
public static final String COL_STD_EMAIL = "STD_EMAIL";
public static final String COL_STD_ADDRESS = "STD_ADDRESS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
Log.e("DATABASE OPERATION","Database created/opend...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STUDENT +" (STD_ID INTEGER PRIMARY KEY AUTOINCREMENT,STD_NAME TEXT,STD_EMAIL TEXT, STD_ADDRESS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_STUDENT );
onCreate(db);
}
public boolean insertData(String STD_NAME, String STD_EMAIL, String STD_ADDRESS)
{
SQLiteDatabase db = this.getWritableDatabase();
//get the data from user into db
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STD_NAME,STD_NAME);
contentValues.put(COL_STD_EMAIL,STD_EMAIL);
contentValues.put(COL_STD_ADDRESS,STD_ADDRESS);
//SEE WHETHER THE DATA INSERT INTO DB OR NOT
//IF RETURN -1, DATA NOT SUCCESSFUL INSERTED
long result = db.insert(TABLE_STUDENT,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + TABLE_STUDENT,null);
return result;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etstdName, etstdEmail, etstdAddress;
Button btnInsertData, btnViewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etstdName = (EditText)findViewById(R.id.etstdName);
etstdEmail = (EditText)findViewById(R.id.etstdEmail);
etstdAddress = (EditText)findViewById(R.id.etstdEmail);
btnViewData = (Button)findViewById(R.id.btnViewData);
btnInsertData = (Button)findViewById(R.id.btnInsertData);
InsertStdData();
}
// I think i get stuck at here but theres not error display at InsertStdData() methid
public void InsertStdData() {
btnInsertData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etstdName.getText().toString(),
etstdEmail.getText().toString(),
etstdAddress.getText().toString());
if(isInserted = true)
Toast.makeText(MainActivity.this,"Data successfully inserted.",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not successfully inserted.",Toast.LENGTH_LONG).show();
}
});
}
public void viewStdData(View view) {
Cursor result = myDB.getAllData();
if(result.getCount() == 0) {
//showmessage method
showMessage("ERROR", "NO DATA FOUND");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()){
buffer.append("STD_ID : "+result.getString(0)+"\n");
buffer.append("STD_NAME : "+result.getString(1)+"\n");
buffer.append("STD_EMAIL : "+result.getString(2)+"\n");
buffer.append("STD_ADDRESS :"+result.getString(3)+"\n\n");
}
//show all data
showMessage("DATA",buffer.toString());
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
You called InsertStdData() but you didnt call viewStdData(View view) in your MainActivity.

SQLLite update() not working, no errors in logcat. How can I diagnose the issue?

I have a SQLite Database of Web site data (ftp address, username, password, port, homedir, url etc). I can add records to the table but can't seem to update them.
I created a SiteManager Activity that loads each row and creates a WebSite object from each row. The WebSite's properties are loaded into EditTexts. The person can edit the properties and than the Update button SHOULD update the table row but it doesn't. Logcat doesn't give any errors so I'm completely at a loss, not sure where to start.
public class SiteManager extends Activity {
private DBAdapter myDb;
private EditText siteManFTPAddress;
private EditText siteManFTPUsername;
private EditText siteManFTPPassword;
private EditText siteManFTPPort;
private EditText siteManURL;
private EditText siteManHome;
private ImageView favIcon;
public ListView site_list;
private Button openBtn;
private Button siteManUpdateBtn;
private int _rowId;
private String _name;
private String _remoteHomeDir;
private int _isLive;
private String _address;
private String _username;
private String _password;
private int _port;
private String _url;
private boolean _status = false;
private String siteFolder;
private List<WebSite> model = new ArrayList<WebSite>();
private ArrayAdapter<WebSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
siteManFTPAddress = (EditText) findViewById(R.id.siteManFTPAdd);
siteManFTPUsername = (EditText) findViewById(R.id.siteManFTPUser);
siteManFTPPassword = (EditText) findViewById(R.id.siteManFTPPass);
siteManFTPPort = (EditText) findViewById(R.id.siteManFTPPort);
siteManURL = (EditText) findViewById(R.id.siteManURL);
siteManHome = (EditText) findViewById(R.id.siteManHome);
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
File rootDir = new File(Environment
.getExternalStorageDirectory() + "/My Webs");
final WebSite item = (WebSite) parent
.getItemAtPosition(position);
_name = item.getName();
siteFolder = rootDir.toString() + "/" + _name;
_remoteHomeDir = item.getHomeDir();
_isLive = item.isLive();
String tmpaddress = item.getAddress();
_address = tmpaddress;
siteManFTPAddress.setText(_address);
String tmpuser = item.getUsername();
_username = tmpuser;
siteManFTPUsername.setText(_username);
String tmppass = item.getPassword();
_password = tmppass;
siteManFTPPassword.setText(_password);
int tmpport = item.getPort();
_port = tmpport;
String portString = Integer.toString(tmpport);
siteManFTPPort.setText(portString);
String tmpURL = item.getUrl();
_url = tmpURL;
siteManURL.setText(_url);
String tmpHome = item.getHomeDir();
_remoteHomeDir = tmpHome;
siteManURL.setText(_remoteHomeDir);
}
});
openBtn = (Button) findViewById(R.id.openSiteBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("siteopen", "siteopen");
returnResult.putExtra("sitename", _name);
returnResult.putExtra("sitehome", siteFolder);
returnResult.putExtra("sitelive", _isLive);
returnResult.putExtra("siteremotehome", _remoteHomeDir);
returnResult.putExtra("siteaddress", _address);
returnResult.putExtra("siteusername", _username);
returnResult.putExtra("sitepassword", _password);
returnResult.putExtra("siteport", _port);
returnResult.putExtra("url", _url);
setResult(2, returnResult);
finish();
}
});
siteManUpdateBtn = (Button)findViewById(R.id.siteManFTPUpdate);
siteManUpdateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_address = siteManFTPAddress.getText().toString();
_username = siteManFTPUsername.getText().toString();
_password = siteManFTPPassword.getText().toString();
String port = siteManFTPPort.getText().toString();
_port = Integer.parseInt(port);
Toast.makeText(SiteManager.this, "Update", Toast.LENGTH_LONG).show();
myDb.updateRow(_rowId, _name, _name, _isLive, _address, _username, _password, _port, _url);
model.clear();
adapter.notifyDataSetChanged();
displayRecords();
}
});
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
if (c.moveToFirst()) {
do {
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
int keyHomeIndex = c.getColumnIndex(DBAdapter.KEY_HOME);
_remoteHomeDir = c.getString(keyHomeIndex);
int keyLiveIndex = c.getColumnIndex(DBAdapter.KEY_LIVE);
_isLive = c.getInt(keyLiveIndex);
int keyAddressIndex = c.getColumnIndex(DBAdapter.KEY_ADDRESS);
_address = c.getString(keyAddressIndex);
int keyUsernameIndex = c.getColumnIndex(DBAdapter.KEY_USERNAME);
_username = c.getString(keyUsernameIndex);
int keyPassIndex = c.getColumnIndex(DBAdapter.KEY_PASSWORD);
_password = c.getString(keyPassIndex);
int keyPortIndex = c.getColumnIndex(DBAdapter.KEY_PORT);
_port = c.getInt(keyPortIndex);
int keyUrlIndex = c.getColumnIndexOrThrow(DBAdapter.KEY_URL);
_url = c.getString(keyUrlIndex);
WebSite sitesFromDB = new WebSite(_rowId, _name, _remoteHomeDir,
_isLive, _address, _username, _password, _port, _url);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
if(adapter.isEmpty()){
}
} while (c.moveToNext());
}
c.close();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
adapter.notifyDataSetChanged();
}
class SiteAdapter extends ArrayAdapter<WebSite> {
private final List<WebSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<WebSite> objects) {
super(context, R.id.sitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.sitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
DBAdapter.java
public boolean updateRow(long rowId, String name, String homedir,
int islive, String address, String username, String password,
int port, String url) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_HOME, homedir);
newValues.put(KEY_LIVE, islive);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_URL, url);
// newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
The value _rowId is only ever set inside the displayRecordSet method where you iterate through the results from the database and set the _rowId:
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
This piece of code seems rather random to me. First you get the columnIndex for the rowId, next you get the index for this specific row and then you get the value of the column with index rowId and then set the _rowId field from this value.
I couldn't tell if the SQLite Database would be so nasty as to just return 0 if there isn't any value in the specified column, but that could definately be the problem.
So every time you get the _rowId set, it might just be set to 0 and when you try to update a row where rowId = 0 nothing happens, as no index in the database can be 0.
See the official documentation about getInt(columnIndex).
To diagnose issues like this, I usually add debug logs into the app. You can see these in your logcat. Log.d("tag", "there is something happening here: " + value);

Categories

Resources