How to fetch data from another classes via Adapter in Android - android

Here I'm trying to make a quiz application without using databases (requirement). Each question has 4 options.
I had made a class for Questions. Now, in the activity in which I want to show my data, I'm unable to get method to fetch the data from the QuestionModelClass.
I had made 2D Array but it gets more complicated to get it. Is there any way to bind 3 of the classes (QuestionModelClass, Adapter class, and Activity class)?
public class QuestionsModelClass {
private String sQuestion;
private String sRightAnswer;
private List<String> sOptions;
QuestionsModelClass(){
sQuestion = null;
sRightAnswer = null;
sOptions = null;
}
public QuestionsModelClass(String sQuestion, String sRightAnswer, List<String> sOptions) {
this.sQuestion = sQuestion;
this.sRightAnswer = sRightAnswer;
this.sOptions = sOptions;
}
public String getsQuestion() {
return sQuestion;
}
public void setsQuestion(String sQuestion) {
this.sQuestion = sQuestion;
}
public String getsRightAnswer() {
return sRightAnswer;
}
public void setsRightAnswer(String sRightAnswer) {
this.sRightAnswer = sRightAnswer;
}
public List<String> getsOptions() {
return sOptions;
}
public void setsOptions(List<String> sOptions) {
this.sOptions = sOptions;
}
}
And my Adapter Class
public class QuizAdapter extends BaseAdapter {
private Context context;
private List<QuestionsModelClass> questionClassList;
private String[][] options;
private LayoutInflater inflater;
private QuizAdapter(Context c, List<QuestionsModelClass> l){
this.context= c;
this.questionClassList = l;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return questionClassList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.questionpattern, parent,false);
QuestionsModelClass questions = questionClassList.get(position);
TextView quesText= convertView.findViewById(R.id.questionTextView);
RadioButton radioButtonA = convertView.findViewById(R.id.optionA);
RadioButton radioButtonB = convertView.findViewById(R.id.optionB);
RadioButton radioButtonC = convertView.findViewById(R.id.optionC);
RadioButton radioButtonD = convertView.findViewById(R.id.optionD);
return convertView;
}
And this is the Activity class in which I am trying to implement all the functions
public class QuizActivity extends Activity {
final Context context= this;
private List<QuestionsModelClass> classObject;
Button okayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
String[] question= new String[]{"Q1. ABDE", "Q2. ADDASD"};
String[][] op;
String[] right = new String[]{"abc","def"};
classObject = new ArrayList<>();
op= new String[][]{
{"a1", "2", "3", "4"},
{"b1","b2","b3","b4"}};
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.customdialoguebox);
dialog.show();
okayButton = (Button) dialog.findViewById(R.id.okayButton);
okayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,"Good Luck!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}

Related

How to check if an item already exists in a Room Database?

