How to change Tabs of a TabLayout from Navigation Drawer - java

Currently I'm changing Tabs from NavigationDrawer but it's not a right way and it takes too long to change tabs from NavigationDrawer becuase I'm replacing Main Fragment of Tabs each time and I don't want it. For more
NavigationDrawerAdapter.java
public class NavDrawerListAdapter extends BaseAdapter {
public Context context;
public MainActivity activity;
public MainTabFragment fragment;
int currentSelectedPostion;
LayoutInflater mInflater;
TextView tv_signup;
SharedPreferences share;
boolean cbc = false;
String fis = "", las = "";
int group_id = 0;
private String[] titles;
private int[] images;
private int[] selectedposition;
public NavDrawerListAdapter(Context context, int[] selectedposition, boolean cb, String fis, String las) {
this.context = context;
this.images = images;
this.cbc = cb;
this.fis = fis;
this.las = las;
share = context.getSharedPreferences("sharePref", 0);
group_id = share.getInt("group_id", 0);
this.selectedposition = selectedposition;
mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(com.cws.advisorymandi.R.layout.drawer_list_item, null);
}
LinearLayout ll_contact_us = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.contact_item);
RelativeLayout ll_login = (RelativeLayout) convertView.findViewById(com.cws.advisorymandi.R.id.signup_item);
LinearLayout ll_equity = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.equity_item);
LinearLayout ll_indices = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.indices_item);
if (cbc) {
tv_signup.setText("Welcome " + fis + " " + las);
tv_logout.setVisibility(View.VISIBLE);
tv_edit.setVisibility(View.VISIBLE);
}
ll_equity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.getInstance().displayView(3, 0, 0);
}
});
ll_indices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.getInstance().displayView(3, 0, 1);
}
});
});
return convertView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
public ListView mDrawerList;
NavDrawerListAdapter adapter;
public static MainActivity getInstance() {
return sMainActivity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.cws.advisorymandi.R.layout.activity_main)
mDrawerList = (ListView) findViewById(com.cws.advisorymandi.R.id.list_slidermenu);
adapter = new NavDrawerListAdapter(getApplicationContext(), selectedposition, cb, firstName, lastName);
mDrawerList.setAdapter(adapter);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
public int displayView(int position, int position2, int position3) {
// update the main content by replacing fragments
first_position = position;
second_position = position2;
third_position = position3;
fragment = null;
switch (position) {
case 0:
sharedPreferences = getSharedPreferences("sharePref", 0);
cb = sharedPreferences.getBoolean("ConfirmLogin", false);
if (cb) {
} else new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fragment = new LoginActivity();
changeFragments3();
}
}, 150);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 3:
// fragment = new MainTabFragment();
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {*/
fragment = new MainTabFragment();
changeFragments();
/*}
}, 150);
mDrawerLayout.closeDrawer(mDrawerList);*/
break;
}
return 0;
}
}
Note: I created each drawer item without using an array or arrayList so onItemClickListener isn't also working in it.

Related

How to save scroll state of a Recyclerview when an item is clicked?

