I have a ListView which is populated by Objects from a JSON file.
I want to sort the ListView alphabetically based on this object: vidLocation.name
How am I able to perform that?
Here's my ListView class:
public class ProjectsList extends ListActivity implements OnItemClickListener, VideoLocationReceiver{
/** Called when the activity is first created. */
private VideoLocation[] videoLocations = null;
private VideoLocationAdapter videoLocationAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
doSync();
//storeSharedPrefs();
ListView lv = getListView();
lv.setOnItemClickListener(this);
videoLocationAdapter = new VideoLocationAdapter(ProjectsList.this,
R.layout.listitems,
new VideoLocation[0]);
lv.setAdapter(videoLocationAdapter);
//CREATE VideoLocation[] from Database!
JsonDB dbhelper = new JsonDB(ProjectsList.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.beginTransaction();
videoLocations = dbhelper.getVideoLocations(db);
db.setTransactionSuccessful();//end transaction
db.endTransaction();
db.close();
}
#Override
public void onResume(){
super.onResume();
DBSync.setVideoLocationReceiver(ProjectsList.this);
}
#Override
public void onPause(){
super.onResume();
DBSync.setVideoLocationReceiver(null);
}
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Intent listIntent = new Intent(this, ProjectDetailsActivity.class);
VideoLocation vidLocation = videoLocations[position];
listIntent.putExtra("documentary_video_url",vidLocation.documentary_video_url);
listIntent.putExtra("spendino.de.ProjectDetail.position",position);
startActivity(listIntent);
}
protected void storeSharedPrefs() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("first-time", true)) {
doSync();
prefs.edit().putBoolean("first-time", false).commit(); // record the fact that the app has been started at least once
}
}
void doSync() {
Intent serviceIntent = new Intent(this, DBSync.class);
startService(serviceIntent);
}
public class VideoLocationAdapter extends ArrayAdapter<VideoLocation> {
public ImageLoader imageLoader;
ImageLoader loader = null;
public VideoLocationAdapter(Context context, int resource, VideoLocation[] vidLocs) {
super(context, resource, vidLocs);
ProjectsList.this.videoLocations = vidLocs;
loader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = ProjectsList.this.getLayoutInflater().inflate(R.layout.listitems, null, true);
}
VideoLocation vidLocation = videoLocations[position];
ImageView v = (ImageView)convertView.findViewById(R.id.image);
String url = vidLocation.documentary_thumbnail_url;
v.setTag(url);
loader.DisplayImage(url, ProjectsList.this, v);
TextView titleView = (TextView)convertView.findViewById(R.id.txt_title);
titleView.setText(vidLocation.name);
return convertView;
}
#Override
public int getCount(){
return videoLocations==null?0:videoLocations.length;
}
#Override
public VideoLocation getItem(int position){
return videoLocations[position];
}
#Override
public boolean hasStableIds(){
return true;
}
#Override
public boolean isEnabled(int position){
return true;
}
#Override
public long getItemId(int position){
return videoLocations[position].id;
}
public void setVideoLocationData(VideoLocation[] newData){
ProjectsList.this.videoLocations = newData;
VideoLocationAdapter.this.notifyDataSetChanged();
}
}
#Override
public void receivedVideoLocationData(VideoLocation[] vidLocs) {
final VideoLocation[] locs = vidLocs;
if (vidLocs==null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//show popup and inform about missing network
}
});
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
videoLocationAdapter.setVideoLocationData(locs);
Log.d("ProjectsList", "updating video locations...");
}
});
}
}
}
Have you set DEFAULT_SORT_ORDER in your query? If not, by doing so you can easily have it list alphabetically.
Use Predefined sorting technique
I see that you are fetching your data from DB. In sqllite query you can give the sort order.
I couldnt find the line here where you are querying db. Trying something like this
public Cursor fetchRow(String tableName, String[] columnslist,
String condition) throws SQLException {
Log.i("DB Fetch arg ", condition);
Cursor mCursor = mDb.query(true, tableName, columnslist, condition,
null, null, null, "_id" + " DESC",null);
if (mCursor != null) {
Log.i("DB", "NOT NULL "+mCursor.getCount());
mCursor.moveToFirst();
}
return mCursor;
}
Related
I am updating my sqlite database using cursorloader inside a recyclerview where i do it by checking checkbox, the value updated but somehow the view became a mess. some row also checked but the value still 0 which should be not checked. This also happen when I insert a new row.
here is my MainActivity where i Updated the database
public class MainActivity extends AppCompatActivity implements
TaskAdapter.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor>{
private TaskAdapter mAdapter;
private FloatingActionButton floatingActionButton;
private ArrayList<Task> task = new ArrayList<>();
private static final int TASKS_LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAdapter = new TaskAdapter(this);
mAdapter.setOnItemClickListener(this);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
/* Click events in floating action button */
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddTaskActivity.class);
startActivity(intent);
}
});
//initialize the loader
getSupportLoaderManager().initLoader(TASKS_LOADER_ID, null, this);
}
#Override
protected void onResume() {
super.onResume();
Log.v("dipanggil", "dipanggil jka");
// re-queries for all tasks
getSupportLoaderManager().restartLoader(TASKS_LOADER_ID, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/* Click events in RecyclerView items */
#Override
public void onItemClick(View v, int position) {
//TODO: Handle list item click event
Intent intent = new Intent(this, TaskDetailActivity.class);
/*b.putLong("ID", task.get(position).getId());
b.putString("DESCRIPTION", task.get(position).getDescription());
b.putInt("PRIORITY", task.get(position).getPriority());
b.putInt("COMPLETE", task.get(position).getComplete());
b.putLong("DUEDATE", task.get(position).getDueDateMillis());*/
intent.putExtra("ID", String.valueOf(task.get(position).getId()));
startActivity(intent);
Log.v("testti", ""+v.getTag()+" apakah sama "+task.get(position).getId());
}
/* Click events on RecyclerView item checkboxes */
#Override
public void onItemToggled(boolean active, int position) {
//TODO: Handle task item checkbox event
ContentValues values = new ContentValues();
String stringId = String.valueOf(task.get(position).getId());
Log.v("test = ", ""+task.get(position).getId());
Uri uri = DatabaseContract.CONTENT_URI;
uri = uri.buildUpon().appendPath(stringId).build();
if(active) {
Log.v("test","tersentuh");
//values.put(DatabaseContract.TaskColumns.IS_COMPLETE, 1);
values.put(DatabaseContract.TaskColumns._ID, task.get(position).getId());
values.put(DatabaseContract.TaskColumns.DESCRIPTION, task.get(position).getDescription());
values.put(DatabaseContract.TaskColumns.IS_PRIORITY, task.get(position).getPriority());
values.put(DatabaseContract.TaskColumns.IS_COMPLETE, 1);
values.put(DatabaseContract.TaskColumns.DUE_DATE, task.get(position).getDueDateMillis());
getContentResolver().update(uri,
values,
null,
null);
}else{
Log.v("test","tidak tersentuh");
values.put(DatabaseContract.TaskColumns._ID, task.get(position).getId());
values.put(DatabaseContract.TaskColumns.DESCRIPTION, task.get(position).getDescription());
values.put(DatabaseContract.TaskColumns.IS_PRIORITY, task.get(position).getPriority());
values.put(DatabaseContract.TaskColumns.IS_COMPLETE, 0);
values.put(DatabaseContract.TaskColumns.DUE_DATE, task.get(position).getDueDateMillis());
getContentResolver().update(uri,
values,
null,
null);
}
// re-queries for all tasks
//mAdapter.notifyDataSetChanged();
getSupportLoaderManager().restartLoader(TASKS_LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new AsyncTaskLoader<Cursor>(this) {
// Initialize a Cursor, this will hold all the task data
Cursor mTaskData = null;
// onStartLoading() is called when a loader first starts loading data
#Override
protected void onStartLoading() {
if (mTaskData != null) {
// Delivers any previously loaded data immediately
deliverResult(mTaskData);
} else {
// Force a new load
forceLoad();
}
}
#Override
public Cursor loadInBackground() {
try {
return getContentResolver().query(DatabaseContract.CONTENT_URI,
null,
null,
null,
DatabaseContract.DEFAULT_SORT);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data) {
mTaskData = data;
super.deliverResult(data);
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
while(data.moveToNext()){
long id = data.getLong(data.getColumnIndex(DatabaseContract.TaskColumns._ID));
String description = data.getString(data.getColumnIndex(DatabaseContract.TaskColumns.DESCRIPTION));
long date = data.getLong(data.getColumnIndex(DatabaseContract.TaskColumns.DUE_DATE));
int priority = data.getInt(data.getColumnIndex(DatabaseContract.TaskColumns.IS_PRIORITY));
int complete = data.getInt(data.getColumnIndex(DatabaseContract.TaskColumns.IS_COMPLETE));
try{
Task tasks = new Task(data);
task.add(tasks);
}catch (Exception e){
e.printStackTrace();
}
}
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
this is the recyclerview adapter
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskHolder> {
/* Callback for list item click events */
public interface OnItemClickListener {
void onItemClick(View v, int position);
void onItemToggled(boolean active, int position);
}
/* ViewHolder for each task item */
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TaskTitleView nameView;
public TextView dateView;
public ImageView priorityView;
public CheckBox checkBox;
public TaskHolder(View itemView) {
super(itemView);
nameView = (TaskTitleView) itemView.findViewById(R.id.text_description);
dateView = (TextView) itemView.findViewById(R.id.text_date);
priorityView = (ImageView) itemView.findViewById(R.id.priority);
checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
itemView.setOnClickListener(this);
checkBox.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == checkBox) {
completionToggled(this);
} else {
postItemClick(this);
}
}
}
private Cursor mCursor;
private OnItemClickListener mOnItemClickListener;
private Context mContext;
public TaskAdapter(Context mContext) {
this.mContext = mContext;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
private void completionToggled(TaskHolder holder) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemToggled(holder.checkBox.isChecked(), holder.getAdapterPosition());
}
}
private void postItemClick(TaskHolder holder) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(holder.itemView, holder.getAdapterPosition());
}
}
#Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.list_item_task, parent, false);
return new TaskHolder(itemView);
}
#Override
public void onBindViewHolder(TaskHolder holder, int position) {
//TODO: Bind the task data to the views
// Indices for the _id, description, and priority columns
int idIndex = mCursor.getColumnIndex(DatabaseContract.TaskColumns._ID);
int descriptionIndex = mCursor.getColumnIndex(DatabaseContract.TaskColumns.DESCRIPTION);
int isCompleteIndex = mCursor.getColumnIndex(DatabaseContract.TaskColumns.IS_COMPLETE);
int isPriorityIndex = mCursor.getColumnIndex(DatabaseContract.TaskColumns.IS_PRIORITY);
int dueDateIndex = mCursor.getColumnIndex(DatabaseContract.TaskColumns.DUE_DATE);
//move cursor to wanted data
mCursor.moveToPosition(position);
// Determine the values of the wanted data
final int id = mCursor.getInt(idIndex);
String description = mCursor.getString(descriptionIndex);
int isComplete = mCursor.getInt(isCompleteIndex);
int isPrior = mCursor.getInt(isPriorityIndex);
long dueDate = mCursor.getLong(dueDateIndex);
Log.v("adapter", " "+DateUtils.getRelativeTimeSpanString(mContext, dueDate)+" "+dueDate);
CharSequence date = DateUtils.getRelativeTimeSpanString(mContext, dueDate);
holder.itemView.setTag(id);
//determine whether to show date or not
if(dueDate != Long.MAX_VALUE){
holder.dateView.setVisibility(View.VISIBLE);
holder.dateView.setText(date);
}else{
holder.dateView.setVisibility(View.GONE);
}
//determine the priority icon
if(isPrior == 0){
holder.priorityView.setImageResource(R.drawable.ic_not_priority);
}else{
holder.priorityView.setImageResource(R.drawable.ic_priority);
}
//determine the text color and description
holder.nameView.setText(description);
holder.nameView.setState(isComplete);
if(isComplete == 1){
holder.checkBox.setChecked(true);
holder.nameView.setState(isComplete);
}
//to chek if due date has passed or not
Calendar now = Calendar.getInstance();
Calendar tasksDate = Calendar.getInstance();
tasksDate.setTimeInMillis(dueDate);
int result = now.compareTo(tasksDate);
if(result >= 0){
holder.nameView.setState(2);
}
else if(result < 0){
holder.nameView.setState(0);
}
}
#Override
public int getItemCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
/**
* Retrieve a {#link Task} for the data at the given position.
*
* #param position Adapter item position.
*
* #return A new {#link Task} filled with the position's attributes.
*/
public Task getItem(int position) {
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("Invalid item position requested");
}
return new Task(mCursor);
}
#Override
public long getItemId(int position) {
return getItem(position).id;
}
public Cursor swapCursor(Cursor cursor) {
if (mCursor == cursor) {
return null; // bc nothing has changed
}
Cursor temp = mCursor;
this.mCursor = cursor; // new cursor value assigned
//check if this is a valid cursor, then update the cursor
if (cursor != null) {
this.notifyDataSetChanged();
}
return temp;
}
}
how to solve this ? thanks!
In the following part of your code you haven't provided the else condition.
if (isComplete == 1){
holder.checkBox.setChecked(true);
holder.nameView.setState(isComplete);
}
You should handle else condition to uncheck the check box because RecyclerView uses old views.
holder.checkBox.setChecked(isComplete == 1);
holder.nameView.setState(isComplete);
Also, you should clear old items before repopulating the list again.
I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.
You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.
After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}
I have delete coding in adapter class as below:
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteItem(id);
}
});
and here is the code in sqliteconnection class,
public void deleteItem(long id) {
System.out.println("DELETE ");
db = sqlHp.getWritableDatabase();
db.delete(ItemDb.TABLE, "_id="+id , null);
db.close();
}
How can I refresh the listview when click the delete button? Thanks.
EDIT
*In class A*
public Cursor getAllItem(String user) {
String[] userID = new String[] {user};
db = sqlHp.getReadableDatabase();
cur=db.query(ItemDb.TABLE, null, "user=?", userID, null, null, "name");
return cur;
}
public Cursor getOneItem(long id) {
db = sqlHp.getReadableDatabase();
cur=db.query(ItemDb.TABLE, null, "_id="+ id, null, null, null,null);
return cur;
}
The class C:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { ItemDb.NAME, ItemDb.CONDITION, ItemDb.EMAIL};
int[] to = new int[] { R.id.etItemName, R.id.etItemCondition, R.id.etEmail };
itemAdapter = new ItemAdapter(this,R.layout.list_item, null, from, to);
this.setListAdapter(itemAdapter);
UserName = (String) getIntent().getSerializableExtra("UserName");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("UserName", UserName); // here string is the value you want to save
editor.commit();
Log.i(Tag, "UserName1: "+ UserName);
}
another part of Class C
#Override
protected void onResume() {
super.onResume();
new GetItem().execute((Object[]) null);
}
#SuppressWarnings("deprecation")
#Override
protected void onStop() {
Cursor cursor = itemAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
itemAdapter.changeCursor(null);
super.onStop();
}
private class GetItem extends AsyncTask<Object, Object, Cursor> {
ItemSQLiteConnector dbConnector = new ItemSQLiteConnector(ItemActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
return dbConnector.getAllItem(UserName);
}
#Override
protected void onPostExecute(Cursor result) {
itemAdapter.changeCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
}
Class B:
public class ItemAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
ImageButton addBtn;
String selection, UserName;
LayoutInflater inflator;
final ItemAdapter myadapter = this;
private SQLiteDatabase db;
public ItemAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = inflator.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex(ItemDb.ID));
final String user = c.getString(c.getColumnIndex(ItemDb.USER));
final String name = c.getString(c.getColumnIndex(ItemDb.NAME));
final String condition = c.getString(c.getColumnIndex(ItemDb.CONDITION));
final String email = c.getString(c.getColumnIndex(ItemDb.EMAIL));
final String category = c.getString(c.getColumnIndex(ItemDb.CATEGORY));
final byte[] image = c.getBlob(c.getColumnIndex(ItemDb.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.photo);
if (image != null) {
if (image.length > 3) {
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
TextView tcondition = (TextView) v.findViewById(R.id.condition);
tcondition.setText(condition);
TextView temail = (TextView) v.findViewById(R.id.email);
temail.setText(email);
final ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(context);
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("user", user);
intent.putExtra("name", name);
intent.putExtra("condition", condition);
intent.putExtra("email", email);
intent.putExtra("category", category);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteItem(id);
//Cursor cur=db.query(ItemDb.TABLE, null, "_id="+ id, null, null, null,null);
//myadapter.changeCursor(cur);
//myadapter.notifyDataSetChanged();
//Intent intent=new Intent(context,Tab.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(intent);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ViewItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("user", user);
intent.putExtra("name", name);
intent.putExtra("condition", condition);
intent.putExtra("email", email);
intent.putExtra("category", category);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
}
}
call notifyDataSetChanged() (from the adapter object or within the adapter class) after the delete of the sql and removing the item from the adapter.
Example:
WhateverMyAdapterClassIs myadapter = new WhateverMyAdapterClassIs();
...
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteItem(id);
//Add code to remove the respective item from the List,ArrayList
//or whatever you use in the adapter then call notifyDataSetChanged()
myadapter.notifyDataSetChanged();
}
});
Or if you have extended an adapter class add a removeItem function and call the notifyDataSetChanged from it:
public void removeItem(int index) {
myList.remove(index);
notifyDataSetChanged();
}
In your case use:
final ItemAdapter myadapter = this;
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteItem(id);
//Add code to remove the respective item from the List,ArrayList
//or whatever you use in the adapter then call notifyDataSetChanged()
myadapter.notifyDataSetChanged();
}
});
public class ItemAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
ImageButton addBtn;
String selection, UserName;
LayoutInflater inflator;
final ItemAdapter myadapter = this;
private SQLiteDatabase db;
private OnItemDeleted mOnItemDeleted;
public interface OnItemDeleted {
public void updateCursor();
}
public ItemAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, OnItemDeleted onItemDeleted) {
super(context, layout, c, from, to,0);
this.layout = layout;
mOnItemDeleted = onItemDeleted;
inflator= LayoutInflater.from(context);
}
.........
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteItem(id);
mOnItemDeleted.updateCursor();
//Intent intent=new Intent(context,Tab.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(intent);
}
});
}
In the calling class C
itemAdapter = new ItemAdapter(this,R.layout.list_item, null, from, to, new MyOnItemDeleted());
......
public class MyOnItemDeleted implements ItemAdapter.OnItemDeleted
{
public void updateCursor()
{
new GetItem().execute((Object[]) null);
}
}
I implement a JSONArray to populate a ListView. Now I want to sort the items on the ListActivity alphabetically by its name, which is its Object Attribute.
How am I able to sort it out?
Heres the Object class I use to implement the ListView:
public class VideoLocation {
public String deleted_at = null;
public int documentary_video_length = -1;
public int id = -1;
public double latitude = 0d;
public double longitude = 0d;
public int position = -1;
public String updated_at = null;
public String name = null;
public String text = null;
public String documentary_video_url = null;
public String documentary_thumbnail_url = null;
public String audio_text_url = null;
public Footage[] footages = null;
public VideoLocation(){
}
and here's the ListActivity Class:
public class ProjectsList extends ListActivity implements OnItemClickListener, VideoLocationReceiver{
/** Called when the activity is first created. */
private VideoLocation[] videoLocations = null;
private VideoLocationAdapter videoLocationAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
doSync();
//storeSharedPrefs();
ListView lv = getListView();
lv.setOnItemClickListener(this);
videoLocationAdapter = new VideoLocationAdapter(ProjectsList.this,
R.layout.listitems,
new VideoLocation[0]);
lv.setAdapter(videoLocationAdapter);
//CREATE VideoLocation[] from Database!
JsonDB dbhelper = new JsonDB(ProjectsList.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.beginTransaction();
videoLocations = dbhelper.getVideoLocations(db);
db.setTransactionSuccessful();//end transaction
db.endTransaction();
db.close();
}
#Override
public void onResume(){
super.onResume();
DBSync.setVideoLocationReceiver(ProjectsList.this);
}
#Override
public void onPause(){
super.onResume();
DBSync.setVideoLocationReceiver(null);
}
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Intent listIntent = new Intent(this, ProjectDetailsActivity.class);
VideoLocation vidLocation = videoLocations[position];
listIntent.putExtra("documentary_video_url",vidLocation.documentary_video_url);
startActivity(listIntent);
}
protected void storeSharedPrefs() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("first-time", true)) {
doSync();
prefs.edit().putBoolean("first-time", false).commit(); // record the fact that the app has been started at least once
}
}
void doSync() {
Intent serviceIntent = new Intent(this, DBSync.class);
startService(serviceIntent);
}
public class VideoLocationAdapter extends ArrayAdapter<VideoLocation> {
public ImageLoader imageLoader;
ImageLoader loader = null;
public VideoLocationAdapter(Context context, int resource, VideoLocation[] vidLocs) {
super(context, resource, vidLocs);
ProjectsList.this.videoLocations = vidLocs;
loader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = ProjectsList.this.getLayoutInflater().inflate(R.layout.listitems, null, true);
}
VideoLocation vidLocation = videoLocations[position];
ImageView v = (ImageView)convertView.findViewById(R.id.image);
String url = vidLocation.documentary_thumbnail_url;
v.setTag(url);
loader.DisplayImage(url, ProjectsList.this, v);
TextView titleView = (TextView)convertView.findViewById(R.id.txt_title);
titleView.setText(vidLocation.name);
return convertView;
}
#Override
public int getCount(){
return videoLocations==null?0:videoLocations.length;
}
#Override
public VideoLocation getItem(int position){
return videoLocations[position];
}
#Override
public boolean hasStableIds(){
return true;
}
#Override
public boolean isEnabled(int position){
return true;
}
#Override
public long getItemId(int position){
return videoLocations[position].id;
}
public void setVideoLocationData(VideoLocation[] newData){
ProjectsList.this.videoLocations = newData;
VideoLocationAdapter.this.notifyDataSetChanged();
}
}
#Override
public void receivedVideoLocationData(VideoLocation[] vidLocs) {
final VideoLocation[] locs = vidLocs;
if (vidLocs==null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//show popup and inform about missing network
}
});
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
videoLocationAdapter.setVideoLocationData(locs);
Log.d("ProjectsList", "updating video locations...");
}
});
}
}
}
Use Collections.sort. Parse your json and fill up a vector or an ArrayList (I think) with instance of VideoLocation. Then call Collections.sort.
Edit:
Collections.sort(youarrayList, new Comparator<VideoLocation>() {
#Override
public int compare(VideoLocation lhs, VideoLocation rhs) {
return lhs.name.compareTo(rhs.name);
}
});
In getVideoLocations(db), you may tell your query to return result as sorted by using ORDER BY [Column]