I have this adapter with a button that dependent on if a object already exists in my Room Database or not will have a differente behavior when it´s clicked. Basically what I want to do is if the object exists I want to remove it. In case it doesn´t I want to add it to my database. I created this method in Dao and a Task to check the existence. Since the Task is asynchronous ,how can I do the verification?
My Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.RestaurantViewHolder> {
private Context mContext;
private List<Restaurant_> mRestaurants;
private Activity act;
private FirebaseAuth mAuth;
private String currentUserId;
private View rView;
public RestaurantAdapter(Context context, List<Restaurant_> restaurants, Activity activity) {
mRestaurants = restaurants;
mContext = context;
act = activity;
}
#Override
public RestaurantViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get layout inflater from context
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate layout
rView = inflater.inflate(R.layout.item_restaurant, parent, false);
// Return a new holder instance
return new RestaurantViewHolder(rView);
}
#Override
public void onBindViewHolder(RestaurantViewHolder viewHolder, final int position) {
// Get the data model based on position
final Activity activity = act;
final Restaurant_ restaurant = mRestaurants.get(position);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
final TextView name = viewHolder.nameTextView;
name.setText(restaurant.getName());
final TextView rating = viewHolder.ratingTextView;
rating.setText((restaurant.getUserRating().getAggregateRating()));
final TextView distance = viewHolder.distanceTextView;
distance.setText(String.valueOf(restaurant.getDistance()) + " Km");
final ImageButton addToWishlistButton = viewHolder.addToWishlistButton;
addToWishlistButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Wishlist wishlist = new Wishlist(currentUserId, restaurant.getId());
//if(alreadyExists){
//RemoveWLTask rlt=new RemoveWLTask(wishlist,activity);
//rlt.execute()
// }
// else{
AddWLTask wlt = new AddWLTask(wishlist, activity);
wlt.execute();
//}
}
});
final ImageButton addToFavoritesButton = viewHolder.addToFavoritesButton;
addToFavoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToFavoritesButton.getBackground().setTint(activity.getResources().getColor(R.color.red));
addToFavorites();
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LiveFragment.getListener().onRestaurantClicked(restaurant.getId());
}
});
}
#Override
public int getItemCount() {
return mRestaurants.size();
}
public class RestaurantViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView ratingTextView;
public TextView distanceTextView;
public ImageButton addToWishlistButton;
public ImageButton addToFavoritesButton;
public RestaurantViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.restaurantName);
ratingTextView = itemView.findViewById(R.id.restaurantRating);
distanceTextView = itemView.findViewById(R.id.restaurantDistance);
addToWishlistButton = itemView.findViewById(R.id.button_wishlist);
addToFavoritesButton = itemView.findViewById(R.id.button_favorites);
}
}
}
My DAO
#Dao
public interface DAO {
#Insert
public void addToWishlist(Wishlist wishlist);
#Delete
public void deleteFromWishlist(Wishlist wishlist);
#Query("Select restaurantId From wishlist Where userId=:id")
public String[] loadWishlist(String id);
#Query("Select restaurantId From wishlist where userId=:userID AND restaurantId=:restaurantID")
public String[]checkExists(String userID, String restaurantID);
}
##My Task ##
public class CheckWLTask extends AsyncTask<Void, Void, Void> {
private DB db;
private Activity activity;
private String userId;
private String restaurantId;
private String [] response;
public CheckWLTask(Activity activity, String idUser, String idRestaurant) {
this.activity = activity;
this.userId = idUser;
this.restaurantId = idRestaurant;
db = Room.databaseBuilder(activity.getApplicationContext(), DB.class, "sample-db").build();
}
#Override
protected Void doInBackground(Void... voids) {
while (!isCancelled()) {
this.response=db.daoAcess().checkExists(userId,restaurantId);
break;
}
return null;
}
}
``

Android Dagger2 Dependency Injection on CustomAdapter