I have an issue with Recyclerview item selection , which is set up in a fragment , the problem is each page which is created by ViewVager has its own instance of the Recyclerview so the output is that selecting Recyclerview items will reset the scroll state of the Recyclerview, so I'm looking for a solution to to save scroll state of a Recyclerview when an item is clicked.
Fragment onViewCreated
// setting RecyclerView
mEpisodesList = (CustomRecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
int scrollValue = mEpisodesList.getHorizontalScrollOffset();
mCallback.sendText(pos, scrollValue);
}
});
mEpisodesList.setAdapter(planetAdapter);
int scrollValue = getArguments().getInt("scrollValue");
new Handler().postDelayed(() -> mEpisodesList.scrollBy(scrollValue, 0), 100);
activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked {
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId, Integer.parseInt(mEpisodes.get(i).getSeason()), Integer.parseInt(mEpisodes.get(i).getEpisode()), i, mScrollValue));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i = 0; i < episodeslist.size(); i++) {
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
// return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
return fragments.get(index);
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
Recyclerview adapter
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
public interface OnItemClickListener {
void onItemClick(int item);
}
private final ArrayList<PlanetModel> episodeslist;
private final OnItemClickListener listener;
SharedPreferences getPref = getContext().getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
int pos = getPref.getInt("i", 0);
int isPlanetSelected = pos;
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition;
}
#NonNull
#Override
public PlanetAdapter.PlanetViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.planet_row, parent, false);
return new PlanetViewHolder(v);
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
}
//holder.image.setImageResource(R.drawable.planetimage);
//vh.text.setText(episodeslist.get(position).toString());
}
#Override
public int getItemCount() {
return episodeslist.size();
}
public class PlanetViewHolder extends RecyclerView.ViewHolder {
protected TextView text;
public PlanetViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text_id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG_TAG", "onClick: current item: " + highlightedPos);
final int previousItem = isPlanetSelected;
isPlanetSelected = getPosition();
SharedPreferences setPref = v.getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
setPref.edit().putInt("newPosition", getPosition()).apply();
listener.onItemClick(getPosition());
}
});
}
// public void bind(final PlanetModel item, final OnItemClickListener listener) {
// }
}
You can solve this by tracking the current scroll value of the RecyclerView, and whenever you hit an a ReyclerView item; add a new parameter to the listener callback with this tracked scroll value to update the new fragment that will be shown on the ViewPager.
Track the scroll value:
mEpisodesList.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
scrollValue += dx;
}
});
Pass it as interface callback:
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos, scrollValue);
}
});
And update that in the list of ViewPager fragments before scrolling to the new page:
#Override
public void sendText(int position, int scrollValue) {
mScrollValue = scrollValue;
TvShowEpisodeDetailsFragment frag = fragments.get(position);
Bundle arguments = frag.getArguments();
arguments.putInt("scrollValue", scrollValue);
mViewPager.setCurrentItem(position, false);
}
try this
// save
recyclerViewState = binding.mainList.layoutManager?.onSaveInstanceState()
// restore
recyclerViewState?.let {
binding.mainList.layoutManager?.onRestoreInstanceState(it)
}

How to display image on full screen on click android?

I am a newbie in android programming and I created a image gallery app to display images on SD card in grid view . It's working fine but I want to select any image and display it on full screen in another activity. I guess its easier when using a String array but I am using an array list to hold/store images. So I don't know how to display images on full screen using that. Can anyone help me out?
ImageGallery.java
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
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 = getApplicationContext().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);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
PhotosActivity.java
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
final ImageView imageView = (ImageView) findViewById(R.id.iv_image);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
FullImageActivity.java
public class FullImageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
// Selected image id
int position1 = i.getExtras().getInt("id");
ImageView imageView = (ImageView) findViewById(R.id.fullImage);
imageView.setImageResource();
}
}
Pass the image path to the second Activity, in your case it is "file://" + al_images.get(int_position).getAl_imagepath().get(position).
Then from the second activity, you can simply display it using the Glide
Glide.with(context).load(path)
.into(imageView);

How to refresh the fragment inside viewpager dynamically?

