I am trying to refresh my view when an item in the list is delete. I am currently trying to refresh/reload the view in the onPostExecute method of AsyncTask. So far nothing I have tried has worked. This would seem like an easy task to complete. My custom adapter extends BaseAdapter. I am hoping there is something simple I am missing. Can anyone shed an light??
Cheers.
public class ItemListActivity extends OrmLiteBaseListActivity<DatabaseHelper> {
private final String TAG = getClass().getSimpleName();
private DatabaseHelper dbHelper;
private ListView itemListView;
private ItemListAdapter listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.itemslistactivity);
registerForContextMenu(getListView());
itemListView = getListView();
itemListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listview_context_menu, menu);
}
});
listAdapter = new ItemListAdapter(getApplicationContext(), new ArrayList<Item>());
itemListView.setAdapter(listAdapter);
dbHelper = getHelper();
new SelectDataTask().execute(dbHelper);
}
public void add_OnClick(View v) {
Intent intent = new Intent();
intent.setClass(this, AddItemActivity.class);
startActivity(intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Item b = (Item) listAdapter.getItem(info.position);
try {
switch (item.getItemId()) {
case R.id.remove_item:
dbHelper.getItemDao().deleteById(new Integer(b.id));
listAdapter.notifyDataSetChanged();
return true;
}
} catch (SQLException e) {
//FIXME
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
return false;
}
private class SelectDataTask extends AsyncTask<DatabaseHelper, Void, List<Item>> {
private final ProgressDialog dialog = new ProgressDialog(
ItemListActivity.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Retreiving item data...");
this.dialog.show();
}
#Override
protected List<Item> doInBackground(DatabaseHelper... params) {
List<Item> l = null;
try {
Dao<Item, Integer> dao = params[0].getItemDao();
l = dao.queryForAll();
} catch (SQLException e) {
//TODO -- cleanup
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
return l;
}
// can use UI thread here
#Override
protected void onPostExecute(List<Item> b) {
listAdapter = new MyListAdapter(getApplicationContext(), b);
itemListView.setAdapter(listAdapter);
//TODO -- none of this works
itemListView.invalidateViews();
listAdapter.notifyDataSetChanged();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
Check my solution (group CRUD):
public class GroupsPreferenceActivity extends BaseAppActivity {
private DatabaseHelper dbHelper;
private ListView listView;
private GroupAdapter groupAdapter;
private DatabaseModel groupModel;
private OnDeleteListener onDeleteListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.group_preference_layout);
setDbHelper(new DatabaseHelper(getApplicationContext()));
setGroupModel(new DatabaseModel(getDbHelper(), GroupData.class));
setListView((ListView) findViewById(R.id.lv_group));
setGroupAdapter(new GroupAdapter(GroupsPreferenceActivity.this));
getListView().setAdapter(getGroupAdapter());
setOnDeleteListener(new OnDeleteListener() {
#Override
public void onClick(GroupData group) {
removeGroup(group);
}
});
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View parent,
int position, long id) {
addGroup(getGroupAdapter().getItem(position));
}
});
getGroupAdapter().setOnDeleteListener(getOnDeleteListener());
doLoadGroups();
}
private void doLoadGroups() {
getGroupAdapter().clear();
List<?> items = getGroupModel().getAll();
for (Object group : items) {
getGroupAdapter().add((GroupData) group);
}
getGroupAdapter().notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.groups_preference_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
super.onMenuItemSelected(featureId, item);
switch (item.getItemId()) {
case R.id.option_item_add_group:
addGroup();
break;
default:
break;
}
return true;
}
private void addGroup() {
addGroup(null);
}
private void addGroup(final GroupData groupData) {
LayoutInflater factory = LayoutInflater
.from(GroupsPreferenceActivity.this);
final View textEntryView = factory.inflate(
R.layout.create_group_dialog_view, null);
final EditText editName = (EditText) textEntryView
.findViewById(R.id.tv_group_name);
String positiveButtonName = getString(R.string.create);
OnClickListener positiveListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
createGroup(editName.getText().toString());
}
};
if (groupData != null) {
positiveButtonName = getString(R.string.update);
editName.setText(groupData.getName());
positiveListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
groupData.setName(editName.getText().toString());
updateGroup(groupData);
}
};
}
AlertDialog.Builder builder = new AlertDialog.Builder(
GroupsPreferenceActivity.this);
String title = getString(R.string.preference_add_group);
builder.setCancelable(true)
.setTitle(title)
.setView(textEntryView)
.setPositiveButton(positiveButtonName, positiveListener)
.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
final Button yesButton = alert.getButton(Dialog.BUTTON_POSITIVE);
yesButton.setEnabled(false);
editName.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
yesButton.setEnabled(s.length() > 0);
}
});
}
protected void updateGroup(GroupData groupData) {
getGroupModel().update(groupData);
doLoadGroups();
}
protected void createGroup(String name) {
GroupData groupData = new GroupData();
groupData.setName(name);
getGroupModel().add(groupData);
doLoadGroups();
}
protected void removeGroup(GroupData group) {
getGroupModel().remove(group);
doLoadGroups();
}
public DatabaseHelper getDbHelper() {
return dbHelper;
}
public void setDbHelper(DatabaseHelper dbHelper) {
this.dbHelper = dbHelper;
}
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
public GroupAdapter getGroupAdapter() {
return groupAdapter;
}
public void setGroupAdapter(GroupAdapter groupAdapter) {
this.groupAdapter = groupAdapter;
}
public DatabaseModel getGroupModel() {
return groupModel;
}
public void setGroupModel(DatabaseModel groupModel) {
this.groupModel = groupModel;
}
public OnDeleteListener getOnDeleteListener() {
return onDeleteListener;
}
public void setOnDeleteListener(OnDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
}
My DB helpers located: https://github.com/beshkenadze/android-utils/tree/master/src/net/beshkenadze/android/db
Related
I am working on android Note application. And I want to delete multiple selected items at a time from RecyclerView as well as from SQLite database. For this I am using contextual action bar. But when I delete some items it shows the following error;
java.lang.NullPointerException: Attempt to invoke interface method 'void com.notes.Adapter$OnClickAction.onClickAction()' on a null object reference
at com.notes.Adapter$1.onLongClick
How to solve this?
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private LayoutInflater inflater;
public List<Note> notes, selected;
OnClickAction receiver;
public int id;
public interface OnClickAction {
void onClickAction();
}
Adapter(Context context, List<Note> notes){
this.inflater = LayoutInflater.from(context);
this.notes = notes;
this.selected=new ArrayList<>();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.note_item,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
final Note item = notes.get(i);
String title = notes.get(i).getTitle();
String date = notes.get(i).getDate();
String time = notes.get(i).getTime();
final long id = notes.get(i).getId();
Log.d("NC" ,"Date on: "+date);
viewHolder.nTitle.setText(title);
viewHolder.nDate.setText(date);
viewHolder.nTime.setText(time);
viewHolder.nID.setText(String.valueOf(notes.get(i).getId()));
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (selected.contains(item)) {
selected.remove(item);
unhighlightView(viewHolder);
} else {
selected.add(item);
highlightView(viewHolder);
}
receiver.onClickAction();
return true;
}
});
if (selected.contains(item))
highlightView(viewHolder);
else
unhighlightView(viewHolder);
}
private void highlightView(ViewHolder holder) {
holder.itemView.setBackgroundColor(Color.CYAN);
}
private void unhighlightView(ViewHolder holder) {
holder.itemView.setBackgroundColor(Color.WHITE);
}
#Override
public int getItemCount() {
return notes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView nTitle,nDate,nTime,nID;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
nTitle = itemView.findViewById(R.id.nTitle);
nDate = itemView.findViewById(R.id.nDate);
nTime = itemView.findViewById(R.id.nTime);
nID = itemView.findViewById(R.id.listId);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// notifyDataSetChanged();
Intent i = new Intent(v.getContext(),NoteDetails.class);
i.putExtra("ID",notes.get(getAdapterPosition()).getId());
v.getContext().startActivity(i);
itemView.setBackgroundColor(Color.GRAY);
}
});
}
}
public List<Note> getSelected() {
return selected;
}
public void setActionModeReceiver(OnClickAction receiver) {
this.receiver = receiver;
}
public void clearSelected() {
selected.clear();
notifyDataSetChanged();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements Adapter.OnClickAction {
RecyclerView recyclerView;
Adapter adapter;
NoteDatabase noteDatabase;
long id;
ActionMode actionMode;
private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.delete_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.dlt:
delete();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
adapter.clearSelected();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteDatabase = new NoteDatabase(this);
recyclerView = findViewById(R.id.listofnotes);
FloatingActionButton button = findViewById(R.id.buttonadd);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Add New Note", Toast.LENGTH_SHORT).show();
Intent i = new Intent(view.getContext(), AddNote.class);
startActivity(i);
}
});
}
public void delete() {
List<Note> newnote=adapter.getSelected();
Log.d("NC","selected "+adapter.selected);
for (int i=0; i<newnote.size(); i++){
long id=newnote.get(i).getId();
noteDatabase.deleteNote(id);
Log.d("NC", "deleted: "+id);
List<Note> getAllNotes = noteDatabase.getAllNotes();
adapter=new Adapter(this,getAllNotes);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),"Note Deleted",Toast.LENGTH_SHORT).show();
}
private void displayList(List<Note> allNotes) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, allNotes);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.dltall) {
noteDatabase.deleteAll();
List<Note> notes = noteDatabase.getAllNotes();
Log.d("NC", "Note after dlt " + notes);
displayList(notes);
Toast.makeText(this, "All Notes Deleted", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
List<Note> getAllNotes = noteDatabase.getAllNotes();
if (getAllNotes.isEmpty()) {
} else {
displayList(getAllNotes);
adapter.setActionModeReceiver((Adapter.OnClickAction)this);
}
}
public void onClickAction() {
int selected = adapter.getSelected().size();
if (actionMode == null) {
actionMode = startActionMode(actionModeCallback);
actionMode.setTitle("Selected: " + selected);
} else {
if (selected == 0) {
actionMode.finish();
} else {
actionMode.setTitle("Selected: " + selected);
adapter.notifyDataSetChanged();
}
}
}
}
You forgot to set the listner in delete()
public void delete() {
List<Note> newnote=adapter.getSelected();
Log.d("NC","selected "+adapter.selected);
for (int i=0; i<newnote.size(); i++){
long id=newnote.get(i).getId();
noteDatabase.deleteNote(id);
Log.d("NC", "deleted: "+id);
List<Note> getAllNotes = noteDatabase.getAllNotes();
adapter=new Adapter(this,getAllNotes);
adapter.setActionModeReceiver((Adapter.OnClickAction)this); // Add this
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),"Note Deleted",Toast.LENGTH_SHORT).show();
}
I'm having a recyclerview to display a list of notes from room database. I've also added search functionality. Currently, I'm having 4 notes in MainActivity (this activity displays notes). On searching, if I get resultant list having more than 2 notes, on clicking them it displays correct notes.But, if resultant has 1 or 2 notes, it always displays the first 2 in list, not the notes filtered by search.
Here's my code:
Model class Note:
#Entity(tableName = TABLE_NAME)
public class Note implements Serializable{
#Nullable
private int Color;
#PrimaryKey(autoGenerate = true)
private long id;
/** Not-null value. */
private String Desc;
private String Time;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public Note() {
}
public Note(String Desc, String Time) {
this.Desc = Desc;
this.Time = Time;
}
public int getColor() {
return Color;
}
public void setColor(int color) {
Color = color;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
/** Not-null value. */
public String getDesc() {
return Desc;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setDesc(String Desc) {
this.Desc = Desc;
}
public String getTime() {
return Time;
}
public void setTime(String Time) {
this.Time = Time;
}
NotesAdapter:
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyViewHolder> {
public List<Note> list;
private Context context;
private List<Note> filteredList = new ArrayList<>();
private ClickListener clickListener;
public List<Note> selectednotes_list = new ArrayList<>();
private String TAG = NotesAdapter.class.getSimpleName();
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mNoteDesc;
public TextView mNoteTime;
public RelativeLayout mcontainer;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNoteTime = itemView.findViewById(R.id.note_time);
mNoteDesc = itemView.findViewById(R.id.note_desc);
mcontainer = itemView.findViewById(R.id.note_container);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,this.getLayoutPosition());
}
/*
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,getLayoutPosition());
//clickListener.onClick(filteredList.get(getAdapterPosition()));
}
*/
}
public NotesAdapter(List<Note> list, Context context,List<Note> selectednotes_list) {
this.list = list;
this.filteredList = list;
this.context = context;
this.selectednotes_list = selectednotes_list;
this.clickListener = (ClickListener) context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.noteview,null,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.mNoteTime.setText(list.get(position).getTime());
holder.mcontainer.setBackgroundColor(Utils.getRandomMaterialColor(context, "50to300"));
holder.mNoteDesc.setText(list.get(position).getDesc());
// Change background color on select
if (selectednotes_list.size() > 0) {
if (selectednotes_list.contains(list.get(position)))
holder.mcontainer.setBackgroundColor(ContextCompat.getColor(context, R.color.colorSecondary));
}
}
#Override
public int getItemCount() {
return list.size();
}
public void filterList(List<Note> filter) {
this.list = filter;
notifyDataSetChanged();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ClickListener{
private StaggeredGridLayoutManager gridLayoutManager;
private RecyclerView recyclerView;
private List<Note> noteList, multiSelectList;
public NotesAdapter notesAdapter;
private Notedatabase notedatabase;
private String TAG = MainActivity.class.getSimpleName();
private FloatingActionButton maddbtn;
private int position;
private SearchView mSearchView;
private boolean isMultiSelect = false;
private Menu context_menu;
private ActionMode mActionMode;
private CoordinatorLayout mCoordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
displayList();
/*
notesList.addAll(noteList);
List<Note> notesList = getNotes();
notesAdapter = new NotesAdapter(notesList,MainActivity.this);
recyclerView.setAdapter(notesAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
// Searchable config with searchview
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
mSearchView.setMaxWidth(Integer.MAX_VALUE);
// Set Listener
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter when query is submitted
Log.d(TAG, "onQueryTextSubmit: " + query);
notesAdapter.filterList(filter(query,noteList));
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// filter progressively as query changes
Log.d(TAG, "onQueryTextChange: " + newText);
notesAdapter.filterList(filter(newText,noteList));
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_search) {
// search action
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close searchview
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
return;
}
super.onBackPressed();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if (resultCode == 1) {
Log.d(TAG, "Request code is 1");
noteList.add((Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 2) {
Log.d(TAG, "Request code 2, update return");
noteList.set(position, (Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 3) {
Log.d(TAG, "Request code 3, delete return");
Log.d(TAG, "Deleting this from list:" + (Note) data.getSerializableExtra("note"));
noteList.remove(MainActivity.this.position);
notesAdapter.notifyItemRemoved(MainActivity.this.position);
}
}
}
private void displayList() {
notedatabase = Notedatabase.getInstance(MainActivity.this);
new RetrieveTask(this).execute();
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerview);
gridLayoutManager = new StaggeredGridLayoutManager(2,1);
mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
recyclerView.setLayoutManager(gridLayoutManager);
noteList = new ArrayList<>();
multiSelectList = new ArrayList<>();
notesAdapter = new NotesAdapter(noteList,MainActivity.this,multiSelectList);
recyclerView.setAdapter(notesAdapter);
maddbtn = findViewById(R.id.add_fab);
maddbtn.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
startActivityForResult(intent,REQUEST_CODE);
});
}
#Override
public void onClick(View view, int pos) {
/*
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",noteList.get(position));
Log.d(TAG, "list.get(position): " + noteList.get(pos).getDesc());
startActivityForResult(intent,REQUEST_CODE);
*/
}
#Override
public void onClick(Note note) {
/*
Log.d(TAG, "onClick with args as note1");
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",note);
startActivityForResult(intent,REQUEST_CODE);*/
}
#Override
public void onLongClick(View view, int pos) {
/* Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);*/
}
private void multi_select(int pos) {
if(mActionMode != null) {
if(multiSelectList.contains(noteList.get(pos))) {
Log.d(TAG, "multi_select removed: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.remove(noteList.get(pos));
}
else {
Log.d(TAG, "multi_select added: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.add(noteList.get(pos));
}
if(multiSelectList.size() > 0) mActionMode.setTitle("" + multiSelectList.size() + " selected");
else mActionMode.setTitle("");
refreshAdapter();
}
}
private void refreshAdapter() {
notesAdapter.selectednotes_list = multiSelectList;
notesAdapter.list = noteList;
notesAdapter.notifyDataSetChanged();
}
class RetrieveTask extends AsyncTask<Void,Void,List<Note>>{
private WeakReference<MainActivity> weakReference;
public RetrieveTask(MainActivity mainActivity) {
weakReference = new WeakReference<>(mainActivity);
}
#Override
protected List<Note> doInBackground(Void... voids) {
if(weakReference.get()!=null)
return weakReference.get().notedatabase.getNoteDao().getNotes();
else
return null;
}
#Override
protected void onPostExecute(List<Note> notes) {
if(notes!=null & notes.size()>0) {
weakReference.get().noteList = notes;
//weakReference.get().noteList.addAll(weakReference.get().getNotes());
Log.d(TAG, "Result: " + notes);
weakReference.get().notesAdapter = new NotesAdapter(notes,weakReference.get(),multiSelectList);
/*
// Randomly set note background
for(Note n:notes) {
n.setColor(getRandomMaterialColor(MainActivity.this,"500"));
}
*/ weakReference.get().recyclerView.addOnItemTouchListener(new RecyclerTouchListener(recyclerView, getApplicationContext(), new ClickListener() {
#Override
public void onClick(View view, int pos) {
if (isMultiSelect)
multi_select(pos);
else {
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", noteList.get(position));
Log.d(TAG, "list.get(position): " + weakReference.get().noteList.get(position).getDesc());
startActivityForResult(intent, REQUEST_CODE);
}
}
#Override
public void onClick(Note note) {
Log.d(TAG, "onClick with args as note");
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", note);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
public void onLongClick(View view, int pos) {
Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);
}
}));
weakReference.get().recyclerView.setAdapter(weakReference.get().notesAdapter);
weakReference.get().notesAdapter.notifyDataSetChanged();
}
else{
displayErrorMsg();
}
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//Prepare the menu
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action,menu);
context_menu = menu;
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//mode.getCustomView().setBackgroundColor(getApplicationContext().getResources().getColor(android.R.color.white));
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// display alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Delete " + multiSelectList.size() + " notes?");
builder.setCancelable(true);
builder.setPositiveButton(R.string.alert_yes,(dialog, which) -> {
// Deleting notes
for (int i = 0; i < multiSelectList.size(); i++) {
Log.d(TAG, "Deleting: " + multiSelectList.get(i));
notedatabase.getNoteDao().deleteNotes(multiSelectList.get(i));
noteList.remove(multiSelectList.get(i));
}
// Display Snackbar
displaySnackbar(mCoordinatorLayout,R.string.delete_success);
dialog.cancel();
// Refresh adapter
refreshAdapter();
// dismiss the contextual action bar
if(mActionMode!=null) mActionMode.finish();
});
builder.setNegativeButton(R.string.alert_no,(dialog, which) -> {
dialog.cancel();
if(mActionMode!=null) mActionMode.finish();
});
builder.setOnCancelListener(dialog1 -> {
Log.d(TAG, "onCancelListener: ");
if(mActionMode!=null) mActionMode.finish();
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
isMultiSelect = false;
multiSelectList = new ArrayList<Note>();
refreshAdapter();
}
};
#Override
protected void onDestroy() {
notedatabase.cleanUp();
super.onDestroy();
}
private void displayErrorMsg() {
Toast.makeText(MainActivity.this,R.string.failure_display,Toast.LENGTH_SHORT).show();
}
}
Any help is widely appreciated!!
Please! Badly stuck here
Found it out!
I was not storing the result of filter, instead I was directly calling it in filterList.
noteList = filter(newText, noteList);
notesAdapter.filterList(noteList);
The above lines did it for me!
Problem
I am new to android and i am using viewpager for the first time in my app and
i am suffering from very strange behavior in my app that is i am using viewpager with three fragments ( TrackFragment , AlbumFragment , ArtistFragment ) and when i swip page from TrackFragment to AlbumFragment and again come back to TrackFragment it becomes blank (but it was not at first time when i am at TrackFragment initially) and same thing happened when i jump to ArtistFragment or any other fragments from the tab layout (its become blank).
And in case when i am going to ArtistFragment from TrackFragment via AlbumFragments by swiping the pages it works correctly (that is contents are shown in pages).
Please suggest me a method to overcome the above problem or any other method to implement same thing.
Here is my code....
MainActivity
public class MainActivity extends AppCompatActivity {
private String[] mPlanetTitles={"Tracks","Album","Artist"};
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
SharedPreferences sharedPreferences;
Fragment [] fragments = {new TracksFragment(),new AlbumFragment(), new ArtistFragment()};
PagerAdapter pagerAdapter;
ViewPager viewPager;
public static ImageView im;
int pos= -1 ;
public static Context context;
MusicService musicService;
boolean mBound;
TabLayout tabLayout ;
public static Uri currentsonguri;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("lastplayed",Context.MODE_PRIVATE);
Intent i = new Intent(MainActivity.this,MusicService.class);
startService(i);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new NavigationDrawerAdapter(this));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 3)
{
Intent i = new Intent(MainActivity.this,PlaylistActivity.class);
startActivity(i);
}
if(position == 4)
{
Intent intent = new Intent();
intent.setAction("android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL");
if((intent.resolveActivity(getPackageManager()) != null)) {
startActivity(intent);
} else {
// No equalizer found :(
Toast.makeText(getBaseContext(),"No Equaliser Found",Toast.LENGTH_LONG).show();
}
}
}
});
tabLayout = (TabLayout) findViewById(R.id.tablayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout.setTabTextColors(Color.DKGRAY,Color.WHITE);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
context = getBaseContext();
pagerAdapter = new myfragment(getSupportFragmentManager());
im = (ImageView) findViewById(R.id.currentsong);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager,true);
SharedPreferences.Editor editor= sharedPreferences.edit();
if(sharedPreferences.getInt("count",0)==0)
{
editor.putInt("count",1);
}
else
{
int c= sharedPreferences.getInt("count",0);
Log.d("Uses count",c+"");
editor.putInt("count",c++);
editor.apply();
}
if(!sharedPreferences.getString("uri","").equals(""))
{
String s = sharedPreferences.getString("uri","");
Uri u = Uri.parse(s);
currentsonguri = u;
MediaMetadataRetriever data=new MediaMetadataRetriever();
data.setDataSource(getBaseContext(),u);
try {
byte[] b = data.getEmbeddedPicture();
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
try {
musicService.setsongbyuri(u,getBaseContext());
musicService.setMediaPlayer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
}
editor.apply();
im.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(currentsonguri);
intent.putExtra("flag",1);
startActivity(intent);
}
});
final Uri r= getIntent().getData();
if(r!=null) {
currentsonguri = r;
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(r);
intent.putExtra("flag",0);
startActivity(intent);
}
}
public class myfragment extends FragmentPagerAdapter {
myfragment(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments[position];
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
String s = "non";
switch (position)
{
case 0 : s= "Tracks" ;
break;
case 1: s= "Albums" ;
break;
case 2: s= "Artist" ;
break;
}
return s;
}
}
public void setview(byte [] b, int position,Uri uri)
{
currentsonguri = uri;
Log.d("position in set view",""+position);
Log.d("fail","i am here");
if(im!=null)
{
if(b!=null)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
else {
songDetailloader loader = new songDetailloader(context);
String s = loader.albumartwithalbum(loader.songalbum(position));
Log.d("fail","fail to set small image");
if (s != null) {
im.setImageBitmap(BitmapFactory.decodeFile(s));
Log.d("fail","nowsetting set small image");
} else {
im.setImageResource(R.drawable.default_track_light);
Log.d("ic","ic_launcher setted");
}
}
}
else {
Log.d(""," im is null");
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 100;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("MainActivity","Get distoryed");
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(this,MusicService.class);
bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
unbindService(serviceConnection);
}}
Tracks Fragment
public class TracksFragment extends Fragment {
songDetailloader loader = new songDetailloader();
ArrayList<Songs> give = new ArrayList<>();
public int pos = -1;
MediaPlayer mp ;
MusicService musicService;
boolean mBound;
ImageView search;
ListViewAdapter listViewAdapter;
RelativeLayout editreltive;
ListView listView;
EditText editText;
TextView ch;
private Cursor cursor ;
int albumindex,dataindex,titleindex,durationindex,artistindex;
private final static String[] columns ={MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.IS_MUSIC,MediaStore.Audio.Media.IS_RINGTONE,MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.SIZE ,MediaStore.Audio.Media._ID};
private final String where = "is_music AND duration > 10000 AND _size <> '0' ";
private final String orderBy = MediaStore.Audio.Media.TITLE;
public TracksFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("fragment created","created");
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
allsongs();
intlistview();
new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(),MusicService.class);
getActivity().bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
}).start();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d("Uri of ",""+give.get(position).getSonguri());
musicService.setplaylist(give,give.get(position).getPosition());
musicService.setMediaPlayer();
view.setSelected(true);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v =LayoutInflater.from(getContext()).inflate(R.layout.select_dialog_layout,null);
builder.setView(v);
builder.setTitle(give.get(position).gettitle()+"\n "+give.get(position).getalbum());
builder.create();
final AlertDialog d=builder.show();
//seting click listner.....
TextView play = (TextView) v.findViewById(R.id.dialogplay);
TextView playnext = (TextView) v.findViewById(R.id.dialogplaynext);
TextView queue = (TextView) v.findViewById(R.id.dialogqueue);
TextView fav = (TextView) v.findViewById(R.id.dialogaddtofav);
TextView album = (TextView) v.findViewById(R.id.dialogalbum);
TextView artist = (TextView) v.findViewById(R.id.dialogartist);
TextView playlist = (TextView) v.findViewById(R.id.dialogaddtoplaylsit);
TextView share = (TextView) v.findViewById(R.id.dialogshare);
TextView delete = (TextView) v.findViewById(R.id.dialogdelete);
TextView properties = (TextView) v.findViewById(R.id.dialogproperties);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f= new File(give.get(position).getSonguri().getLastPathSegment());
Log.d("LENGTH IS",""+f.length());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
d.dismiss();
}
});
playnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
queue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
musicService.insertinqueue(give.get(position));
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
DataBaseClass db = new DataBaseClass(getContext());
int i=db.insetintoliked(give.get(position));
if(i==1)
{
Toast.makeText(getContext(),"Added to Favorites",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getContext(),"Already in Favorites",Toast.LENGTH_SHORT).show();
}
});
album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",give.get(position).getalbum());
i.putExtras(b);
startActivity(i);
}
});
artist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getActivity(),ArtistActivity.class);
i.putExtra("artist",give.get(position).getartist());
startActivity(i);
d.dismiss();
}
});
playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setMessage("Audio '"+give.get(position).gettitle()+"' will be deleted permanently !");
b.setTitle("Delete ?");
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
b.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File f= new File(give.get(position).getSonguri().getPath());
boolean b = f.delete();
Log.d("Is file exist",f.exists()+"");
Log.d("File Lenth",""+f.length());
Log.d("Return value",""+b);
loader.set(getContext());
loader.deleteSong(getContext(),give.get(position).getPosition());
give.remove(position); // give is Arraylist of Songs(datatype);
listViewAdapter.notifyDataSetChanged();
if(b)
{
Toast.makeText(getContext(),"Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(),"Fail to Delete",Toast.LENGTH_SHORT).show();
}
}
});
b.create().show();
d.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, give.get(position).getSonguri());
startActivity(Intent.createChooser(share, "Share Audio"));
}
});
properties.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
File f= new File(give.get(position).getSonguri().getPath());
long size = (f.length())/1024;
long mb= size/1024;
long kb= size%1024;
b.setMessage("Size:"+"\n"+"Size "+mb+"."+kb+" MB\n"+"Path:"+f.getAbsolutePath()+"\n");
b.setTitle(f.getName());
b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
b.create().show();
d.dismiss();
}
});
return true;
}
});
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("fragment","instance saved");
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.d("Fragment","Instance Restored");
}
public void intlistview()
{
listViewAdapter = new ListViewAdapter(getContext(),give);
listView.setAdapter(listViewAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Fragment","Destroyed");
getActivity().unbindService(serviceConnection);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
public void allsongs()
{
cursor = getContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, where, null, orderBy);
dataindex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
albumindex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
titleindex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
durationindex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
artistindex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
cursor.moveToFirst();
for(int i=0;i<cursor.getCount();i++)
{
Songs song = new Songs();
song.setalbum(cursor.getString(albumindex));
song.settitle(cursor.getString(titleindex));
song.setSonguri(Uri.parse(cursor.getString(dataindex)));
song.setartist(cursor.getString(artistindex));
song.setDuration(Long.decode(cursor.getString(durationindex)));
song.setPosition(cursor.getPosition());
this.give.add(song);
cursor.moveToNext();
}
cursor.close();
}}
Album Fragment
public class AlbumFragment extends Fragment {
songDetailloader songDetailloader = new songDetailloader();
public AlbumFragment() {
super();
}
GridView gridView;
AlbumAdapter a;
private static ArrayList<Bitmap> image = new ArrayList<>();
LinearLayout linearLayout;
Cursor cursor ;
ImageView album;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v =inflater.inflate(R.layout.albumgridview,container,false);
gridView = (GridView) v.findViewById(R.id.gridview);
album = (ImageView) v.findViewById(R.id.albumart);
/*Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.grid_layout_anim);
GridLayoutAnimationController controller = new GridLayoutAnimationController(animation,0.2f,0.2f);
gridView.setLayoutAnimation(controller);*/
final TextView albumname = (TextView) v.findViewById(R.id.albumname);
cursor = songDetailloader.getAlbumCursor(getContext());
if(image.size()==0)
new getbitmaps().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = songDetailloader.albumart(position);
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",songDetailloader.album(position));
i.putExtras(b);
startActivity(i);
}
});
return v;
}
public class getbitmaps extends AsyncTask<Void,Void,Void>
{
Bitmap b;
public getbitmaps() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<cursor.getCount();i++)
{
cursor.moveToPosition(i);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize= 2;
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)),options);
if(b==null)
{
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)));
}
image.add(b);
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
a =new AlbumAdapter(getContext(),image);
a.setCursor();
gridView.setAdapter(a);
new Thread(new Runnable() {
#Override
public void run() {
songDetailloader.set(getContext());
}
}).start();
}
}}
Artist Fragment
public class ArtistFragment extends Fragment {
ListView listView ;
ArrayList<Artists> aa = new ArrayList<>();
final String[] columns3 = {MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST,MediaStore.Audio.Artists.NUMBER_OF_ALBUMS,MediaStore.Audio.Artists.NUMBER_OF_TRACKS};
final static String orderBy3 = MediaStore.Audio.Albums.ARTIST;
public Cursor cursor3;
public ArtistFragment() {
super();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
new artist().execute();
return v;
}
public class artist extends AsyncTask<Void, Void ,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
allartist();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArtistAdapter artistAdapter = new ArtistAdapter(getActivity().getBaseContext(),aa);
listView.setAdapter(artistAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(getActivity(), ArtistActivity.class);
i.putExtra("artist", aa.get(position).getArtistname());
i.putExtra("noofsongs",aa.get(position).getNofosongs());
startActivity(i);
}
});
}
}
#Override
public void setInitialSavedState(SavedState state) {
super.setInitialSavedState(state);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void allartist()
{
cursor3 = getContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, columns3, null, null, orderBy3);
cursor3.moveToFirst();
for(int i=0;i< cursor3.getCount() ;i++)
{
Artists art = new Artists();
art.setArtistname(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.ARTIST)));
art.setNoalbums(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_ALBUMS))));
art.setNofosongs(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_TRACKS))));
this.aa.add(art);
cursor3.moveToNext();
}
cursor3.close();
}}
Maybe you can try to add this property to you viewpager, in the onCreate method of your MainActivity :
viewPager.setOffscreenPageLimit(fragments.size());
Update
Another thing you could try is:
In your myfragment override getItemPosition in this way:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
And add this code in your onCreate of your MainActivity:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int previousState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (previousState == ViewPager.SCROLL_STATE_SETTLING && state == ViewPager.SCROLL_STATE_IDLE) {
pagerAdapter.notifyDataSetChanged();
}
previousState = state;
}
});
The aim of this code is not to be efficient, but to try to understand your problem.
Hope this can help you
I have listview that populated by Volley and I want to add filter to it without editing adapter class, I did this before but with other custom adapter not populate data from JSON file like this one,
Telephones.class
public class Telephones extends AppCompatActivity {
RequestQueue requestQueue;
private List<tel_list> data = new ArrayList<tel_list>();
private ListView listView;
private TelAdapter adapter;
private EditText telfilter;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telephones);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.actionbar);
listView = (ListView) findViewById(R.id.listview1);
adapter = new TelAdapter(this, data);
listView.setAdapter(adapter);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
telfilter = (EditText) findViewById(R.id.myFilter);
telfilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://10.0.2.2/abb/getphones.php",
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hideprogressDialog();
try {
JSONArray jsonArray = response.getJSONArray("telephones");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject telephones = jsonArray.getJSONObject(i);
tel_list tellist = new tel_list();
tellist.setName(telephones.getString("name"));
tellist.setNumber(telephones.getString("number"));
data.add(tellist);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideprogressDialog();
Log.e("Volley", "Error");
}
}
);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onDestroy() {
super.onDestroy();
hideprogressDialog();
}
private void hideprogressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent intent = new Intent(this, about.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
TelAdapter.class
public class TelAdapter extends ArrayAdapter<tel_list> {
private Context context;
private List<tel_list> telephones;
public TelAdapter(Context context, List<tel_list> data) {
super(context, R.layout.activity_item, data);
telephones = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View item = inflater.inflate(R.layout.activity_item, null);
TextView name = (TextView) item.findViewById(R.id.names);
name.setText(telephones.get(position).getName());
TextView number = (TextView) item.findViewById(R.id.numbers);
number.setText(telephones.get(position).getNumber());
return item;
}
}
am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.