I learn Dependency Injection using Dagger2 in my android code, I dont have any trouble using it until I try to inject the presenter in my CustomAdapter for ListView, it always return Null Value. The purpose is I want to execute the Presenter function when someone click the ListView Item. This is my CustomAdapter Looks like :
public class CustomAdapter extends BaseAdapter {
ArrayList<String> contactNameList, listGroup;
Context context;
ArrayList<Bitmap> contactImages;
ArrayList<Integer> listContactId;
private static LayoutInflater inflater=null;
#Inject
DetailScreenPresenter detailScreenPresenter;
public CustomAdapter(MainActivity mainActivity, ArrayList<String> contactNameList, ArrayList<Bitmap> contactImages, ArrayList<String> listGroup, ArrayList<Integer> listContactId)
{
this.contactNameList = contactNameList;
context = mainActivity;
this.contactImages = contactImages;
this.listGroup = listGroup;
this.listContactId = listContactId;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return contactNameList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class Holder
{
public Holder(View view,Context context)
{
ButterKnife.bind(this,view);
}
#BindView(R.id.txtName)
TextView tvName;
#BindView(R.id.txtGroup)
TextView tvGroup;
#BindView(R.id.imageProfile)
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView;
rowView = inflater.inflate(R.layout.contact_list, null);
Holder holder=new Holder(rowView, context);
holder.tvName.setText(contactNameList.get(position));
holder.img.setImageBitmap(contactImages.get(position));
holder.tvGroup.setText(listGroup.get(position));
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
detailScreenPresenter.loadDetail(listContactId.get(position));
}
});
return rowView;
}
}
and this is the MainActivity that trigger the CustomAdapter
public class MainActivity extends AppCompatActivity implements MainScreenContact.View {
#BindView(R.id.listContact)
ListView listView;
ArrayList<String> listName;
ArrayList<Bitmap> listImage;
ArrayList<String> listGroup;
ArrayList<Integer> listContactId;
HashMap<Integer, Bitmap> tempImageArray;
String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
#Inject
MainScreenPresenter mainPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
listName = new ArrayList<>();
listImage = new ArrayList<>();
tempImageArray = new HashMap<>();
listGroup = new ArrayList<>();
listContactId = new ArrayList<>();
DaggerMainScreenComponent.builder()
.netComponent(((App) getApplicationContext()).getNetComponent())
.mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
.build().inject(this);
mainPresenter.loadPost();
}
#Override
public void showPosts(List<Post> posts) {
Collections.sort(posts, new Comparator<Post>() {
#Override
public int compare(Post post1, Post post2) {
String name1=post1.getFirstName()+" "+post1.getLastName();
String name2=post2.getFirstName()+" "+post2.getLastName();
return name1.compareToIgnoreCase(name2);
}
});
int indexGroup=0;
for (int i = 0; i < posts.size(); i++) {
if(posts.get(i).getProfilePic().contains("http"))
mainPresenter.loadImage(posts.get(i).getProfilePic(), i);
else
mainPresenter.loadImage("http://example.com", i);
if(Arrays.binarySearch(letter,Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase())==-1)
{
if(listGroup.size()==0)
listGroup.add("*");
else
listGroup.add(" ");
}
else
{
if(!listGroup.get(indexGroup).equalsIgnoreCase(Character.toString(posts.get(i).getFirstName().charAt(0)))) {
listGroup.add(Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase());
indexGroup = i;
}
else
listGroup.add(" ");
}
listContactId.add(i, posts.get(i).getId());
listName.add(i, posts.get(i).getFirstName() + " " + posts.get(i).getLastName());
}
}
#Override
public void showError(String message) {
Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_LONG).show();
}
#Override
public void showComplete() {
Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
}
#Override
public void setImageProfile(Bitmap profileBmp, int x) {
tempImageArray.put(x, profileBmp);
if(tempImageArray.size()==listName.size())
{
SortedSet<Integer> keys = new TreeSet<Integer>(tempImageArray.keySet());
for(Integer key : keys)
{
listImage.add(tempImageArray.get(key));
}
listView.setAdapter(new CustomAdapter(this, listName, listImage, listGroup, listContactId));
}
}
}
Please help how to inject the DetailScreenPresenter presenter.
Thanks alot
In general, in order to perform injection into any Object, you should explicitly call <some_dagger_component>.inject(<target_object>).
In your case, you could do it this way:
CustomAdapter adapter = new CustomAdapter(this, listName, listImage, listGroup, listContactId);
DaggerMainScreenComponent.builder()
.netComponent(((App) getApplicationContext()).getNetComponent())
.mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
.build().inject(adapter);
listView.setAdapter(adapter);
However, what you're trying to do is an abuse of dependency injection framework - you should not perform injection into adapter, but simply pass the required objects to adapter's constructor.
In this post you can find additional information about dependency injection in Android.

ListView is not refreshing