I have one ViewPager(mainViewPager) inside my MainActivity which renders from a fragment that contains another ViewPager(imageViewPager) and a TextView. Now The imageViewPager renders from another fragment that contains ImageView and a button. I've set onClick listener on this ImageView that turns in fullscreen view of the image with a button beneath.Now onClick of this buttton I want to return to my MainActivity with the condition to be on the same page from which I entered and with the same image which I viewed last in fullscreen.I am able to get the same page but the image always starts from 0.
Basically my hierarchy is like:
MainActivity
--mainViewPager-->TaskFragment
--imageViewPager-->ImageFragment(contains only ImageView
--TextView(set text returned from MainActivity)
My Code:
MainActivity.java
public class MainActivity extends FragmentActivity {
private ViewPager mViewPager;
private CustomPagerAdapter mPagerAdapter;
private int changedPosition;
private String[] vehicles = new String[]{"Audi Q7", "Honda Accord", "Hyundai i20", "Maruti Suzuki Swift", "Mahindra XUV 500",
"Swift Dzire", "Honda City", "Honda Civic", "Mercedez Benz", "Rolls Royce", "Ferrari"};
private String[][] vehicle_info = new String[][]{
{"http://www.hdwallpapers.in/walls/2010_abt_audi_q7_3_tdi_3-wide.jpg",
"http://www.hdwallpapers.in/walls/2010_mtm_audi_s5_cabrio_michelle_edition-wide.jpg",
"http://www.hdwallpapers.in/walls/2009_audi_tts_coupe_car-wide.jpg"},
{"http://automobiles.honda.com/images/2015/accord-sedan/exterior-gallery/2015-honda-accord-sedan-sport-exterior-side1.jpg",
"http://www.carprousa.com/wp-content/uploads/2015/01/HondaInterior-e1421978263126.jpg",
"http://www.carprousa.com/wp-content/uploads/2015/01/HondaInterior2-e1421978365916.jpg"},
...........
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager)findViewById(R.id.mainViewPager);
mPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), vehicles, vehicle_info);
mViewPager.setAdapter(mPagerAdapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
changedPosition = data.getIntExtra("CHANGED_POSITION", 0);
Log.i("POSITION 3:"," "+changedPosition);
TaskFragment fragment = new TaskFragment();
Bundle bundle = new Bundle();
bundle.putInt("IMAGE_POSITION", changedPosition);
fragment.setArguments(bundle);
}
}
}
activity_main.xml
<android.support.v4.view.ViewPager
android:id="#+id/mainViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
CustomPagerAdapter.java
public class CustomPagerAdapter extends FragmentStatePagerAdapter{
private String[] vehicles,selected_vehicle_info;
private String[][] vehicle_info;
public CustomPagerAdapter(FragmentManager fragmentManager,String[] vehicles,String[][] vehicle_info){
super(fragmentManager);
this.vehicles = vehicles;
this.vehicle_info = vehicle_info;
}
#Override
public Fragment getItem(int position) {
selected_vehicle_info = vehicle_info[position];
TaskFragment taskFragment = new TaskFragment();
Bundle bundle = new Bundle();
bundle.putString("ITEM",vehicles[position]);
bundle.putStringArray("ITEM_INFO",selected_vehicle_info);
taskFragment.setArguments(bundle);
return taskFragment;
}
#Override
public int getCount() {
return vehicles.length;
}
}
TaskFragment.java
public class TaskFragment extends Fragment {
private String vehicle;
private String[] vehicle_info;
private ViewPager imageViewPager;
private ImagePagerAdapter imagePagerAdapter;
private int changedImagePosition;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
vehicle = getArguments().getString("ITEM");
vehicle_info = getArguments().getStringArray("ITEM_INFO");
View view = inflater.inflate(R.layout.activity_task_fragment,container,false);
TextView messageTextView = (TextView) view.findViewById(R.id.textView);
messageTextView.setText(vehicle);
imageViewPager = (ViewPager)view.findViewById(R.id.imageViewPager);
imagePagerAdapter = new ImagePagerAdapter(getActivity(), vehicle_info);
imagePagerAdapter.notifyDataSetChanged();
imageViewPager.setAdapter(imagePagerAdapter);
imageViewPager.setCurrentItem(changedImagePosition);
return view;
}
private class ImagePagerAdapter extends PagerAdapter {
private Activity activity;
private String[] vehicle_info;
public ImagePagerAdapter(Activity activity,String[] vehicle_info){
this.activity = activity;
this.vehicle_info = vehicle_info;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = LayoutInflater.from(activity);
View view = inflater.inflate(R.layout.activity_image_fragment,container,false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Picasso.with(getContext()).load(vehicle_info[position]).into(imageView);
if(imageView.getParent()!=null)
((ViewGroup)imageView.getParent()).removeView(imageView);
((ViewPager) container).addView(imageView, 0);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ImageInFullScreen.class);
intent.putExtra("IMAGES_URL", vehicle_info);
intent.putExtra("IMAGE_POSITION", position);
activity.startActivityForResult(intent, 0);
}
});
return imageView;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return vehicle_info.length;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
ImageInFullScreen.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("CHANGED_POSITION",changedImgPosition);
setResult(0,intent);}});
//and the same adapter n all.
where ever you want to refresh the view put the following code
this.page_position = 0;
imagePagerAdapter.notifyDataSetChanged();
and in your ImagePagerAdapter override the following function -
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
POSITION_NONE means whenever notifyDataSetChanged is called, adapter will create fresh views rather than using the same views.
This should work in our case.
I have found an answer to my question, the problem was that somehow my setCurrentItem() wasn't working inside TaskFragment's onCreateView(), so I've moved it to the Run method of Runnable interface's postAtTime()nd then it worked perfectly.
Here's my edited code.
MainActivity.java`
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
claim_id = vehicleDetailsArrayList.get(changedPage).getClaimId();
//Retrieve value of position of last viewed image, before clicking the button
changedPosition = data.getIntExtra("CHANGED_POSITION", 0);
Log.i("POSITION 3:"," "+changedPosition);
if(changedPage > -1 && changedPage < vehicleDetailsArrayList.size()) {
addUpdateImagePositionInList(claim_id, changedPosition);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mViewPager.getAdapter() != null) {
mViewPager.getAdapter().notifyDataSetChanged();
}
}
}, 0);
}
}
public void addUpdateImagePositionInList(int claimId, int position){
for (int imageLength = 0; imageLength < imagePositionArrayList.size(); imageLength++)
{
if (claimId == (imagePositionArrayList.get(imageLength).getClaim_id()))
{
imagePositionArrayList.get(imageLength).setImagePosition(position);
return;
}
}
imagePositionArrayList.add(new ImagePosition(claimId, position));
}
public int getChangedImagePosition(int claimId){
for (int imageLength = 0; imageLength < imagePositionArrayList.size(); imageLength++)
{
if (claimId == (imagePositionArrayList.get(imageLength).getClaim_id()))
{
Log.i("POSITION123 "," ::"+ imagePositionArrayList.get(imageLength).getImagePosition() );
return imagePositionArrayList.get(imageLength).getImagePosition();
}
}
return 0;
}
`
TaskFragment.java`
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
id = getArguments().getInt("ID");
vehicle = getArguments().getString("ITEM");
vehicle_info = getArguments().getStringArray("ITEM_INFO");
changedImagePosition = ((MainActivity)getActivity()).getChangedImagePosition(id);
View view = inflater.inflate(R.layout.task_fragment,container,false);
TextView messageTextView = (TextView) view.findViewById(R.id.textView);
messageTextView.setText(vehicle);
imageViewPager = (ViewPager)view.findViewById(R.id.imageViewPager);
imagePagerAdapter = new ImagePagerAdapter(getActivity(), vehicle_info);
imageViewPager.setAdapter(imagePagerAdapter);
/*The below code doesn't work
if (imageViewPager.getCurrentItem() != changedImagePosition) {
Log.i("POSITION current", ":" + imageViewPager.getCurrentItem());
Log.i("POSITION changed", " :"+ changedImagePosition);
setCurrentItem = true;
imageViewPager.setCurrentItem(changedImagePosition, false);
Log.i("POSITION getCurrent", " :" + imageViewPager.getCurrentItem());
}
*/
new Handler().postAtTime(new Runnable() {
#Override
public void run() {
if (imageViewPager.getAdapter() != null) {
imageViewPager.getAdapter().notifyDataSetChanged();
imageViewPager.setCurrentItem(changedImagePosition);
}
}
},0);
return view;
}
`

