Recyclerview update data, but recyclerview scrolls with freezes - java

When in SettingsActivity switch on to show only selected with checkbox and my List contains near 30 items, recyclerview scrolls normally, but when I use List with 900 items - recyclerview scrolls with freezes. Where my way to update recyclerview is wrong?
Android Studio log:
E/RecyclerView: No adapter attached; skipping layout
I/Choreographer: Skipped 68 frames! The application may be doing too much work on its main thread.
BikesAdapter:
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder>{
private static final String PREFS_NAME = "bikes_prefs";
public static List<Categories> categories;
private Context context;
public BikesAdapter(Context context) {
this.context = context;
notifyDataSetChanged();
}
#Override
public BikesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new BikesViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_bikes, parent, false));
}
#Override
public void onBindViewHolder(final BikesViewHolder holder, final int position) {
final SharedPreferences setFavoritesCnB = FragmentBikesListXT.context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean isFavoriteChB = setFavoritesCnB.getBoolean(categories.get(position).title, false);
holder.cbStars.setChecked(isFavoriteChB);
holder.cbStars.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = setFavoritesCnB.edit();
editor.putBoolean(categories.get(position).title, holder.cbStars.isChecked());
editor.apply();
if (holder.cbStars.isChecked()) {
openDBHelper.save(position);
Constants.CATEGORIES.add(categories.get(position));
} else {
openDBHelper.delete(position);
Constants.CATEGORIES.remove(categories.get(position));
}
}
});
if (checkSwitch) {
if (!isFavoriteChB) {
holder.cardView.setVisibility(View.GONE);
} else {
holder.textTitle.setText(categories.get(position).title);
}
} else holder.textTitle.setText(categories.get(position).title);
holder.textTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(categories.get(position).link));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return categories.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private CheckBox cbStars;
private TextView textTitle;
public BikesViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardView);
cbStars = (CheckBox) itemView.findViewById(R.id.cbStars);
textTitle = (TextView) itemView.findViewById(R.id.tv_title_bike);
}
}
}
Fragment with recyclerview:
public class FragmentBikesListXT extends Fragment {
public static RecyclerView rvBikes;
public static ProgressBar pbBikes;
public static Context context;
public static CreateDBHelper dbHelper;
public static OpenDBHelper openDBHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.fragment_bikes_list_xt, container, false);
rvBikes = (RecyclerView) layout.findViewById(R.id.rvBikes);
pbBikes = (ProgressBar) layout.findViewById(R.id.pbBikes);
SharedPreferences setSwitch = getActivity().getSharedPreferences(PREFS_LIST, MODE_PRIVATE);
checkSwitch = setSwitch.getBoolean("NameOfThingToSave", false);
context = getContext();
dbHelper = new CreateDBHelper(this.getActivity());
openDBHelper = new OpenDBHelper();
initIO(Constants.URL_FULL_LIST);
return layout;
}
public void initIO(String url) {
ParseXT.initializeData(url);
rvBikes.setHasFixedSize(true);
rvBikes.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
}
}
SettingsActivity:
public class SettingsActivity extends AppCompatActivity {
private Switch mSwitch;
public static boolean checkSwitch;
public static final String PREFS_LIST = "list_prefs";
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mSwitch = (Switch) findViewById(R.id.switch_list);
SharedPreferences setSwitch = getSharedPreferences(PREFS_LIST, MODE_PRIVATE);
mSwitch.setChecked(setSwitch.getBoolean("NameOfThingToSave", false));
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
checkSwitch = true;
SharedPreferences.Editor editor = getSharedPreferences(PREFS_LIST, MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}else{
checkSwitch = false;
SharedPreferences.Editor editor = getSharedPreferences(PREFS_LIST, MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
finish();
return super.onOptionsItemSelected(item);
}
}
OpenDBHelper:
public class OpenDBHelper implements IDBHelper {
private SQLiteDatabase db;
#Override
public void read() {
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
BikesAdapter.categories.clear();
Cursor c = db.query(Constants.TABLE_BIKE, null, null, null, null, null, null);
if (c.moveToFirst()) {
int titleColIndex = c.getColumnIndex(Constants.FIELD_TITLE);
int linkColIndex = c.getColumnIndex(Constants.FIELD_LINK);
do {
BikesAdapter.categories.add(new Categories(
c.getString(titleColIndex),
c.getString(linkColIndex)));
Log.d("DBHelper", "READ ID = " + c.getString(titleColIndex));
} while (c.moveToNext());
} else
c.close();
}
#Override
public void save(int position) {
ContentValues cv = new ContentValues();
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
cv.put(Constants.FIELD_TITLE, BikesAdapter.categories.get(position).title);
cv.put(Constants.FIELD_LINK, BikesAdapter.categories.get(position).link);
long size = db.insert(Constants.TABLE_BIKE, null, cv);
Log.d("DBHelper", "SAVE row inserted, size " + size + " ID = , " + BikesAdapter.categories.get(position).title);
FragmentBikesListXT.dbHelper.close();
}
#Override
public void delete(int position) {
db = FragmentBikesListXT.dbHelper.getWritableDatabase();
String[] whereArgs = {String.valueOf(BikesAdapter.categories.get(position).title)};
db.delete(Constants.TABLE_BIKE, Constants.FIELD_TITLE + " = ?", whereArgs);
Log.d("DBHelper", "DELETE ID = " + BikesAdapter.categories.get(position).title);
db.close();
}
}
And parser class:
public class ParseXT {
private static Elements titleTxt;
private static Elements linkTxt;
private static ArrayList<String> titleList = new ArrayList<>();
private static ArrayList<String> linkList = new ArrayList<>();
public static BikesAdapter bikesAdapter = new BikesAdapter(FragmentBikesListXT.context);
public static void initializeData(String url) {
new NewTreadParsed(url).execute();
}
public static class NewTreadParsed extends AsyncTask<List<Categories>, Void, List<Categories>> {
private String url;
public NewTreadParsed(String url) {
this.url = url;
}
#Override
protected List<Categories> doInBackground(List<Categories>... params) {
Document doc;
List<Categories> categories = new ArrayList<>();
try {
doc = Jsoup.connect(url).get();
titleTxt = doc.select(".topictitle");
linkTxt = doc.select(".a[href]");
titleList.clear();
linkList.clear();
for (Element contents : titleTxt) {
titleList.add(contents.text());
}
for (Element contents1 : titleTxt) {
Element element = contents1.select("a[href]").first();
linkList.add(element.attr("abs:href"));
}
}
catch (IOException e){
e.printStackTrace();
}
for (int i = 0; i < titleList.size(); i++) {
categories.add(new Categories(titleList.get(i), linkList.get(i)));
}
return categories;
}
#Override
protected void onPostExecute(List<Categories> categories) {
super.onPostExecute(categories);
FragmentBikesListXT.pbBikes.setVisibility(ProgressBar.INVISIBLE);
BikesAdapter.categories = categories;
FragmentBikesListXT.rvBikes.setAdapter(bikesAdapter);
}
}
}

Use notifyDataSetChanged()
If you are writing an adapter it will always be more efficient to use the more specific change events if you can. Rely on notifyDataSetChanged()

Related

How can ı update items position in SQliteopenhelper

I save my recyclerview with SQliteopenhelper . I use Itemtouchhelper and I can change items positions with itemtouchhelper on recycler view but I cant update positions on my database How Can I ?
todoactivity.java
public class todoactivity extends AppCompatActivity {
TextView title;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback move = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END , 0) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
Collections.swap(Listsx,fromPosition,toPosition);
recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition);
// I want update items position on my SQliteOpenhelper in there
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
};
ItemTouchHelper itemTouchHelperx = new ItemTouchHelper(move);
itemTouchHelperx.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
DatabaseHelper.java
public class DatabaseHelper4 extends SQLiteOpenHelper {
public static final String DATABASE_NAME4 = "mylistxxx.db";
public static final String TABLE_NAME4 = "mylist_dataxxx";
public static final String COL14 = "iDxxx";
public static final String COL24 = "ITEM1xxx";
public DatabaseHelper4(Context context) {
super(context, DATABASE_NAME4, null, 1);
}
#Override
public void onCreate(SQLiteDatabase dbxxx) {
String createTable = "CREATE TABLE " + TABLE_NAME4 + " (iDxxx INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1xxx TEXT)";
dbxxx.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase dbxxx, int oldVersion, int newVersion) {
dbxxx.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME4);
onCreate(dbxxx);
}
public boolean addDataxxx(String textt) {
SQLiteDatabase dbxxx = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL24, textt);
long result = dbxxx.insert(TABLE_NAME4, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase dbxxx = this.getWritableDatabase();
Cursor dataxxx = dbxxx.rawQuery("SELECT * FROM " + TABLE_NAME4, null);
return dataxxx;
}
}
Adapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
Thats my java classes . My activity is todoactivity . My SQliteopenhelper is DatabaseHelper.java . My Adapter is adapter.java . I can change items position on my recyclerview but ı cant update items position on my database . How can I
I suggest adding a column with the position to use for ordering.
Please close the cursor and return a list of objects. You can read your cursor using cursor.getString(cursor.getColumnIndex(colName)). Overriding close in your helper and closing the writableDatabase is also good practise. I myself open the writableDatabase only once (upon create) and close it at the end (upon close).
Regards, Mike

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