I've got problem with my ListView. I'm creating new object and add it to the database by clicking button in the first fragment. In the second fragment I've got listview with objects from my database. Everything works fine but listView in the second fragment doesn't refresh - I see new objects only after restarting app. All solutions like : notifyDataSetChanged don't work :/
Here's my adapter from first fragment:
public class ConcertAdapter extendsRecyclerView.Adapter<ConcertAdapter.MyViewHolder> {
private static final String FRAGMENT_TAG = "fragmentTag";
private static final String TAG = ConcertAdapter.class.getSimpleName() ;
private LayoutInflater inflater;
private Context context;
private List<Concert> concertList = new ArrayList<>();
private DatabaseHelper mDatabaseHelper = null;
private int selectedRecordPosition = -1;
private MainActivity mActivity;
public ConcertAdapter(Context context, List<Concert> concerts, MainActivity mainActivity) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
this.mActivity = mainActivity;
}
public void setListConcert(ArrayList<Concert> concertList) {
this.concertList = concertList;
notifyItemRangeChanged(0, concertList.size());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.from(parent.getContext()).inflate(R.layout.concert_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final float screenWidthPx = holder.itemView.getResources().getDisplayMetrics().widthPixels;
Concert current = concertList.get(position);
Log.d("mLog", current.getUrl());
holder.mImage.setImageUrl(current.getUrl(), MySingleton.getInstance().getImageLoader());
holder.mImage.getLayoutParams().height = (int) (screenWidthPx * 0.50);
holder.mFav_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
final Concert favConcert = new Concert();
favConcert.setTitle(concertList.get(position).getTitle());
favConcert.setContent(concertList.get(position).getContent());
favConcert.setDate(concertList.get(position).getDate());
favConcert.setUrl(concertList.get(position).getUrl());
try {
final Dao<Concert, Integer> concertDao = getHelper().getConcertDao();
concertDao.create(favConcert);
}catch (SQLException e) {
e.printStackTrace();
}
}
}
});
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date concertDate = new Date();
try {
concertDate = format.parse(current.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
String s = String.valueOf(days);
holder.mDate_btn.setText(s + " dni");
if (s.equals("0")) {
holder.mDate_btn.setText("dziś :)");
}
}
#Override
public int getItemCount() {
return concertList.size();
}
public void setConcerts(List<Concert> concerts) {
concertList = new ArrayList<>(concerts);
}
public void showDisplay(int position) {
Bundle bundle = new Bundle();
bundle.putInt("position", position);
bundle.putString("content", concertList.get(position).getContent());
bundle.putString("date", concertList.get(position).getDate());
bundle.putString("url", concertList.get(position).getUrl());
bundle.putString("title", concertList.get(position).getTitle());
Fragment fragment = new DisplayConcertFragment();
fragment.setArguments(bundle);
mActivity.replaceFragment(fragment);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView mImage;
public Button mDate_btn;
public TextView mBubble;
public ToggleButton mFav_btn;
public ImageView mBubbleImage;
private ConcertFragment mConcertFragment;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (NetworkImageView) itemView.findViewById(R.id.concerts_niv);
mDate_btn = (Button) itemView.findViewById(R.id.date_btn);
mImage.setOnClickListener(this);
mFav_btn = (ToggleButton) itemView.findViewById(R.id.fav_btn);
}
#Override
public void onClick(View v) {
showDisplay(getAdapterPosition());
//ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
}
public Concert removeItem(int position) {
final Concert concert = concertList.remove(position);
notifyItemRemoved(position);
return concert;
}
}
private DatabaseHelper getHelper() {
if (mDatabaseHelper == null) {
mDatabaseHelper = OpenHelperManager.getHelper(context,DatabaseHelper.class);
}
return mDatabaseHelper;
}
Here's my second adapter:
public class FavAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private List mRecords;
private Dao<Concert, Integer> concertDao;
private Button mDateButton;
private NetworkImageView mImage;
public FavAdapter(Context context, int resource, List objects, Dao<Concert, Integer> concertDao) {
super(context, resource, objects);
this.mRecords = objects;
this.concertDao = concertDao;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = mInflater.inflate(R.layout.concert_item, parent, false);
if(mRecords.get(position).getClass().isInstance(new Concert())){
final Concert concert = (Concert) mRecords.get(position);
mImage =((NetworkImageView)convertView.findViewById(R.id.concerts_niv));
mImage.setImageUrl(concert.getUrl(), MySingleton.getInstance().getImageLoader());
final float screenWidthPx = mImage.getResources().getDisplayMetrics().widthPixels;
mImage.getLayoutParams().height = (int) (screenWidthPx * 0.50);
mDateButton = (Button) convertView.findViewById(R.id.date_btn);
Date concertDate = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
concertDate = format.parse(concert.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
String s = String.valueOf(days);
mDateButton.setText(s + " dni");
if (s.equals("0")) {
mDateButton.setText("dziś :)");
}
// ((TextView)convertView.findViewById(R.id.teacher_tv)).setText(studentDetails.teacher.teacherName);
}
return convertView;
}
}
And here's my second fragment with ListView:
public class FavFragment extends Fragment {
private static final String TAG = FavFragment.class.getSimpleName() ;
private DatabaseHelper mDatabaseHelper = null;
private ListView mListView;
private int selectedRecordPosition = -1;
private Dao<Concert, Integer> concertDao;
private List<Concert> concertList;
private MainActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fav_layout, container, false);
mListView = (ListView)v.findViewById(R.id.concerts_lv);
mActivity = (MainActivity) getContext();
try {
concertDao = getHelper().getConcertDao();
concertList = concertDao.queryForAll();
FavAdapter adapter = new FavAdapter(getContext(), R.layout.concert_item, concertList, concertDao);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mListView.invalidateViews();
mListView.refreshDrawableState();
} catch (SQLException e) {
e.printStackTrace();
}
Log.e(TAG, "onCreateView notify");
return v;
}
private DatabaseHelper getHelper() {
if (mDatabaseHelper == null) {
mDatabaseHelper = OpenHelperManager.getHelper(getContext(), DatabaseHelper.class);
}
return mDatabaseHelper;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mDatabaseHelper != null) {
OpenHelperManager.releaseHelper();
mDatabaseHelper = null;
}
}
}
Here's my first fragment
public class ConcertFragment extends Fragment implements MyBackPressed {
private static final String FRAGMENT_TAG = "fragmentTag";
private static final String TAG = ConcertFragment.class.getSimpleName() ;
public ProgressBar progress;
private ConcertLoader concertLoader;
private RecyclerView recyclerView;
private Context mContext;
private android.support.v4.app.FragmentManager mFragmentManager;
private MainActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
JodaTimeAndroid.init(getContext());
View v = inflater.inflate(R.layout.fragment_concert_layout, container, false);
progress = (ProgressBar) v.findViewById(R.id.progressBar);
recyclerView = (RecyclerView) v.findViewById(R.id.concerts_rv);
concertLoader = new ConcertLoader(ConcertFragment.this);
mActivity = (MainActivity) getContext();
futureConcerts();
return v;
}
public void futureConcerts() {
concertLoader.execute();
getActivity().getWindow().getDecorView().getRootView().setClickable(false);
}
public void notifyAboutListCreation(List<Concert> res) {
ConcertAdapter adapter = new ConcertAdapter(getActivity().getApplicationContext(), res, mActivity);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
progress.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
getActivity().finish();
}
}
I had similar problems a while ago. Are you triggering any UI updates from non-UI threads? Maybe from within listeners? Try using the following code where the UI updates are triggered.
runOnUiThread(new Runnable(){
#Override
public void run(){
...
adapter.notifyDataSetChanged();
mListView.invalidateViews();
mListView.refreshDrawableState();
...
}
});
Personally, I now have started to wrap any problematic code blocks in a generic try-catch block that catches Exception and see if there are any exceptions I migh thave overseen (using logcat on terminal with tag filter).
(Cannot comment yet, so answering in this way)