how to use getItematposition() in recyclerview adapter as ListView

I have a RecyclerViewAdapter which fill my List with StoreName,image etc, I had model for listitems.ok, I'm migrating from a ListView to recylerview. i want to click on any item and get that items data(like Store name) and intent to another activity, now problem is that when i click on item it give wrong storename. but when i was using onItemclickListener that provide correct input. i will show u..
This my RecyclerViewAdapter.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<StoresItem> mDataset;
private static MyClickListener myClickListener;
Context context;
Bitmap xx;
public MyRecyclerViewAdapter(Context context, List<StoresItem> myDataset)
{
mDataset = myDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtStoreName,txtDeliveryTime;
ImageView storeImg;
RatingBar ratingBar;
public DataObjectHolder(View itemView)
{
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName);
txtDeliveryTime = (TextView) itemView.findViewById(R.id.txtDeliveryTime);
storeImg = (ImageView) itemView.findViewById(R.id.storeImg);
ratingBar=(RatingBar)itemView.findViewById(R.id.ratingBar);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener)
{
this.myClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
ImageView storeImg;
holder.txtStoreName.setText(mDataset.get(position).gettxtStoreName().toString());
holder.txtDeliveryTime.setText(mDataset.get(position).gettxtDeliveryTime().toString());
holder.ratingBar.setFocusable(false);
int loader = R.drawable.image;
String url = mDataset.get(position).getstoreImg().toString();
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(url,loader,holder.storeImg);
}
public void addItem(StoresItem dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener
{
public void onItemClick(int position, View v);
}
public Object getItem(int position)
{
return mDataset.get(position);
}
#Override
public long getItemId(int position)
{
return mDataset.indexOf(getItem(position));
}
#Override
public int getItemViewType(int position)
{
return super.getItemViewType(position);
}
}
This is my StoreModel.
public class StoresItem
{
private String txtStoreName, txtDeliveryTime, storeImg;
public StoresItem(String txtStoreName, String txtDeliveryTime,String storeImg)
{
this.txtStoreName = txtStoreName;
this.txtDeliveryTime = txtDeliveryTime;
this.storeImg = storeImg;
}
public String gettxtStoreName()
{
return txtStoreName;
}
public void settxtStoreName(String txtStoreName)
{
this.txtStoreName = txtStoreName;
}
public String gettxtDeliveryTime()
{
return txtDeliveryTime;
}
public void settxtDeliveryTime(String txtDeliveryTime)
{
this.txtDeliveryTime = txtDeliveryTime;
}
public String getstoreImg()
{
return storeImg;
}
public void setstoreImg(String storeImg)
{
this.storeImg = storeImg;
}
}
And this is my Fragment where i using onclickListner.
public class RecylerFragment extends Fragment
{
ListView storeListView;
List<StoresItem> storesItem;
StoresListAdaptor adapter;
String selectedStore;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static final String[] storeNameGrocery = new String[]
{
"Value Store", "Grocery Mart", "Wild Water-Sadar Bazar", "Store99","Coco-Buzz", "Wild Water - Sector 46"
};
public static final String[] storeNameFresh = new String[]
{
"Mother's Love", "The Flower Shop", "Flower N Emotions"
};
public static final String[] storeNameElectronics = new String[]
{
"Molife-Sheetla Mata Road", "Apple Store- Shona Road", "Vandana Communication", "Samsung Store","JMD Mobile - Sector 14", "Sterling - Gurgaon"
};
public static final String[] storeNameVegetable = new String[]
{
"Fortune Store", "Best Food - Mega Mall", "Sadar Bazar", "MTR Store","Coco-Buzz"
};
public static final String[] deliveryTime = new String[]
{
"20min", "10min", "9min", "15min","30min", "1hr","20min","20min", "10min", "9min", "15min","30min", "1hr","20min" };
private static final String KEY_POSITION="position";
public static final String[] iconsUrl = new String[]
{
"http://icons.iconarchive.com/icons/femfoyou/angry-birds/96/angry-bird-icon.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/96/grimace-icon.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
};
public RecylerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_recycler_view, container, false);
Bundle bundle = this.getArguments();
String myString = bundle.getString("page_position");
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
storesItem = new ArrayList<StoresItem>();
if(myString.equals("999")) {
for (int i = 0; i < storeNameGrocery.length; i++) {
StoresItem item = new StoresItem(storeNameGrocery[i], "Delivery Time " + deliveryTime[i],iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("888")) {
for (int i = 0; i < storeNameFresh.length; i++) {
StoresItem item = new StoresItem(storeNameFresh[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("777")) {
for (int i = 0; i < storeNameElectronics.length; i++) {
StoresItem item = new StoresItem(storeNameElectronics[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("666")) {
for (int i = 0; i < storeNameVegetable.length; i++) {
StoresItem item = new StoresItem(storeNameVegetable[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
mAdapter = new MyRecyclerViewAdapter(getActivity(), storesItem);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
**#Override
public void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v)
{
System.out.println(" Clicked on Item " + position);
StoresItem storesItems = (StoresItem) ((MyRecyclerViewAdapter) mAdapter).getItem(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
}**
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
okk...there is something wrong with recyclerviews-onItemclicklister because listviews - onItemCLicklistner()
provide Adapterview and i can simply get Item by using parent.getItematposition(position) like this.
storeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StoresItem storesItems = (StoresItem) parent.getItemAtPosition(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
Can Any one tell me whats the reason why getWrong StoreName.??
You are using myClickListener.onItemClick(getLayoutPosition(), v); you have to use myClickListener.onItemClick(getAdapterPosition(), v);

invalidateViews() and notifyDataSetChanged() doesnt work for me

i using ListView in fragment. I have one asynctask to download json data from remote server. I try refresh programmatically my displayed adapter/listview in onPostExecute function but it doesn't work for me.
My main activity with three fragments, three listview, three adapter and one async task.
public class ContactsActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
private static List<Item> BackList = new ArrayList<Item>();
private static List<Item> BackList2 = new ArrayList<Item>();
private static List<Item> BackList3 = new ArrayList<Item>();
private static ListView ListView;
private static Context activity;
public static String HASH;
private static final String[] timestamp = {"0"};
private static WeatherAdapter adapter;
private static int fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
Intent myIntent= getIntent();
HASH = myIntent.getStringExtra("HASH");
Log.d("Intent - contactActivity", HASH);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
(new PrefetchData()).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contacts, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
fragment = position;
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
int index = getArguments().getInt(ARG_SECTION_NUMBER);
fragment = index;
activity = getActivity();
ListView listview1 = (ListView) rootView.findViewById(R.id.listView);
switch(fragment){
case 1:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row, BackList);
listview1.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
Intent rozmowa = new Intent(getActivity(), Incotalk.class);
rozmowa.putExtra("HASH", HASH);
startActivity(rozmowa);
}
});
break;
case 2:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row2, BackList2);
break;
case 3:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row3, BackList3);
break;
}
listview1.setAdapter(adapter);
ListView = listview1;
return rootView;
}
}
/**
* Async Task to make http call
*/
private class PrefetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
#Override
protected Void doInBackground(Void... arg0) {
final String id = HASH;
final String url = "http://freshfrog.pl/projects/talk.php?user="+id+"&t=" + timestamp[0];
Log.d("BBB","start");
try {
String page = new Communicator().executeHttpGet(url);
JSONObject jsonObject = new JSONObject(page);
timestamp[0] = jsonObject.getString("t");
HASH = jsonObject.getJSONObject("s").getString("hash");
JSONArray oczekujacy = jsonObject.getJSONArray("m");
// wiadomosci
BackList.clear(); // czyści przed odświerzeniem
BackList2.clear();
BackList3.clear();
for (int i=oczekujacy.length()-1; i>0; i--) {
JSONObject actor = oczekujacy.getJSONObject(i);
String message = actor.getString("m");
String hash = actor.getString("n");
String t = actor.getString("t");
int l = BackList.size();
Boolean jest = false;
for(int j=0; j<l; j++){
Item item = BackList.get(j);
if(!item.isSection()){
ContactItem contactItem= (ContactItem) item;
if( (contactItem.hash).equals(hash) ){
jest = true;
break;
}
}
//Log.d("bbb", BackList.get(j).hash);
}
if(!jest && !hash.equals(id)) BackList.add(
new ContactItem(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
message,
hash));
}
// znajomi
BackList2.add(new SectionItem("Otrzymane zaproszenia"));
oczekujacy = jsonObject.getJSONObject("f").getJSONObject("p").getJSONArray("sending");
for (int i=0; i<oczekujacy.length(); i++) {
JSONObject actor = oczekujacy.getJSONObject(i);
String name = actor.getString("name");
String hash = actor.getString("hash");
String avatar = actor.getString("avatar");
BackList2.add(new ContactItem(getBitmapFromURL(avatar) , name, hash) );
}
// szukaj
BackList3.add(new SectionItem("Znajomi"));
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
BackList3.add(new ContactItem(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
name,
phoneNumber) );
}
} catch (Exception e) {
Log.d("BBB", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
}
}
My custom adapter
public class WeatherAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
List<Item> data = null;
private LayoutInflater vi;
public WeatherAdapter(Context context, int layoutResourceId, List<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
SectionHolder holder2 = null;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
Item i = data.get(position);
if(row == null){
if(!i.isSection()){
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
}else{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
}
}
else
{
if(!i.isSection()){
//holder = (WeatherHolder) row.getTag();
}else{
//holder2 = (SectionHolder) row.getTag();
}
}
return row;
}
public void update(List<Item> newlist) {
Log.d("bbb","aktualizacja listview");
data.clear();
data.addAll(newlist);
this.notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() // Create this function in your adapter class
{
//notifySetDataChanged()
super.notifyDataSetChanged();
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
static class SectionHolder
{
TextView txtTitle;
}
}
the part of the "if(row == null){" should only contain initializations of the views and the viewHolders.
it shouldn't contain any setting of data to the views.
after this part ( after the "else {...}" ) , you should update the views with the new data .
here's my fix to your code (looks ugly, but should work) :
...
int type=getViewType();
switch(type)
{
case 0:
if(row == null)
{
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
holder = (WeatherHolder) row.getTag();
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
break;
case 1:
if(row == null)
{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
}
else
holder2 = (SectionHolder) row.getTag();
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
break;
}
return row;
...
... int getViewType(...) {... return i.isSection()? 1:0;}
... int getViewTypeCount(){return 2;}
btw, you should really watch the lecture "the world of listView" . they have great tips that will make your code much better.
for example, you can use getViewTypeCount , getViewType, getItem, as shown on the API .
to view your code i see that you have started your async execution again on postExcecute
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
also clearing data inside your doBackground
To get changes on your data you should not clear your data just get updates records and notify your adapeter
try to change the method data.addAll(newlist) by using addall(newlist, data);
inside addall method add one by one the list of element. this way it should work.
i had the same problem and i correct it the way i explained.

Categories

Resources