Search a RecyclerView that gets its data from an async Task

I've been trying to implement a SearchView in my actionBar that filters a recyclerview that gets its data from an Async task for days now and I cant seem to get it to work.
On all the answers I've seen here gets The adapter for the recycler class is on the same class as the SearchView. but on my app the adapter is in the Async class while the Searchview is in a fragment. I made an Async class because I dont want my UI thread slowing down or crashing when my app is trying to load the items on the RecyclerView. Bellow are my codes, any help would be lovely.
and lastly for my fragment, I have a few codes so ill just cut most of them out and leave whats relevant to the question. Thanks.
for MyAsync.java
public class MyAsync extends AsyncTask<Void,RafTask,Void>{
private RecyclerView recyclerView;
private ProgressBar progressBar;
private Context context;
private static ClientRecycler recycler;
private SearchView searchView;
private ArrayList<RafTask> newLists = new ArrayList<>();
String am;
private static ArrayList<RafTask> raftask = new ArrayList<>();
private static final String TAG = "ListDataActivity";
public MyAsync(RecyclerView recyclerView, ProgressBar progressBar,Context context, ArrayList<RafTask> newList){
this.recyclerView = recyclerView;
this.progressBar = progressBar;
this.context = context;
this.newLists = newList;
}
#Override
protected void onPreExecute() {
recycler = new ClientRecycler(raftask);
recyclerView.setAdapter(recycler);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids) {
MyHelper mHelper = new MyHelper(context,null,null,1);
SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
String Name;
int count = 0;
Cursor c = mHelper.getRafData();
while(c.moveToNext()){
//Database codes
publishProgress(new RafTask(Name,"","",String.valueOf(count),"",""));
return null;
}
#Override
protected void onProgressUpdate(RafTask... value) {
raftask.add(value[0]);
recycler.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
progressBar.setVisibility(View.GONE);
Log.d(TAG, "fragment text pass: " + am);
}
public static void setFilter(ArrayList<RafTask> newList){
// newList = newLists;
raftask = new ArrayList<>();
raftask.addAll(newList);
recycler.notifyDataSetChanged();
}
}
And for the Rafadapter.java
public class RafRecycler extends RecyclerView.Adapter<RafRecycler.MyViewHolder> {
private static ArrayList<RafTask> rafTasks = new ArrayList<>();
public RafRecycler(ArrayList<RafTask> rafTasks){
this.rafasks = rafTasks;
}
#Override
public RafRecycler.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_rafs,parent,false);
return new RafRecycler.MyViewHolder(view);
}
#Override
public void onBindViewHolder(ClientRecycler.MyViewHolder holder, int position) {
holder.name.setText(rafTasks.get(position).get_raftaskname());
holder.id.setText(String.valueOf(rafTasks.get(position).get_raftaskid())+".");
// holder.id.setText(String.valueOf("->"));
holder.m = rafTasks.get(position).get_raftaskid();
}
#Override
public int getItemCount() {
return clientTasks.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView id,name;
String m;
public MyViewHolder(View itemView) {
super(itemView);
id = itemView.findViewById(R.id.txt_id);
name = itemView.findViewById(R.id.txt_name);
m=itemView.toString();
final MyDatabaseHelper mDatabaseHelper = new MyDatabaseHelper(itemView.getContext(),null,null,1);
final boolean clicked = false;
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String names = name.getText().toString();
Cursor c = mHelper.getClientItemID(names);
int itemID = -1;
String email = "";
String address = "";
String shipaddress = "";
String number = "";
while (c.moveToNext()){
//Chech here for the codes to edit all plus numbers
//
//
itemID = c.getInt(0);
address =c.getString(4);
number =c.getString(2);
shipaddress =c.getString(5);
email =c.getString(3);
}
if(itemID >-1){
Log.d(TAG, "onItemClick: The id is: " + itemID);
Log.d(TAG, "onItemClick: The desc is: " + address);
Log.d(TAG, "onItemClick: The price is: " + shipaddress);
Intent editScreenIntent = new Intent(v.getContext(), EditClientActivity.class);
editScreenIntent.putExtra("id", itemID);
editScreenIntent.putExtra("name", names);
editScreenIntent.putExtra("number", number);
editScreenIntent.putExtra("address", address);
editScreenIntent.putExtra("email", email);
editScreenIntent.putExtra("shipaddress", shipaddress);
v.getContext().startActivity(editScreenIntent);
((MainActivity) v.getContext()).overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}else{
Toast.makeText(v.getContext(),"No idd clicked", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void setFilter(ArrayList<ClientTask> newList){
clientTasks = new ArrayList<>();
clientTasks.addAll(newList);
notifyDataSetChanged();
}
}
And lastly my fragment.java
public class ClientFragment extends Fragment implements SearchView.OnQueryTextListener {
private static final String TAG = "ListDataActivity";
MyDatabaseHelper mDatabaseHelper;
private ProgressBar progressBar;
private RecyclerView recyclerView;
public static SearchView searchView;
static String am;
private MenuItem menua;
public static ArrayList<ClientTask> newList;
RecyclerView.LayoutManager layoutManager;
public BackgroundAsync backgroundAsync;
private ArrayList<ClientTask> clienttask = new ArrayList<>();
ClientRecycler recycler;
private ListView mListView;
Button opencon;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ClientFragment() {
// Required empty public constructor
}
public static ClientFragment newInstance(String param1, String param2) {
ClientFragment fragment = new ClientFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onPrepareOptionsMenu(Menu menu){
am="asdf";
MenuItem menuItem = menu.findItem(R.id.mysearchbtn);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
Log.d(TAG, "onCreateFragment ");
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (getArguments() != null) {
setRetainInstance(true);
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_client, container, false);
progressBar = view.findViewById(R.id.progressbar);
recyclerView = view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recycler = new ClientRecycler(clienttask);
opencon = view.findViewById(R.id.opencon);
opencon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddClient.class);
startActivity(intent);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
// Toast.makeText(context, " Off", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
newList = new ArrayList<>();
for (ClientTask clientTask : clienttask) {
String name = clientTask.get_clienttaskname().toLowerCase();
if (name.contains(newText)) {
Log.d(TAG, "u get any: "+ name);
newList.add(clientTask);
}else{
Log.d(TAG, "we aint got shit: "+ name);
}
}
Log.d(TAG, "the usual fail ");
recyclerView.setAdapter(recycler);
return true;
}
void filter(String text){
ArrayList<ClientTask> newList = new ArrayList();
for (ClientTask c : clienttask) {
// String name = clientTask.get_clienttaskname().toLowerCase();
if (c.get_clienttaskname().contains(text)) {
newList.add(c);
}
Log.d(TAG, "the usual fail ");
BackgroundAsync.setFilter(newList);
recyclerView.setAdapter(recycler);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
new BackgroundAsync(recyclerView,progressBar,getActivity(),newList).execute();
}
}
Some parts of my code may be quite unecessary to solve my problem, but I've tried so many fixes that didn't work and as a result, I have some weird looking implementations.Sorry for the trouble and again, thanks for thew help.
I managed to solve the problem by Moving the Async task class into the Fragment class So they share the same variables. I cleared all the input in the constructor so it became new BackgroundBsync().execute();. That solved it and I am now able to search all the data with a separate method i made in the Rafadapter class. the codes are below.
public void setFilter(ArrayList<ClientTask> newList){
clientTasks = new ArrayList<>();
clientTasks.addAll(newList);
notifyDataSetChanged();
}
so all i needed to add in my onQueryTextChange was to add a few lines of code
newText = newText.toLowerCase();
ArrayList<ClientTask> newList = new ArrayList();
for (ClientTask c : clienttask) {
String name = c.get_clienttaskname().toLowerCase();
if (name.contains(newText)) {
newList.add(c);
}
Log.d(TAG, "the usual fail ");
}
recycler.setFilter(newList);
return true;
And it solved my problem. Please note that RafAdapter is the same as ClientRecycler.

Fail to solve E/RecyclerView: No adapter attached; skipping layout

When back to previous activity or I get out the app is closed and show this error:
E/RecyclerView: No adapter attached; skipping layout
Within a asycntask in his method onPostExecute I declare a recycleview and RecyclerView.LayoutManager but no have idea what it's wrong. I need your help to solve this problem. Below is my code:
#Override
public void onPostExecute(List<Modules> result) {
if (pDialog.isShowing()){
RecyclerView.LayoutManager Manager =new LinearLayoutManager(DepartureModule.this);
RecyclerView.Adapter adapter = new ModuleAdapter(result);
RecyclerView RVODetails = (RecyclerView) findViewById(R.id.RVODetails);
RVODetails.setLayoutManager(Manager);
RVODetails.setAdapter(adapter);
pDialog.dismiss();
}
and this is my adapter class:
public class ModuleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
public final ImageButton Actions;
public final ImageView Image;
public final TextView ModuleCode;
public final TextView ModuleDescription;
public final TextView ModuleDate;
public String ModuleIds;
public ModuleViewHolder(View itemView) {
super(itemView);
Image = (ImageView)itemView.findViewById(R.id.logo);
Actions = (ImageButton)itemView.findViewById(R.id.Actions);
//TitleModuleCode = (TextView)itemView.findViewById(R.id.TitleModuleCode);
ModuleCode = (TextView)itemView.findViewById(R.id.ModuleCode);
//TitleModuleDescription = (TextView)itemView.findViewById(R.id.TitleModuleDescription);
ModuleDescription = (TextView)itemView.findViewById(R.id.ModuleDescription);
ModuleDate = (TextView)itemView.findViewById(R.id.ModuleDate);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
this.itemClickListener.OnItemClick(view,getLayoutPosition());
// Toast.makeText(view.getContext(), "POS" + getLayoutPosition()
// , Toast.LENGTH_LONG).show();
}
public void setItemClickListener(ItemClickListener ItemClick){
this.itemClickListener = ItemClick;
}
}
public ModuleAdapter(List<Modules> Items){
this.Items = Items;
}
#Override
public int getItemCount() {
return Items.size();
}
#Override
public ModuleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_cardview,viewGroup,false);
return new ModuleViewHolder(view);
}
#Override
public void onBindViewHolder(final ModuleViewHolder ViewHolder, final int position) {
context = ViewHolder.itemView.getContext();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"fonts/CaviarDreams.ttf");
ViewHolder.Image.setImageResource(Items.get(position).getImages());
ViewHolder.Actions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowPopupMenu(ViewHolder.Actions,position,ViewHolder);
}
});
ViewHolder.ModuleCode.setText(Items.get(position).getModule());
ViewHolder.ModuleCode.setTypeface(typeface); ViewHolder.ModuleDescription.setText(Items.get(position).getDescription());
ViewHolder.ModuleDescription.setTypeface(typeface);
ViewHolder.ModuleDate.setText(Items.get(position).getDate());
ViewHolder.ModuleDate.setTypeface(typeface);
ViewHolder.ModuleIds = Items.get(position).getModuleIds();
ViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void OnItemClick(View view, int Pos) {
//Toast.makeText(context, "POSITION :" + Pos, Toast.LENGTH_SHORT).show();
}
});
}
private void ShowPopupMenu (final View view, final int position,final ModuleViewHolder holder){
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.action_modify:
final Connection connectionupdate = new Connection(context,Connection.DATABASE_NAME,null,
Connection.DATABASE_VERSION);
final SQLiteDatabase dbUpdate = connectionupdate.getWritableDatabase();
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/CaviarDreams.ttf");
AlertDialog.Builder ModifyModule = new AlertDialog.Builder(context);
LayoutInflater modifyinflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
final View viewmodify = modifyinflater.inflate(R.layout.layout_custom_dialog_create_modules,null);
TILM = (TextInputLayout)viewmodify.findViewById(R.id.TILM);
TILM.setTypeface(typeface);
TILD = (TextInputLayout)viewmodify.findViewById(R.id.TILD);
TILD.setTypeface(typeface);
ModuleCodeE = (EditText)viewmodify.findViewById(R.id.ModuleCode);
ModuleCodeE.setTypeface(typeface);
ModuleDescE = (EditText)viewmodify.findViewById(R.id.ModuleDesc);
ModuleDescE.setTypeface(typeface);
ModuleCodeE.setText(Items.get(position).getModule());
ModuleDescE.setText(Items.get(position).getDescription());
final String Id = Items.get(position).getModuleIds();
ModifyModule.setView(viewmodify);
ModifyModule.setIcon(R.drawable.logomini);
ModifyModule.setTitle("Construmuebles FM");
ModifyModule.setMessage(" Modifica los valores en los siguientes campos :");
ModifyModule.setPositiveButton("Actualizar", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ContentValues VUpdate = new ContentValues();
VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_CODE,ModuleCodeE.getText().toString()); VUpdate.put(Database.CamposModuloDetails.KEY_MODULE_DESC,ModuleDescE.getText().toString());
long IdUpdate = dbUpdate.update(Database.MODULE_DETAILS_TABLE,VUpdate,Database.CamposModuloDetails
.KEY_MODULE_DETAILS_ID + " = ?",new String []{Id});
new UpdateCardView(context,IdUpdate).execute();
dialogInterface.dismiss();
}
});
ModifyModule.setNegativeButton("Cancelar", new DialogInterface
.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
ModifyModule.show();
return true;
case R.id.action_delete:
new DeleteCardView(context,holder,position).execute();
return true;
}
return false;
}
});
menu.show();
}
class DeleteCardView extends AsyncTask<Void,Void,Long>{
private ProgressDialog pDialog;
ModuleViewHolder holder;
int position;
public DeleteCardView(Context context,ModuleViewHolder holder,int position) {
pDialog = new ProgressDialog(context);
this.holder = holder;
this.position = position;
}
#Override
protected void onPreExecute() {
pDialog.setMessage(" Eliminado registro...");
pDialog.show();
}
#Override
protected Long doInBackground(Void... voids) {
String ModuleIdCardView = holder.ModuleIds;
Connection connection = new Connection(context, Connection.DATABASE_NAME, null,
Connection.DATABASE_VERSION);
long i = connection.DeleteByIdCardView(ModuleIdCardView);
if (i != 0) {
return i;
} else {
return i;
}
}
#Override
protected void onPostExecute(Long Result) {
if (pDialog.isShowing()){
pDialog.dismiss();
Items.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,Items.size());
if (Items.size()==0){ /**viewPager.setCurrentItem(0);**/ }
}
}
}
}
Rearrange your code as follows
recyclerView = (RecyclerView) findViewById(R.id.RVODetails);
mAdapter = new ModuleAdapter(result);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}