How to show Images in Gridview using pulltorefresh class

I can show images in gridview normally. However, I want to use pulltorefresh functionality and I found a library to get the functionality. I am confused how to integrate my images.
Now, the gridview just shows imagelinks in the array. How can I use imageAdapter instead of arrayAdapter to show the Images?
Thanks a lot.
This is the activity class:
public final class PullToRefreshGridActivity extends Activity {
static final int MENU_SET_MODE = 0;
private LinkedList<String> mListItems;
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private ArrayAdapter<String> mAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefreshGridActivity.this, "Pull Down!", Toast.LENGTH_SHORT).show();
new GetDataTask().execute();
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefreshGridActivity.this, "Pull Up!", Toast.LENGTH_SHORT).show();
new GetDataTask().execute();
}
});
mListItems = new LinkedList<String>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
mGridView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems.addFirst("Added after refresh...");
mListItems.addAll(Arrays.asList(result));
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshGridView.onRefreshComplete();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_SET_MODE, 0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
private String[] mStrings = {"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg",
"https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
"https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg",
"https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg",
"https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg",
"https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg",
"https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
"https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg",
"https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg",
"https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg",
"https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg",
"https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s1024/Chihuly.jpg",};
}
Create a custom Adapter, where you refresh each cell. Create an object which contains a String and Image property, in GetDataTask create an ArrayList of all those new objects and refresh your adapter.
Heres a simple example of the adapter and object
public class CustomStepsAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<CustomObject> details;
private LayoutInflater mInflater;
public CustomStepsAdapter(Context aContext, ArrayList<CustomObject> data) {
this.details = data;
this.mContext = aContext;
mInflater = LayoutInflater.from(aContext);
}
public int getCount() {
return details.size();
}
public CustomObject getItem(int position) {
return details.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView() {
return mInflater.inflate(R.layout.custom_step_options_cell, null);
}
public View getView(int position, View convertView, ViewGroup parent) {
final CustomObject item = getItem(position);
CustomStepCell cell = null;
if (convertView == null) {
convertView = getView();
cell = new CustomStepCell();
cell.itemName = (TextView) convertView.findViewById(R.id.option_name);
cell.image = (ImageView) convertView.findViewById(R.id.green_checkmark);
convertView.setTag(cell);
}
else
{
cell = (CustomStepCell) convertView.getTag();
}
cell.itemName.setText(item.getItemName());
cell.image = item.getImage();
return convertView;
}
public boolean isShowPrices() {
return showPrices;
}
public void setShowPrices(boolean showPrices) {
this.showPrices = showPrices;
}
public static class CustomStepCell
{
public TextView itemName;
public ImageView image;
}
}
public class CustomObject
{
private String itemName;
private ImageView image;
public CustomObject()
{
this.itemName = "";
}
public void setImage(ImageView anImage)
{
this.image = anImage;
}
public void setItemName(String anItemName)
{
this.itemName = anItemName;
}
public ImageView getImage()
{
return this.image;
}
public String getItemName()
{
return this.itemName;
}
}

