viewpager first item doesn't show content - android

I know there is lots of threads talk about first item problems in viewpager, I searched many time about my issue but no way I just lose time.
would you help me, please ?
I use FragmentStatePagerAdapter , fragment and loader manager that add radio buttons dynamically. the first iitem in view pager doesn't show radio buttons until I swipe to third item and back again to the first one.
screen
Image
Fragment:
package mohalim.android.egybankstest.Fragments;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import mohalim.android.egybankstest.Database.AppContract;
import mohalim.android.egybankstest.Models.Choice;
import mohalim.android.egybankstest.Models.Question;
import mohalim.android.egybankstest.R;
import mohalim.android.egybankstest.ResultActivity;
public class QuizFragement extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final String UPDATE = "update";
private static final int GET_CHOICES_LOADER_ID = 100;
private static final int UPDATE_CHOSEN_ANSWER_LOADER_ID = 101;
private static final String SELECTED_QUIZ = "selected_quiz";
ArrayList<Question> questions;
ArrayList<Choice> choices;
int questionPosition;
String selectedQuiz;
RadioGroup radioGroup;
TextView questionText;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
choices = new ArrayList<>();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.quiz_fragment, container, false);
questionText = view.findViewById(R.id.m);
radioGroup = view.findViewById(R.id.choices_radio);
radioGroup.removeAllViews();
questionText.setText(questions.get(questionPosition).getQuestion_text());
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(GET_CHOICES_LOADER_ID,null,this)
.forceLoad();
}
/**
* end the session
*/
FloatingActionButton fab = view.findViewById(R.id.end_session);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ResultActivity.class);
intent.putExtra(SELECTED_QUIZ,selectedQuiz);
startActivity(intent);
getActivity().finish();
}
});
return view;
}
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable final Bundle args) {
if (id==GET_CHOICES_LOADER_ID){
Uri choicesUri = AppContract.ChoiceEntry.CONTENT_URI
.buildUpon()
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId()))
.build();
String questionId = String.valueOf(questions.get(questionPosition).getQuestionId());
String questionIDSelection = AppContract.ChoiceEntry.COLUMN_QUESTION_ID + "=?";
String[] questionIDSelectionArgs = new String[]{questionId};
return new CursorLoader(
getActivity(),
choicesUri,
null,
questionIDSelection,
questionIDSelectionArgs,
null
);
}else if(id == UPDATE_CHOSEN_ANSWER_LOADER_ID){
return new AsyncTaskLoader<Cursor>(getActivity()) {
#Nullable
#Override
public Cursor loadInBackground() {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Uri updateChosenUri = AppContract.QuestionsEntry.CONTENT_URI
.buildUpon()
.appendPath(UPDATE)
.appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build();
ContentValues contentValues = new ContentValues();
contentValues.put(AppContract.QuestionsEntry.COLUMN_ANSWER_CHOSEN,checkedId);
if (group.getChildAt(checkedId-1).getTag().toString().equals("1")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 1);
}else if (group.getChildAt(checkedId-1).getTag().toString().equals("0")){
contentValues.put(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT, 0);
}
getActivity().getContentResolver().update(updateChosenUri,contentValues,null,null);
Cursor cursor = getActivity().getContentResolver().query(
AppContract.QuestionsEntry.CONTENT_URI.buildUpon().appendPath(String.valueOf(questions.get(questionPosition).getQuestionId())).build(),
null,null,null,null
);
if (cursor.getCount() == 1){
cursor.moveToFirst();
Log.v("string", cursor.getInt(cursor.getColumnIndex(AppContract.QuestionsEntry.COLUMN_IS_CHOSEN_CORRECT))+"");
Log.v("string 2", group.getChildAt(radioGroup.getCheckedRadioButtonId()-1).getTag().toString());
}
}
});
return null;
}
};
}
return null;
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor choicesCursor) {
if (questionPosition == 0){
Toast.makeText(getActivity(), ""+selectedQuiz, Toast.LENGTH_SHORT).show();
}
if (loader.getId() == GET_CHOICES_LOADER_ID){
if (choicesCursor.getCount() >0){
while (choicesCursor.moveToNext()){
String text = choicesCursor.getString(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_CHOICE_TEXT));
int is_correct = choicesCursor.getInt(choicesCursor.getColumnIndex(AppContract.ChoiceEntry.COLUMN_IS_TRUE));
Choice choice = new Choice();
choice.setChoiceText(text);
choice.setCorrect(is_correct);
choices.add(choice);
}
for (int i=0; i<choices.size();i++){
LayoutInflater inflater = LayoutInflater.from(getContext());
final View radioButton = inflater.inflate(R.layout.radio_button,radioGroup,false);
((RadioButton) radioButton).setText(choices.get(i).getChoiceText());
radioButton.setTag(choices.get(i).isCorrect());
radioGroup.addView(radioButton);
}
for (int i = 0; i<radioGroup.getChildCount();i++){
radioGroup.getChildAt(i).setId(i+1);
}
}
if (questionPosition == 0){
getActivity().getSupportLoaderManager()
.initLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}else {
getActivity().getSupportLoaderManager()
.restartLoader(
UPDATE_CHOSEN_ANSWER_LOADER_ID,
null,
this).forceLoad();
}
}
}
#Override
public void onLoaderReset(#NonNull Loader<Cursor> loader) {
}
public void setQuestions(ArrayList<Question> questions) {
this.questions = questions;
}
public void setQuestionPosition(int questionPosition) {
this.questionPosition = questionPosition;
}
public ArrayList<Question> getQuestions() {
return questions;
}
public int getQuestionPosition() {
return questionPosition;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
}
ViewPagerAdapter
package mohalim.android.egybankstest.Adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import mohalim.android.egybankstest.Fragments.QuizFragement;
import mohalim.android.egybankstest.Models.Question;
public class MyQuizPager extends FragmentStatePagerAdapter {
ArrayList<Question> questions;
String selectedQuiz;
public MyQuizPager(FragmentManager fm, ArrayList<Question> questions, String selectedQuiz) {
super(fm);
this.questions = questions;
this.selectedQuiz = selectedQuiz;
}
#Override
public Fragment getItem(int position) {
QuizFragement fragment = new QuizFragement();
fragment.setQuestions(questions);
fragment.setQuestionPosition(position);
fragment.setSelectedQuiz(selectedQuiz);
return fragment;
}
#Override
public int getCount() {
return questions.size();
}
#Override
public int getItemPosition(Object object) {
QuizFragement fragment = (QuizFragement) object;
int position = fragment.getQuestionPosition();
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
}
All code is here

Finnaly I found the solution:
Quate:
By default it is viewpager.setOffscreenPageLimit(1) , meaning View
pager will by default load atleast 1 on the right and one on the left
tab of current tab.
https://stackoverflow.com/a/47054077/5862361
when i start quizActivity viewpager load the first item and the second too so the loadermanager restart before complete its work.
I solved it by adding another loadermanger
one for the first item and the second for the second one:
if (questionPosition == 0){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}else{
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID_FIRST,
null,
this
).forceLoad();
}
}else if (questionPosition == 1){
if (getActivity().getSupportLoaderManager() == null){
getActivity().getSupportLoaderManager().initLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}
}else {
getActivity().getSupportLoaderManager().restartLoader(
GET_CHOICES_LOADER_ID,
null,
this
).forceLoad();
}