No data in Listview with contentprovider

I'm working on a class project in Java, exploring the use of the ContentProvider class for moving data between apps. We're making a basic CRUD app, with SQLite storage and a ContentProvider to move data to a second app. My debugging shows that my SQLite inserts seem to be working and building my database, but my ListView will not populate. It gives a spinning loading ring forever, which is not an issue I usually see with ListView. I've double- and tripple- checked that the adapter is in place, and I use a part of my loadData() method to create a list of item objects from the database which I can't find a problem with. I'm not sure where else the issue could be coming from.
MainActivity:
public static DatabaseHelper helper;
public static ItemProvider provider;
static Button addNew;
public static final int NEXT_REQUESTCODE = 1;
static ListFragment frag;
static ArrayList<ItemObject> items = new ArrayList<ItemObject>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new DatabaseHelper(this);
provider = new ItemProvider(helper);
FragmentManager mgr = getFragmentManager();
FragmentTransaction trans = mgr.beginTransaction();
final Context context = this.getApplicationContext(); //to pass as context
frag = ListFragment.newInstance(context, items);
frag.loadData();
trans.replace(R.id.fragment_container, frag, ListFragment.TAG);
addNew = (Button) findViewById(R.id.addNew);
addNew.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addActivity = new Intent(context, FormActivity.class); //sets intent for addactivity
startActivityForResult(addActivity, NEXT_REQUESTCODE); //starts activity expecting response
}
});
}
//handles response from addactivity
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK && requestCode == NEXT_REQUESTCODE) {
Bundle result = data.getExtras();
ItemObject placeholder = new ItemObject(result.getString("weight"), result.getInt("steps"), result.getString("date")); //builds the object to be added to the list from addactivity response
frag.addObject(placeholder); //adds the object to the list
}
}
Context getContext() {
return this.getContext();
}
}
SQLiteOpenHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_FILE = "database.db";
private static final int DATABASE_VERSION = 1;
public static SQLiteDatabase db;
SQLiteDatabase.CursorFactory factory;
private static final String DROP_TABLE = "DROP TABLE IF EXISTS item_table";
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS item_table ( _id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, steps INTEGER, weight TEXT)";
public DatabaseHelper(Context c) {
super(c, DATABASE_FILE, null, DATABASE_VERSION);
db = getWritableDatabase();
// db.execSQL(DROP_TABLE);
db.execSQL(CREATE_TABLE);
//db.openOrCreateDatabase(DATABASE_FILE, factory);
}
#Override
public void onCreate(SQLiteDatabase _db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addItem(ContentValues v)
{
}
}
ListFragment class
public class ListFragment extends Fragment {
public static final String TAG = "ListFragment.TAG";
public static ArrayList<ItemObject> items = new ArrayList<ItemObject>();
static ListView itemList;
static ItemAdapter adapter;
static int selectedPosition;
public static final int NEXT_REQUESTCODE = 2;
static Context context;
static ArrayList<ItemObject> placeholder;
static MainActivity activity;
static Uri uri = Uri.EMPTY;
//constructor
public static ListFragment newInstance(Context _context, ArrayList<ItemObject> _items) {
ListFragment fragment = new ListFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View theView = inflater.inflate(R.layout.list_fragment_layout, parent, false);
//create and attach custom adapter
MainActivity activity = (MainActivity) getActivity();
context = activity.getContext();
itemList = (ListView) theView.findViewById(R.id.itemList);
adapter = new ItemAdapter(context, items);
itemList.setAdapter(adapter);
itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
selectedPosition = position;
openView(items.get(position));
}
});
loadData();
adapter.notifyDataSetChanged();
return theView;
}
//function for opening the "View details" view
public void openView(ItemObject selected) {
Intent detailActivity = new Intent(getActivity(), DetailActivity.class);
detailActivity.putExtra("weight", selected.getWeight());
detailActivity.putExtra("steps", selected.getSteps());
detailActivity.putExtra("date", selected.getDate());
detailActivity.putExtra("position", selectedPosition);
startActivityForResult(detailActivity, NEXT_REQUESTCODE);
}
public void saveItem(ItemObject _item) {
ContentValues v = new ContentValues();
v.put("weight", _item.getWeight());
v.put("steps", _item.getSteps());
v.put("date", _item.getDate());
activity.provider.insert(uri, v);
loadData();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void loadData() {
String[] columns = new String[]{"weight","steps","date"};
Uri destination = Uri.parse(Environment.getDataDirectory().toString()+"/data/ContentProviderApp/database.db");
Cursor c = activity.provider.query(destination, columns, null, null, null, null);
if(c != null)
{
c.moveToFirst();
ArrayList<ItemObject> placeholder = new ArrayList<ItemObject>();
for(int i = 0; i < c.getCount(); i++)
{
int x = c.getCount();
ItemObject newItem = new ItemObject(c.getString(3),c.getInt(2), c.getString(1));
placeholder.add(newItem);
c.moveToNext();
}
items = placeholder;
}
}
public void deleteData() {
}
public void updateData() {
}
//handles a delete request from "view" activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == getActivity().RESULT_OK && requestCode == NEXT_REQUESTCODE) {
Bundle result = data.getExtras();
adapter.notifyDataSetChanged();
}
}
//Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon screen orientation changes).
public ListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
//adds an object passed in from the activity
public void addObject(ItemObject _item) {
saveItem(_item);
//items.add(_item);
//adapter.notifyDataSetChanged();
//saveData();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
// mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
// mListener = null;
}
}
ContentProvider class
public class ItemProvider extends ContentProvider {
DatabaseHelper helper;
public ItemProvider() {
}
public ItemProvider(DatabaseHelper _helper) {
helper = _helper;
}
#Override
public boolean onCreate() {
return false;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return helper.db.query("item_table", null, null, null, null, null, null, null);
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
helper.db.insert("item_table", null, values);
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
helper.db.delete("item_table", selection, selectionArgs);
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
helper.db.update("item_table", values, selection, selectionArgs);
return 0;
}
}
ItemAdapter class
public class ItemAdapter extends BaseAdapter {
private Context context;
private static final long ID_CONSTANT = 0x666666L;
private ArrayList<ItemObject> items;
public ItemAdapter()
{
}
public ItemAdapter(Context _context, ArrayList<ItemObject> _items)
{
context = _context;
items = _items;
}
#Override
public int getCount() {return items.size();}
#Override
public ItemObject getItem(int _position) {return items.get(_position);}
#Override
public long getItemId(int _position) { return ID_CONSTANT + _position;}
#Override
public View getView (int _position, View _convertView, ViewGroup _parent) {
if(_convertView == null) {
_convertView = LayoutInflater.from(context).inflate(R.layout.item_layout, _parent, false);
}
ItemObject item = getItem(_position);
TextView text = (TextView) _convertView.findViewById(R.id.weight);
text.setText(item.getWeight().toString());
text = (TextView) _convertView.findViewById(R.id.steps);
text.setText(Integer.toString(item.getSteps()));
text = (TextView) _convertView.findViewById(R.id.date);
text.setText(item.getDate().toString());
return _convertView;
}
}
I believe the problem is in the loadData method:
items = placeholder;
It should be items.addAll(placeholder).
Did you get a chance to test this?
In loadData() after the line item = placeholder add adapter.notifyDataSetChanged();.

Categories

Resources