Endless pagination listview Android with database

I need to implement an endless pagination listview in my code, I've searched online and I saw a lot of examples, but none of them is using database, my app does the following:
it connects to an API and retrieves the data with json and show it in a listview, ok that works fine, but I want that listview to have an infinite scroll, like the facebook one.
I don't want anyone to write the code for me, I'm asking to someone guide me on wich is the better way to achieve that, I'll share some of my code, so you can understand:
try {
//Repositorio is my database
Repositorio mRepositorio = new Repositorio(getActivity());
List listaDeClientes = mRepositorio.getClientes();
System.out.println(listaDeClientes);
TextView total = (TextView) rootView.findViewById(R.id.totalClientes);
total.setText(getTotalClientes(mRepositorio.getTotalRegistros("clientes")));
final ArrayAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item, listaDeClientes);
ListView lv = (ListView) rootView.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClienteModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(Context context, int resource, List<ClienteModel> objects) {
super(context, resource, objects);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClienteModel mClienteModel = getItem(position);
view = inflater.inflate(resourceId, parent, false);
TextView tvId = (TextView) view.findViewById(R.id.clienteId);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
tvId.setText(String.valueOf(mClienteModel.getClientes_id()));
tvNome.setText(mClienteModel.getNome());
tvTipo.setText(mClienteModel.getTipo());
return view;
}
}
Model:
public class ClienteModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer clientes_id;
private Integer id_rm;
private Integer credencial_id;
private String nome;
private String tipo;
private String informacao_adicional;
private String _criado;
private String _modificado;
private String _status;
public Integer getClientes_id() {
return clientes_id;
}
public void setClientes_id(Integer clientes_id) {
this.clientes_id = clientes_id;
}
public Integer getId_rm() {
return id_rm;
}
public void setId_rm(Integer id_rm) {
this.id_rm = id_rm;
}
public Integer getCredencial_id() {
return credencial_id;
}
public void setCredencial_id(Integer credencial_id) {
this.credencial_id = credencial_id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getInformacao_adicional() {
return informacao_adicional;
}
public void setInformacao_adicional(String informacao_adicional) {
this.informacao_adicional = informacao_adicional;
}
public String get_criado() {
return _criado;
}
public void set_criado(String _criado) {
this._criado = _criado;
}
public String get_modificado() {
return _modificado;
}
public void set_modificado(String _modificado) {
this._modificado = _modificado;
}
public String get_status() {
return _status;
}
public void set_status(String _status) {
this._status = _status;
}
public static String[] getColunas() {
return Colunas;
}
public static void setColunas(String[] colunas) {
Colunas = colunas;
}
public static String[] Colunas = new String[]{
Coluna.CLIENTES_ID,
Coluna.ID_RM,
Coluna.CREDENCIAL_ID,
Coluna.NOME,
Coluna.TIPO,
Coluna.INFORMACAO_ADICIONAL,
Coluna._CRIADO,
Coluna._MODIFICADO,
Coluna._STATUS
};

Categories

Resources