Related

This error is coming while doing intent Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'?

I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}

How to customize Adapter for SwipeCard?

I am making a flash card app with SwipeCard
This is my FlashCardActivity:
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.adapter.CardListAdapter;
import org.koreanlab.fabloading.basickit.BasicCompatActivity;
import org.koreanlab.fabloading.basickit.remote.RemoteService;
import org.koreanlab.fabloading.basickit.remote.ServiceGenerator;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FlashCardActivity extends BasicCompatActivity {
private String TAG = getClass().getSimpleName();
private ArrayList<CardItem> cardList;
private ArrayAdapter<String> cardAdapter;
private CardListAdapter cardListAdapter;
private int i;
CardItem newCard;
#BindView(R.id.frame)
SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashcard);
ButterKnife.bind(this);
cardList = new ArrayList<>();
Log.d(TAG, "cardList created");
// get Two Words;
cardList.add(getCardItem());
cardList.add(getCardItem());
Log.d(TAG, "added Card");
cardListAdapter = new CardListAdapter(this, R.layout.card_item, cardList);
Log.d(TAG, "adapter created: " + (cardListAdapter == null ? "cardAdapter is NULL" : "cardAdapter is not NULL"));
flingContainer.setAdapter(cardListAdapter);
Log.d(TAG, "adapter set: " + (flingContainer == null ? "flingContainer is NULL" : "flingContainer is not NULL"));
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
cardList.remove(0);
cardListAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(FlashCardActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(FlashCardActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
Log.d(TAG, "onAdapterAboutToEmpty: "+itemsInAdapter);
cardList.add(getCardItem());
cardListAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(FlashCardActivity.this, "Clicked!");
}
});
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
public CardItem getCardItem() {
// No problem here.
return newCard;
}
}
Notice that, getCardItem() just get one card. First of all, it calls two cards and the cardList has two cards when activity has created. And after that I'd like to get just one card after swipe. getCardItem() has no problem. I can see that I receives the data from my Server.
This is my custom CardListAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import java.util.List;
public class CardListAdapter extends ArrayAdapter {
private final String TAG = this.getClass().getSimpleName();
private Context context;
private int cardResId;
private int frontResId;
private int backResId;
private List<CardItem> cardList;
private LayoutInflater mInflater;
//this, R.layout.card_item, R.id.card_front, R.id.card_back, cardList
public CardListAdapter(Context context, int cardResId, ArrayList<CardItem> cardList) {
super(context, cardResId);
this.context = context;
this.cardResId = cardResId;
this.cardList = cardList;
mInflater = LayoutInflater.from(context);
}
public void setItem(CardItem newItem) {
Log.d(TAG, "setItem");
for (int i = 0; i < cardList.size(); i++) {
CardItem item = cardList.get(i);
if (item.seq == newItem.seq) {
cardList.set(i, newItem);
break;
}
}
}
#Override
public int getCount() {
Log.d(TAG, "getVIew");
return 0;
}
public int getPosition(CardItem item) {
Log.d(TAG, "getPosition = "+item);
return cardList.indexOf(item);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(cardResId, parent,false);
holder = new ViewHolder();
Log.d(TAG, "getView");
holder.frontTV = convertView.findViewById(R.id.card_front);
holder.backTV = convertView.findViewById(R.id.card_back);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.frontTV.setText((String)getItem(position));
holder.backTV.setText((String)getItem(position));
return convertView;
}
static class ViewHolder
{
TextView frontTV, backTV;
}
}
I checked many blogs and other Q&A, but I haven't figured it out how to solve this problem. That activity keeps going back after receiving 'one word' data from the Server and It doesn't show any error messages.

