I have been building a simple note app and have successfully SQlite database and loaders to load data on a listview. Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how. I've search but mainly tutorials are for Content provider, I read this: http://developer.android.com/reference/android/content/AsyncTaskLoader.html#q=addAll
but not understand much because they use BroadcastReceiver to get change on sd card.
Im all ears to any suggestion and thanks for any help in advance!
this is my code: WhiteNote.java
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
noteListAdapter=new NoteListAdapter(context, new ArrayList<NoteItems>());
note_database.open();
getLoaderManager().initLoader(0, null,WhiteNote.this);
note_database.close();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.dbnoteListAdapter);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context,note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context, data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_noteitems= new ArrayList<NoteItems>();
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
loader_db = db;
loader_noteitems=loader_db.get_NoteListArray(loader_noteitems,loader_db);
}
#Override
protected void onStartLoading() {
if (loader_noteitems != null) {
deliverResult(loader_noteitems); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open();
ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
loader_db.get_NoteListArray(note_items,loader_db);
loader_db.close();
return note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
if (isReset()) {
if (data != null) {
onReleaseResources(data);
}
}
ArrayList<NoteItems> oldNotes = loader_noteitems;
loader_noteitems = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldNotes != null) {
onReleaseResources(oldNotes);
}
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_noteitems = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_noteitems = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
my NoteDatabase.java
public class NoteDatabase {
private static final String DATABASE_NAME = "DB_NOTE";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NOTE = "NOTE";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TOPIC = "Topic";
public static final String COLUMN_NOTECONTENT = "Content";
public static final String COLUMN_NAME = "Name";
public NoteListAdapter dbnoteListAdapter;
private static Context my_context;
static SQLiteDatabase note_sqldb;
private OpenHelper noteopenHelper;
public NoteDatabase(Context c){
NoteDatabase.my_context = c;
}
public NoteDatabase open() throws SQLException{
noteopenHelper = new OpenHelper(my_context);
note_sqldb = noteopenHelper.getWritableDatabase();
return this;
}
public void close(){
noteopenHelper.close();
}
public long createData(String chude_note, String noidung_note) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TOPIC, chude_note);
cv.put(COLUMN_NOTECONTENT, noidung_note);
cv.put(COLUMN_NAME, "by Black");
return note_sqldb.insert(TABLE_NOTE, null, cv);
}
public String getData() {
String[] columns = new String[] {COLUMN_ID,COLUMN_TOPIC,COLUMN_NOTECONTENT,COLUMN_NAME};
Cursor c = note_sqldb.query(TABLE_NOTE, columns, null, null, null, null, null);
/*if(c==null)
Log.v("Cursor", "C is NULL");*/
String result="";
int iRow = c.getColumnIndex(COLUMN_ID);
int iTopic = c.getColumnIndex(COLUMN_TOPIC);
int iContent = c.getColumnIndex(COLUMN_NOTECONTENT);
int iOwner = c.getColumnIndex(COLUMN_NAME);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result +" \n"+ c.getString(iRow)
+ "\n - Topic: " + c.getString(iTopic)
+ "\n - Content: " + c.getString(iContent)
+ "\n - Owner: " + c.getString(iOwner) + "\n";
}
c.close();
//Log.v("Result", result);
return result;
}
public Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (note_sqldb.isOpen()) {
note_sqldb.close();
}
note_sqldb = noteopenHelper.getWritableDatabase();
c1 = note_sqldb.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
public void get_NoteListAdapter() {
ArrayList<NoteItems> noteList = new ArrayList<NoteItems>();
noteList.clear();
open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteList.add(one_rowItems);
}
c1.close();
close();
dbnoteListAdapter = new NoteListAdapter(my_context, noteList);
}
public ArrayList<NoteItems> get_NoteListArray(ArrayList<NoteItems> noteitems_list,NoteDatabase db) {
noteitems_list.clear();
db.open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteitems_list.add(one_rowItems);
}
c1.close();
db.close();
return noteitems_list;
}
public int deleteNote(String topic) {
return note_sqldb.delete(TABLE_NOTE, COLUMN_TOPIC + "='" + topic + "'", null);
}
public int deleteAllNote() {
return note_sqldb.delete(TABLE_NOTE, null, null);
}
}
Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how.
There is no way to make that happen automatically. Either:
Something tells the loader that the data changed, so it knows to reload, or
The Loader is the one that is doing the "add, change, or delete a note in database"
I went with the latter approach with my CWAC-LoaderEx project and its SQLiteCursorLoader.
Related
I've created a database to store ExoPlayer's seek time so when the user tries to play the same content, if it is in the database, then it will ask the user to resume or start again but getting NullPointerException.
Here's the Database:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydata.db";
private static final String EPISODE_TABLE_NAME = "episode_data";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_EPISODE_DATA_TABLE());
}
private String CREATE_EPISODE_DATA_TABLE() {
return "CREATE TABLE IF NOT EXISTS episode_data (id TEXT,timestamp TEXT)";
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS episode_data");
onCreate(db);
}
public String getEpisodeData(String string2) {
SQLiteDatabase sQLiteDatabase = this.getReadableDatabase();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("SELECT * FROM episode_data WHERE id= ");
stringBuilder.append(string2);
Cursor cursor = sQLiteDatabase.rawQuery(stringBuilder.toString(), null);
String string3 = null;
if (cursor != null) {
boolean bl = cursor.moveToLast();
string3 = null;
if (bl) {
string3 = cursor.getString(cursor.getColumnIndex("timestamp"));
}
cursor.close();
}
return string3;
}
public long insertEpisodeData(String string2, String string3) {
SQLiteDatabase sQLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("id", string2);
contentValues.put("timestamp", string3);
long l = sQLiteDatabase.replace(EPISODE_TABLE_NAME, null, contentValues);
sQLiteDatabase.close();
return l;
}
}
The activity where it stores the data from and also crashes:
public class ShowsDetailsActivity extends AppCompatActivity {
public String episodeid;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series_details);
databaseHelper = new DatabaseHelper(this);
// My rest of the code
}
public void iniMoviePlayerForEpisode(EpiModel epiModel,Context context){
ShowsDetailsActivity.epiModel =epiModel;
String type=epiModel.getServerType();
if (type.equals("embed") || type.equals("vimeo") || type.equals("gdrive")){
isVideo=false;
initWeb(epiModel.getStreamURL());
}else {
isVideo=true;
initVideoPlayer(epiModel.getStreamURL(),context,type);
}
}
}
public void setMediaUrlForTvSeries(String url, String season, String episod, String episode_id) {
mediaUrl = url;
this.season = season;
this.episod = episod;
this.episodeid = episode_id;
}
public void initVideoPlayer(String url, Context context, String type) {
progressBar.setVisibility(VISIBLE);
if (player != null) {
player.release();
}
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new
AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new
DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
simpleExoPlayerView.setPlayer(player);
player.prepare(mediaSource, true, false);
player.addListener(new Player.DefaultEventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playWhenReady && playbackState == Player.STATE_READY) {
isPlaying = true;
progressBar.setVisibility(View.GONE);
} else if (playbackState == Player.STATE_READY) {
progressBar.setVisibility(View.GONE);
isPlaying = false;
if (player != null) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("episode id: ");
stringBuilder.append(episodeid);
stringBuilder.append(" TimeStamp: ");
stringBuilder.append(player.getCurrentPosition() / 1000L);
databaseHelper.insertEpisodeData(episodeid, String.valueOf((long)player.getCurrentPosition()));
}
} else if (playbackState == Player.STATE_BUFFERING) {
isPlaying = false;
progressBar.setVisibility(VISIBLE);
} else {
isPlaying = false;
if (player != null) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("episode id: ");
stringBuilder.append(episodeid);
stringBuilder.append(" TimeStamp: ");
stringBuilder.append(player.getCurrentPosition() / 1000L);
databaseHelper.insertEpisodeData(episodeid, String.valueOf((long)player.getCurrentPosition()));
}
}
}
});
String getPlayed = databaseHelper.getEpisodeData(episodeid);
if (getPlayed != null) {
showResumeAlert();
return;
}
player.setPlayWhenReady(true);
}
private void showResumeAlert () {
new AlertDialog.Builder(this)
.setTitle("Do you want to resume from where you left ?")
.setPositiveButton("Resume", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getPlayed = databaseHelper.getEpisodeData(episodeid);
if (getPlayed != null) {
player.seekTo(Long.parseLong(getPlayed));
player.setPlayWhenReady(true);
}
}
})
.setNegativeButton("Start Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
player.setPlayWhenReady(true);
}
})
.setCancelable(false)
.show();
}
// My rest of the code
}
The adapter:
public class DirectorApater extends RecyclerView.Adapter<DirectorApater.OriginalViewHolder> {
private List<EpiModel> items;
private Context ctx;
int selectedPosition=-1;
private int seasonNo;
public DirectorApater(Context context, List<EpiModel> items,String name, int seasonNo) {
ArrayList<EpiModel> arrayList=new ArrayList<>();
for(int i=0;i<items.size();i++){
if(items.get(i).getSeson().equals(name)){
arrayList.add(items.get(i));
}
}
items.clear();
this.items = arrayList;
this.seasonNo = seasonNo;
ctx = context;
}
#Override
public DirectorApater.OriginalViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
DirectorApater.OriginalViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_director_name, parent, false);
vh = new DirectorApater.OriginalViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final DirectorApater.OriginalViewHolder holder, final int position) {
final EpiModel obj = items.get(position);
holder.llEpi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition=position;
notifyDataSetChanged();
((ShowsDetailsActivity)ctx).setMediaUrlForTvSeries(obj.getStreamURL(), obj.getSeson(), obj.getEpi(), obj.getEpisode_id());
if (!castSession) {
new ShowsDetailsActivity().iniMoviePlayerForEpisode(obj,ctx);
} else {
((ShowsDetailsActivity)ctx).showQueuePopup(ctx, holder.llEpi, ((ShowsDetailsActivity)ctx).getMediaInfo());
}
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
// some code
public OriginalViewHolder(View v) {
super(v);
// some code
}
}
So basically when a user clicks on the recyclerview item, it passes the data to the activity class "(ShowsDetailsActivity)ctx).setMediaUrlForTvSeries(obj.getStreamURL(), obj.getSeson(), obj.getEpi(), obj.getEpisode_id());"
App works fine without
String getPlayed = databaseHelper.getEpisodeData(episodeid);
if (getPlayed != null) {
showResumeAlert();
return;
}
in ShowsDetailsActivity class but crashes with this error log when I add it:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String
com.myapp.db.DatabaseHelper.getEpisodeData(java.lang.String)' on a null object reference
You are calling the iniMoviePlayerForEpisode method here:
new ShowsDetailsActivity().iniMoviePlayerForEpisode(obj,ctx);
but at that point onCreate was not yet called and thus your databaseHelper is still null. Check the reference i linked: onCreate is called when your Activity starts, not when the object is created.
I'm making a project in Android/Java. I have an activity with a listview that displays values from a database and a remove button. For the moment, each row of this list view consists of a checktextview. This last one displays the name of an element of the database. I want to select different elements (with the check text view) and then if I press the remove button, all the selected elements have to be removed from the list and from database. In the following I put the essential parts of my classes. I already done most of the work.
This is my activity:
public class ShoppingListActivity extends AppCompatActivity {
// Variables for the management of the database
private DBManagerShoppingList dbShoppingList;
private Cursor crs;
// List view for the shopping list elements
private ListView shoppingListListView;
private ShoppingListViewAdapter shoppingListViewAdapter;
// Generic variables
private String selectedShoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
// Find of the useful widgets
shoppingListListView = findViewById(R.id.listViewSelShoppingList);
shoppingListsSpinner = findViewById(R.id.spinnerShoppingLists);
selectedShoppingList = "List_1";
populateListView();
}
// Populate list view from database
public void populateListView() {
// Database management
dbShoppingList = new DBManagerShoppingList(this, selectedShoppingList);
crs = dbShoppingList.query();
new Handler().post(new Runnable() {
#Override
public void run() {
shoppingListViewAdapter = new ShoppingListViewAdapter(ShoppingListActivity.this, crs, 0);
shoppingListListView.setAdapter(shoppingListViewAdapter);
}
});
}
// Remove selected elements
public void removeSelectedElements(View btnRemove) {
// TODO
}
}
This is my custom adapter:
public class ShoppingListViewAdapter extends CursorAdapter {
private LayoutInflater layoutInflater;
private List<Integer> elementsPosArrayList = new ArrayList<>();
private HashMap<String, Integer> elementsMap = new HashMap<>();
public ShoppingListViewAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return layoutInflater.inflate(R.layout.list_view_row, viewGroup, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
elementsMap.put(elementName, cursor.getPosition());
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementsPosArrayList.add(elementsMap.get(checkBoxElementName.getText().toString()));
} else {
elementsPosArrayList.remove(elementsMap.get(checkBoxElementName.getText().toString()));
}
}
});
}
public long getElementId(Cursor crs, int position) {
crs.moveToPosition(position);
return crs.getLong(crs.getColumnIndex(DBFieldsShoppingList.FIELD_ID));
}
public List<Integer> getElementsPosArrayList() {
return elementsPosArrayList;
}
}
Classes for the database management are the following:
DBHelper:
public class DBHelperShoppingList extends SQLiteOpenHelper {
private String DBName;
public DBHelperShoppingList(#Nullable Context context, int dbVersion, String dbName) {
super(context, dbName, null, dbVersion);
this.DBName = dbName;
}
#Override
public void onCreate(SQLiteDatabase shoppingListDB) {
String q = "CREATE TABLE " + DBFieldsShoppingList.FIELD_TABLE_NAME +
" ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
DBFieldsShoppingList.FIELD_ELEMENT_NAME + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_TYPE + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_QUANT + " TEXT)";
shoppingListDB.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase shoppingListDB, int oldVersion, int newVersion) {}
}
Class for the fields of the database:
public class DBFieldsShoppingList {
public static final String FIELD_ID = "_Id";
public static final String FIELD_TABLE_NAME = "Shopping_List";
public static final String FIELD_ELEMENT_NAME = "Element_Name";
public static final String FIELD_ELEMENT_TYPE = "Element_Type";
public static final String FIELD_ELEMENT_QUANT = "Element_Quant";
}
Class database manager:
public class DBManagerShoppingList {
private DBHelperShoppingList dbHelperShoppingList;
public DBManagerShoppingList(Context ctx, String shoppingListName) {
dbHelperShoppingList = new DBHelperShoppingList(ctx, 1, shoppingListName);
}
public void dbSave(String elementName, String elementType, String elementQuantity) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_NAME, elementName);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_TYPE, elementType);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_QUANT, elementQuantity);
try {
db.insert(DBFieldsShoppingList.FIELD_TABLE_NAME, null, cv);
} catch (SQLiteException ignored) {}
}
public boolean deleteElement(long id) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ID + "=?", new String[]{Long.toString(id)})>0;
} catch(SQLiteException exc) {
return false;
}
}
public static void deleteDB(Context ctx, String DBName) {
ctx.deleteDatabase(DBName);
}
public Cursor query() {
Cursor crs;
try {
SQLiteDatabase db = dbHelperShoppingList.getReadableDatabase();
crs = db.query(DBFieldsShoppingList.FIELD_TABLE_NAME, null, null, null, null, null, null, null);
} catch (SQLiteException exc) {
return null;
}
return crs;
}
}
I tought, in bindView method of the adapter class, to save a map between element name and its position. Then, to create a list of the element names of the checked elements. In this way, I can know the positions of the checked elements, from the map. Now, I have to get indexes of the checked elements, in order to remove them from database, with delete method of the database manager class.
How can I solve this problem? If my structure is not correct, say me how to change.
Thank you very much in advance.
Marco
Hy to everybody,
I found the solution. In database manager class, I changed the delete method in the following way:
public boolean deleteElement(String elementName) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ELEMENT_NAME + "=?", new String[]{(elementName)})>0;
} catch(SQLiteException exc) {
return false;
}
}
This allows, to search by name in database.
In adapter class, I removed the map, and I wrote an arraylist of string, where I put name of the checked elements:
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementNamesArrayList.add(checkBoxElementName.getText().toString());
} else {
elementNamesArrayList.remove(checkBoxElementName.getText().toString());
}
}
});
}
Finally, in the activity class, the remove method is the following:
public void removeSelectedElements(View btnRemove) {
List<String> elementNamesArrayList = shoppingListViewAdapter.getElementNamesArrayList();
for (String item: elementNamesArrayList) {
dbShoppingList.deleteElement(item);
}
populateListView();
}
In this way I solved my problem.
Marco
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.
I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter 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 name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// 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 initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// 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 name, String address,
String username, String password, int port, int passive) {
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_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
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);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> 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);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
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) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, 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.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);
I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.