Sorting a multi view type RecyclerView according to month and year

I am using a multiview type RecyclerView and the header should display the name of month and year and further in items I am loading images from gallery using Glide. First of all, I want that the name of month and year should be displayed on every header and then the images should belong to that particular month and year only.
I want my Multiview to look like this
Screenshot
Here is my code
GalleryAdapter.java
package com.jumptotv.adapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.CursorLoader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jumptotv.GlideApp;
import com.jumptotv.R;
import com.jumptotv.model.HeaderModel;
import com.jumptotv.model.Movie;
import com.jumptotv.view.activity.FullScreenActivity;
import com.jumptotv.view.activity.MainActivity;
import com.jumptotv.view.activity.VideoActivity;
import com.jumptotv.view.activity.VideoPlayActivity;
import com.jumptotv.view.fragment.GalleryFragment;
import java.io.File;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class GalleryAdapter2 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private List<HeaderModel> moviesList;
private ArrayList<String> imageData;
final int HEADER = 0;
final int ITEMS = 1;
int n = 0;
String sort[];
String month[] = {"DAY", "TODAY", "SEP 1", "SEP 2", "SEP 3", "OCT 2018", "NOV 2018", "DEC 2018", "JAN 2017", "FEB 2017"};
public GalleryAdapter2(ArrayList<String> imageData, Context context, List<HeaderModel> moviesList) {
this.imageData = imageData;
this.context = context;
this.moviesList = moviesList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == HEADER) {
view = LayoutInflater.from(context).inflate(R.layout.header_type_layout, parent, false);
return new Header2(view);
} else if (viewType == ITEMS) {
view = LayoutInflater.from(context).inflate(R.layout.grid_type_layout, parent, false);
return new MyViewHolde(view);
}
throw new RuntimeException("No match found");
}
#Override
public int getItemViewType(int position) {
int viewType = ITEMS; //Default is 1
if (position % 16 == 0) {
viewType = HEADER;
}
//return position;
//if zero, it will be a header view
return viewType;
}
private String getItem(int position)
{
return imageData.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final int itemType = getItemViewType(position);
switch (holder.getItemViewType()) {
case 1:
final String data = imageData.get(position);
String data2 = GalleryAdapter2.getMimeType(data);
if (data != null) {
if (data2.equals("jpg") || (data2.equals("png")) || (data2.equals("tif")) || (data2.equals("gif"))) {
((MyViewHolde) holder).play.setVisibility(View.GONE);
GlideApp.with(context)
.load(data)
.placeholder(R.drawable.gallery_39)
.into(((MyViewHolde) holder).singleImageView);
((MyViewHolde) holder).singleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullScreenActivity.class);
intent.putExtra(FullScreenActivity.IMAGE_POSITION, position);
context.startActivity(intent);
}
});
} else if (data2.equals("mkv") || (data2.equals("flv")) || (data2.equals("mov")) || (data2.equals("mp4")) || (data2.equals("3gp")) || (data2.equals("wmv")) || (data2.equals("mpg") || (data2.equals("avc")) || (data2.equals("UNKNOWN")))) {
Glide.with(context).load(data).into(((MyViewHolde) holder).singleImageView);
((MyViewHolde) holder).play.setVisibility(View.VISIBLE);
((MyViewHolde) holder).play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, VideoPlayActivity.class);
intent.putExtra("video_url", data);
intent.putExtra(VideoPlayActivity.VIDEO_POSITION, position);
context.startActivity(intent);
}
});
}
} else {
}
break;
case 0:
n++;
if(n==10)
{
n=6;
n++;
}
((Header2) holder).textView.setText(month[n]);
break;
//Header2 header2=new Header2(View itemView);
// bindHeaderItem(,position);
//((Header2) holder).textView.setText(month[n]);
/*if(position==0)
{
n=n+1;
}
*/
}
}
#Override
public int getItemCount() {
return imageData.size();
}
public boolean isHeader(int position) {
return position == 0;
}
public static String getMimeType(String url) {
Uri uri = Uri.parse(url);
String extension = MimeTypeMap.getFileExtensionFromUrl(uri.getPath());
return extension;
}
public class MyViewHolde extends RecyclerView.ViewHolder {
ImageView singleImageView, play;
public MyViewHolde(View itemView) {
super(itemView);
singleImageView = (ImageView) itemView.findViewById(R.id.gallery);
play = (ImageView) itemView.findViewById(R.id.play_video2);
}
}
public class Header2 extends RecyclerView.ViewHolder {
TextView textView;
public Header2(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.headerTitle);
// textView.setText(month[n]);
}
}
private void bindHeaderItem(Header2 holder, int position) {
TextView title = (TextView) holder.textView.findViewById(R.id.headerTitle);
title.setText(moviesList.get(position).getTitle());
}
}
GalleryFragment
package com.jumptotv.view.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.CursorLoader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jumptotv.R;
import com.jumptotv.Utility;
import com.jumptotv.adapter.GalleryAdapter;
import com.jumptotv.adapter.GalleryAdapter2;
import com.jumptotv.model.HeaderModel;
import com.jumptotv.model.Model_Video;
import com.jumptotv.model.Movie;
import com.jumptotv.view.activity.FullScreenActivity;
import com.jumptotv.view.activity.VideoActivity;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class GalleryFragment extends Fragment {
public GalleryFragment() {
}
private Context context;
private List<HeaderModel> movieList = new ArrayList<>();
private RecyclerView recyclerView;
ArrayList<String> imageData;
GalleryAdapter2 adapter;
ImageView gallery,play,back_button;
String title;
Button play_video;
Uri uri;
TextView header;
Cursor cursor;
int column_index_data=0, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
String month[] = {"TODAY", "SEP 1", "SEP 2","SEP 3","OCT 2018,NOV 2018,DEC 2018,JAN 2017,FEB 2017"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
context = getActivity();
HeaderModel headerModel =new HeaderModel("TODAY");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow1");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow2");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow3");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorro4");
movieList.add(headerModel);
headerModel =new HeaderModel("Tomorrow5");
movieList.add(headerModel);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewList);
recyclerView.setHasFixedSize(true);
back_button=(ImageButton)view.findViewById(R.id.back_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment someFragment = new FileFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_frame, someFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
header=(TextView)view.findViewById(R.id.see_all);
final View view2 = inflater.inflate(R.layout.grid_type_layout, container, false);
Bundle bundle = this.getArguments();
if(bundle != null) {
title = bundle.get("key").toString();
}
gallery=(ImageView)view2.findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
});
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (position %16 == 0) ? 3 : 1;
}
});
recyclerView.setLayoutManager(layoutManager);
MyTask myTask = new MyTask();
myTask.execute();
return view;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
boolean flag = Utility.checkReadStoragePermission(getActivity(),GalleryFragment.this);
if (flag) {
imageData= getAllShownImagesPath(getActivity());
Log.e("imageData: ", String.valueOf(imageData.size()));
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new GalleryAdapter2(imageData,getActivity(),movieList);
recyclerView.setAdapter(adapter);
}
}
private ArrayList<String> getAllShownImagesPath(Activity activity) {
if(title.equals("All Photos"))
{
// header.setText("All Photos");
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getActivity().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
}
else if(title.equals("All Videos"))
{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
header.setText(title);
// Stuff that updates the UI
}
});
//header.setText("All Videos");
int column_id,thum;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Images.Media.DATE_ADDED;
cursor = getActivity().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
listOfAllImages.add(absolutePathOfImage);
}
}
else if(title.equals("All Files")){
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
header.setText(title);
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE
}; // used for query ContentResolver for mediafiles
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO; // used to select images and videos from contentResolver
Uri queryUri = MediaStore.Files.getContentUri("external");
CursorLoader cursorLoader = new CursorLoader(getActivity(),queryUri, projection, selection, null, MediaStore.Files.FileColumns.DATE_ADDED + " DESC");
cursor = cursorLoader.loadInBackground();
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
}
});
}
return listOfAllImages;
}
}

Need Help Sorting ListView with Custom Adapter

I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});

SharedPreferences resetting when app closes

I have a ListView fragment that has the option to save specific table values. You can click a button to toggle the table to only show saved values. When the toggle is active instead of saving you have the option to delete values. I have noticed however that while the delete will delete the value permanently so long as the app is open, If i close the app and reopen it, the value will reappear. Also if I delete the app and reinstall this same value reappears. I'm not sure how this value is getting added in and why it refuses to go. Debugging shows me saving the correct values in SharedPreferences but that does not stay.
EDIT: After some more testing it appears that the first item saved in the specific SharedPreferences remains permanently saved. It cannot be removed and all other values saved will not remain there.
Fragment:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.os.StrictMode;
import com.tble.brgo.HTMLPull;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Websites#newInstance} factory method to
* create an instance of this fragment.
*/
public class Websites extends Fragment implements SearchView.OnQueryTextListener, displayInterface {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private SearchView mSearchView;
private ListView mListView;
public Boolean toggle = false;
public ArrayList<InfoArticle> mData = new ArrayList<InfoArticle>();
public StandardCellAdapter mAdapter;
public ArrayList<InfoArticle> fDataSet = new ArrayList<InfoArticle>();
public Websites webTable;
public Websites() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Websites.
*/
// TODO: Rename and change types and number of parameters
public static Websites newInstance() {
Websites fragment = new Websites();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toggle = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_websites, container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<InfoArticle> data = new ArrayList<InfoArticle>();
webTable = this;
try {
data = getData();
} catch (IOException e) {
e.printStackTrace();
}
mListView = (ListView) view.findViewById(R.id.WebsiteTable);
final StandardCellAdapter adapter = new StandardCellAdapter(getActivity(), data, 1,this);
fDataSet = data;
mData = data;
mListView.setAdapter(adapter);
mAdapter = adapter;
mSearchView = (SearchView) view.findViewById(R.id.searchView);
mListView.setTextFilterEnabled(true);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.dataToggle);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleView();
}
});
setupSearchView();
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.webRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
mData = getData();
mAdapter = new StandardCellAdapter(getContext(), mData, 1,webTable);
mListView.setAdapter(mAdapter);
} catch (IOException e) {
e.printStackTrace();
}
swipeLayout.setRefreshing(false);
}
});
return view;
}
private void setupSearchView() {
mSearchView.setOnQueryTextListener(this);
mSearchView.setIconifiedByDefault(true);
}
private ArrayList<InfoArticle> getData() throws IOException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
int school = sharedPref.getInt("School", 14273);
HTMLPull Connection = new HTMLPull();
Connection.getStaff(school);
Connection.Results.remove(0);
return Connection.Results;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public ArrayList<InfoArticle> toData(ArrayList<String> t, ArrayList<String> d) {
ArrayList<InfoArticle> temp = new ArrayList<InfoArticle>();
if (t.size() == 0) {
temp.add(new InfoArticle("Slide to Save Teachers", "google.com"));
} else {
for (int i = 0; i < t.size(); i++) {
temp.add(new InfoArticle(t.get(i), d.get(i)));
}
}
return temp;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private void toggleView(){
if (!toggle) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
HashSet<String> defv = new HashSet<String>();
ArrayList<String> teachers = new ArrayList<String>(sharedPref.getStringSet("teachPref", defv));
ArrayList<String> links = new ArrayList<String>(sharedPref.getStringSet("linkPref", defv));
mAdapter = new StandardCellAdapter(getContext(), toData(teachers, links),2,this);
mListView.setAdapter(mAdapter);
toggle = true;
} else {
mAdapter = new StandardCellAdapter(getContext(), mData, 1,this);
mListView.setAdapter(mAdapter);
toggle = false;
}
}
/**public void displayWebpage(int position){
if (toggle == true) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(mAdapter.getItem(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
} else {
if (!mSearchView.isIconified()) {
for (InfoArticle a : fDataSet) {
if (a.title.equals(((InfoArticle) mListView.getAdapter().getItem(position)).title)) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(a.description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
} else {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(fDataSet.get(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
}*/
public void displayWebpage(String Link){
WebsiteDisplay fullView = WebsiteDisplay.newInstance(Link);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
CellAdapter:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.nfc.Tag;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.graphics.Typeface;
import android.widget.Filterable;
import android.widget.Filter;
import org.w3c.dom.Text;
/**
* Created by Praveen on 8/21/16.
*/
public class StandardCellAdapter extends ArrayAdapter<InfoArticle> implements Filterable {
public ArrayList<InfoArticle> orig;
public ArrayList<InfoArticle> Teachers;
public SwipeRevealLayout swipeV;
public TextView deleteButton;
public TextView saveButton;
public int tableType;
public displayInterface activity;
public Context ct;
public StandardCellAdapter(Context context, ArrayList<InfoArticle> titles, int tableType, displayInterface inter) {
super(context, 0, titles);
this.Teachers = titles;
this.tableType = tableType;
saveButton = new TextView(context);
deleteButton = new TextView(context);
activity = inter;
ct = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String title = getItem(position).title;
String desc = getItem(position).description;
Holder TagHolder = null;
TextView Ctitle;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
if (tableType == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.nclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
else if(tableType == 1){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.scSwipe);
saveButton = (TextView)convertView.findViewById(R.id.saveButton);
TagHolder.Save = saveButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.tcSwipe);
deleteButton = (TextView) convertView.findViewById(R.id.deleteButton);
TagHolder.Delete = deleteButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
}
else {
TagHolder = (Holder) convertView.getTag();
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
if(tableType == 1) {
TagHolder.Save.setTag(position);
TagHolder.Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTeacher((int)v.getTag());
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
else if(tableType == 2) {
TagHolder.Delete.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteTeacher((int)v.getTag());
if(Teachers.size() == 0)
Teachers.add(new InfoArticle("Slide to Save Teachers", "google.com"));
notifyDataSetChanged();
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
Typeface customFont = Typeface.SERIF;
Ctitle.setTypeface(customFont);
Ctitle.setText(title);
return convertView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<InfoArticle> results = new ArrayList<InfoArticle>();
if (orig == null)
orig = Teachers;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final InfoArticle g : orig) {
if (g.title.toLowerCase()
.contains(constraint.toString().toLowerCase())) {
results.add(g);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Teachers = (ArrayList<InfoArticle>)results.values;
notifyDataSetChanged();
}
};
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public ArrayList<InfoArticle> toIA(ArrayList<String> data){
ArrayList<InfoArticle> converted = new ArrayList<InfoArticle>();
for(String a: data)
{
converted.add(new InfoArticle(a,""));
}
return converted;
}
#Override
public int getCount() {
return Teachers.size();
}
#Override
public InfoArticle getItem(int position) {
return Teachers.get(position);
}
public void saveTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
teach.add(Teachers.get(position).title);
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
link.add(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
new AlertDialog.Builder(getContext())
.setTitle("Teacher Saved")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(true);
}
private void deleteTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
teach.remove(Teachers.get(position).title);
link.remove(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
HashSet<String> defv = new HashSet<String>();
Teachers.remove(position);
new AlertDialog.Builder(getContext())
.setTitle("Teacher Deleted")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(false);
}
class Holder{
TextView Delete;
TextView Save;
TextView Cell;
}
}

Categories

Resources