I have a relative layout which contains a viewpager to enable to me swipe images fetched from my web service.The fetched images are then stored in a ArrayList which contains a HashMap. I've logged the fetching part of from web service and the log indicates that I am indeed fetching different images. However, whenever I'm swiping from image to image, the viewpager displays the same image which is always the last image saved. I've logged the ArrayList of images in the Pager Adapter and it seems that I am getting the correct arraylist size but I'm getting the same bitmap in all sizes.
This is my PagerAdapter class:
public class ImageAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public ImageAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video, null);
RelativeLayout rlAttach = (RelativeLayout) view.findViewById(R.id.rl_attach);
ImageView imgAttach = (ImageView) view.findViewById(R.id.img_attach);
VideoView vvAttach = (VideoView) view.findViewById(R.id.vv_attach);
LinearLayout llOverlay = (LinearLayout) view.findViewById(R.id.ll_video_overlay);
ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
LinearLayout llUnsupportFile = (LinearLayout) view.findViewById(R.id.ll_unsupport_file);
Log.d(TAG, "image: " + images.size() + " " + images);
Bitmap image = (Bitmap) images.get(position).get("image");
image = CommonUtilities.checkBitmapRotation(bmp);
imgAttach.setVisibility(View.VISIBLE);
vvAttach.setVisibility(View.GONE);
llOverlay.setVisibility(View.GONE);
llUnsupportFile.setVisibility(View.GONE);
imgAttach.setImageBitmap(image);
pBar.setVisibility(View.GONE);
setPreviewClick(imgAttach, position, rlAttach);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
This is where I set the adapter and set notifidydatasetchange:
if (galleryList.size() > 0) {
llNoGallery.setVisibility(View.GONE);
rlHasGallery.setVisibility(View.VISIBLE);
pbGallery.setVisibility(View.GONE);
vpGallery.setVisibility(View.VISIBLE);
tvPageCount.setVisibility(View.VISIBLE);
mImageAdapter = new ImageAdapter(getActivity(), galleryList);
for (HashMap getList : galleryList) {
Log.d(TAG, "onMe: " + getList.toString());
}
vpGallery.setAdapter(mImageAdapter);
vpGallery.addOnPageChangeListener(viewPagerPageChangeListener);
vpGallery.setOffscreenPageLimit(galleryList.size());
mImageAdapter.notifyDataSetChanged();
tvPageCount.setText("1/" + galleryList.size());
} else {
rlHasGallery.setVisibility(View.GONE);
llNoGallery.setVisibility(View.VISIBLE);
}
This is the function to save the images fetched to the arraylist:
private void saveImagesToArrayList(String photo) {
bmp = null;
if (!photo.isEmpty()) {
bmp = imageLoader.loadImageSync(photo);
// tmp hashmap for single image
HashMap<String, Object> hmImage = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImage.put("image", bmp);
galleryList.add(hmImage);
// tmp hashmap for single image
HashMap<String, Object> hmImageInString = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImageInString.put("image", photo);
galleryListInString.add(hmImageInString);
}
}
This is my ViewPagerChangeListener which shows the position of the image swipped to :
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
tvPageCount.setText(position + 1 + "/" + (galleryList.size()));
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
Here I have the setPreviewClick method to open up the image in full screen via intent. The images show here are correct here which displays different images on swipe.
private void setPreviewClick(View view, int imagePosition, RelativeLayout rlAttach) {
final int mPosition = imagePosition;
rlAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
ImageView mImg = (ImageView) view;
mImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
}
The intentViewActivity method is as follows:
public void intentViewActivity(int position) {
Intent intent = new Intent(getActivity(), ViewImageViewPagerActivity.class);
intent.putExtra("images", galleryListInString);
intent.putExtra("image_position", position);
getActivity().startActivity(intent);
}
The one of the parameter of the intentViewActivity method is the ViewImageViewPagerActivity which is this:
package com.epicamera.vms.i_neighbour.activity;
public class ViewImageViewPagerActivity extends AppCompatActivity {
private String TAG = "ViewImageViewPagerActivity";
Toolbar toolbar;
private View temp_view;
private VideoView vv;
private TextView toolbar_title;
private ViewPager insideViewPager;
private MyViewPagerAdapter myViewPagerAdapter;
ArrayList<HashMap<String, Object>> imageList = new ArrayList<>();
Bitmap bmp = null;
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
private String username, companyname, usertype, companylogo, userid, token, userphoto, usergender;
private String android_id;
private String regId;
private Bitmap attachment = null;
private int imagePosition = 0, actualPosition = 0;
private int onPageScrollPosition = 0;
private boolean isVideo = false;
private Handler fileCheckerHandler = new Handler();
private Runnable fileCheckerRunnable = null;
private Uri uri;
// AsyncTask
AsyncTask<Void, Void, Boolean> task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image_video_viewpager);
CommonUtilities.toggleRotationAdvance(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar_title = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//remove the tittle
getSupportActionBar().setDisplayShowTitleEnabled(false);
SessionManager session = new SessionManager(this.getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// session id
username = user.get(SessionManager.KEY_USERNAME);
// user id
companyname = user.get(SessionManager.KEY_COMPANYNAME);
// company id
usertype = user.get(SessionManager.KEY_USERTYPE);
// company id
companylogo = user.get(SessionManager.KEY_COMPANYLOGO);
// user id
userid = user.get(SessionManager.KEY_USERID);
// session token
token = user.get(SessionManager.KEY_TOKEN);
// session user photo
userphoto = user.get(SessionManager.KEY_USERPHOTO);
usergender = user.get(SessionManager.KEY_USERGENDER);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
insideViewPager = (ViewPager) findViewById(R.id.inside_view_pager);
imageList = (ArrayList<HashMap<String,Object>>) getIntent().getExtras().getSerializable("images");
imagePosition = getIntent().getExtras().getInt("image_position");
actualPosition = imagePosition;
myViewPagerAdapter = new MyViewPagerAdapter(ViewImageViewPagerActivity.this, imageList);
insideViewPager.setAdapter(myViewPagerAdapter);
insideViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
insideViewPager.setOffscreenPageLimit(imageList.size());
insideViewPager.setCurrentItem(actualPosition, false);
myViewPagerAdapter.notifyDataSetChanged();
toolbar_title.setText(actualPosition + 1 + " / " + (imageList.size()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_image_menu, menu);
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "id: " + item.getItemId());
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_savetogallery:
String[] count = toolbar_title.getText().toString().split("/");
int value = Integer.parseInt(count[0].trim()) - 1;
HashMap<String, String> child = new HashMap<>();
child.put("image", (String) imageList.get(value).get("image"));
saveToGallery(child, "File");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void saveToGallery(HashMap<String, String> item, final String type) {
//take the current position
final String select_document_link = item.get("image");
final String select_document_name = item.get("image");
final String selected_document = select_document_name.substring(select_document_name.lastIndexOf('/') + 1, select_document_name.length());
final String document_download_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").getPath() + File.separator + selected_document;
final File file = new File(document_download_path);
Log.d(TAG, "path: " + document_download_path + " " + select_document_link);
// Check is the file is exist
// if (file.exists()) {
// //Open the file if exist
// openFile(file);
// } else {
//Download and open the file, if does not exist
try {
Toast.makeText(ViewImageViewPagerActivity.this, "Downloading...", Toast.LENGTH_SHORT).show();
// final ProgressDialog progDailog = ProgressDialog.show(this,
// this.getResources().getString(R.string.txt_title_downloading),
// this.getResources().getString(R.string.txt_document_downloading), true);
new Thread() {
public void run() {
try {
//Download the document
final DownloadManager downloadManager;
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").mkdirs();
downloadManager = (DownloadManager) ViewImageViewPagerActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
// have to replace space to %20
String url = select_document_link.replace(" ", "%20");
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(selected_document)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM + "/i-Neighbour",
selected_document)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
//ADDED LOOP HERE UNTIL FILE DOWNLOAD IS COMPLETE
fileCheckerRunnable = new Runnable() {
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
//download is waiting to retry or resume
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_PENDING:
//download is waiting to start
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_RUNNING:
//download is currently running
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_SUCCESSFUL:
//download has successfully completed
//Open the document
// openFile(file);
Toast.makeText(ViewImageViewPagerActivity.this, type + " saved to Gallery->i-
Neighbour", Toast.LENGTH_SHORT).show();
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
case DownloadManager.STATUS_FAILED:
//download has failed (and will not be retried)
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
}
}
}
};
fileCheckerHandler.postDelayed(fileCheckerRunnable, 1000);
} catch (Exception e) {
Log.d(TAG, "Error: " + e);
}
}
}.start();
} catch (Exception e) {
Log.e("ERROR", "Error -> " + e.getMessage());
}
}
// outside viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
toolbar_title.setText(position + 1 + " / " + (imageList.size()));
onPageScrollPosition = position;
Log.d(TAG, "onpagescrollposition: " + onPageScrollPosition);
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public MyViewPagerAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video2, null);
final VideoView vvFullScreen = (VideoView) view.findViewById(R.id.vv_full_screen);
final TouchImageView imgFullScreen = (TouchImageView) view.findViewById(R.id.img_full_screen);
final ImageView imgVideoBg = (ImageView) view.findViewById(R.id.img_video_bg);
final ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
final LinearLayout llVideoPlay = (LinearLayout) view.findViewById(R.id.ll_video_play);
view.setTag("pos" + position);
//Bitmap image = (Bitmap) images.get(position).get("image");
String image_url = (String) images.get(position).get("image");
imgFullScreen.setVisibility(View.VISIBLE);
vvFullScreen.setVisibility(View.GONE);
llVideoPlay.setVisibility(View.GONE);
Glide.with(context).load(image_url)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgFullScreen);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
Related
I supposed to get ImageDisplay from ArrayJson, it will hit API 3 times
this function will send urlimage 3 times
for(i=0; i<3; i++){send(UrlImage);}
this works
private void getViewYoyo(){
String[] str = new String[3];
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), str);
str[0]="https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg";
str[1]="https://i.chzbgr.com/full/8803531264/hD42E57C6/";
str[2]="https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg";
viewPager.setAdapter(adapterViewPagerHot);
}
But this doesn't work
public void getHighlightMainActivity(int ReceivedDummyUrutan, int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
String[] str = new String[ReceivedTotalThread];
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), str);
if(ReceivedDummyUrutan==0)
str[0]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==1)
str[1]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==2)
str[2]=ReceivedDummyImageOri;
if(ReceivedDummyUrutan==ReceivedTotalThread-1) {
viewPager.setAdapter(adapterViewPagerHot);
}
}
This is adapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[];
public AdapterViewPagerHot(Context context, String[] list) {
this.mContext = context;
this.image_url = list;
}
#Override
public int getCount() {
return image_url.length;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
What will happen with GetHighlight function is it will show the third image only, the first and second image was blank
I am not sure how to make it works like this
String test[]=new String[]{urlImageSend>>Image1, urlImageSend>Image2, urlImageSend>>Image3}
by hitting using for 3 times
Declare one ArrayList which will hold the image URLs in your activity class like this
ArrayList<String> list = new ArrayList<>();
Now define one function which will insert the image URL's in the ArrayList
list.add(imageURL);
Now create your viewpager adapter and set the adapter
adapterViewPagerHot = new AdapterViewPagerHot(getActivity(), list);
Make sure you change string to arraylist in the AdapterViewPagerHot class
I am attempting to pull data from my parse server and display an image and text within a RecyclerView of CardViews. I have encountered a few issues, some of which may not have been corrected appropriately, so please feel free to correct any novice code you find below outside of my two current issues. Finally my two issues are.
The data does not display initially. I have 3 tabs in a ViewPager and I have to swipe over twice in order for it to display. If I'm on tab 1 the data doesn't appear until I swipe to tab 3 and return to tab 1, and vice versa. Because there isn't a tab 4, tab 2 never displays.
The second issue I am currently faced with is that at times the data will not match up. It will have the picture from one row matched with the description from another entity.
Below is my MusicFragment.java
public class MusicFragment extends Fragment {
private ArrayList<String> titles = new ArrayList<>();
private ArrayList<Bitmap> bitmaps = new ArrayList<>();
private ArrayList<String> descriptions = new ArrayList<>();
private boolean notComplete = true;
public MusicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RecyclerView musicRecycler = (RecyclerView)inflater.inflate(
R.layout.fragment_music, container, false);
if (notComplete) {
// Get the MusicFragImages class as a reference.
ParseQuery<ParseObject> query = new ParseQuery<>("MusicFragImages");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
titles.add(title);
descriptions.add(description);
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
}
}
});
}
} else {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete = false;
}
// Create captioned images and registers it to the adapter.
CaptionedImagesAdapter adapter = new CaptionedImagesAdapter(titles, bitmaps, descriptions);
musicRecycler.setAdapter(adapter);
// Set up the layout.
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
musicRecycler.setLayoutManager(layoutManager);
adapter.setListener(new CaptionedImagesAdapter.Listener() {
public void onClick(int position) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), AudioActivity.class);
getActivity().startActivity(intent);
break;
case 1:
intent = new Intent(getActivity(), VideoActivity.class);
getActivity().startActivity(intent);
break;
}
}
});
return musicRecycler;
}
}
Additionally, here is my CaptionedImagesAdapter
class CaptionedImagesAdapter extends
RecyclerView.Adapter<CaptionedImagesAdapter.ViewHolder> {
private final ArrayList<String> captions;
private final ArrayList<Bitmap> bitmaps;
private final ArrayList<String> descriptions;
private Listener listener;
interface Listener {
void onClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final CardView cardView;
public ViewHolder(CardView v) {
super(v);
cardView = v;
}
}
public CaptionedImagesAdapter(ArrayList<String> captions, ArrayList<Bitmap> bitmaps, ArrayList<String> descriptions) {
this.captions = captions;
this.bitmaps = bitmaps;
this.descriptions = descriptions;
}
#Override
public int getItemCount() {
return captions.size();
}
public void setListener(Listener listener) {
this.listener = listener;
}
#Override
public CaptionedImagesAdapter.ViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.card_selection_2, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int index = position;
// Creates a CardView
CardView cardView = holder.cardView;
ImageView imageView = cardView.findViewById(R.id.type_image);
imageView.setImageBitmap(bitmaps.get(index));
imageView.setContentDescription(descriptions.get(index));
// Populate the caption.
TextView textView = cardView.findViewById(R.id.type_text);
textView.setText(captions.get(index));
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (listener != null)
listener.onClick(index);
}
});
}
}
FOR REFERENCE...... if needed MainActivity.java is below
public class MainActivity extends AppCompatActivity {
// Variables for the audio player.
public static MediaPlayer mediaPlayer;
public static int albumId;
public static int currentSong = -1;
public static boolean isPlaying = false;
private static int[] songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Attach the SectionsPageAdapter to the ViewPager
SectionsPageAdapter pagerAdapter = new SectionsPageAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
int currentTab = 0;
pager.setCurrentItem(currentTab);
// Attach the ViewPager to the TabLayout
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
// Starts the player.
player();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the app bar.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_contact:
intent = new Intent(MainActivity.this, ContactActivity.class);
startActivity(intent);
return true;
case R.id.action_cart:
intent = new Intent(this, CartActivity.class);
startActivity(intent);
return true;
case R.id.action_member:
intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class SectionsPageAdapter extends FragmentPagerAdapter {
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MusicFragment();
case 1:
return new ArtFragment();
case 2:
return new FashionFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getText(R.string.title_music);
case 1:
return getResources().getText(R.string.title_art);
case 2:
return getResources().getText(R.string.title_fashion);
}
return null;
}
}
private void player() {
/*Create a background thread that will automatically advance to
* the next song, as long as there is a next song.*/
// Get the songs.
songs = AudioData.audio[albumId].getSongs();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (isPlaying) {
if (!(mediaPlayer.isPlaying()) && currentSong < songs.length - 1) {
mediaPlayer.stop();
mediaPlayer.reset();
currentSong++;
mediaPlayer = MediaPlayer.create(MainActivity.this, songs[currentSong]);
mediaPlayer.start();
isPlaying = true;
}
//Set the flag to false at the end of the album.
if (currentSong == songs.length) {
isPlaying = false;
}
}
handler.postDelayed(this, 1000);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
}
Thanks again to Harikumar for correcting the first issue. I ended up correcting the second issue with the code below. It was within the enhance for loop.
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
Bitmap bitmap;
titles.add(title);
descriptions.add(description);
byte[] data;
try {
data = file.getData();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
adapter.notifyDataSetChanged(); //notify your adapter that data has changed
} catch (ParseException pe) {
Toast.makeText(getContext(), pe.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Data will be updated if you notify your adapter CaptionedImagesAdapter. Try modifying the code to:
public class MusicFragment extends Fragment {
private ArrayList<String> titles = new ArrayList<>();
private ArrayList<Bitmap> bitmaps = new ArrayList<>();
private ArrayList<String> descriptions = new ArrayList<>();
private CaptionedImagesAdapter adapter;
private boolean notComplete = true;
public MusicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
RecyclerView musicRecycler = (RecyclerView)inflater.inflate(
R.layout.fragment_music, container, false);
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
musicRecycler.setLayoutManager(layoutManager);
adapter = new CaptionedImagesAdapter(titles, bitmaps, descriptions);
musicRecycler.setAdapter(adapter);
if (notComplete) {
// Get the MusicFragImages class as a reference.
ParseQuery<ParseObject> query = new ParseQuery<>("MusicFragImages");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject object : objects) {
String description = (String) object.get("description");
ParseFile file = (ParseFile) object.get("image");
String title = (String) object.get("title");
titles.add(title);
descriptions.add(description);
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(bitmap);
adapter.notifyDataSetChanged(); //notify your adapter that data has changed
}
}
});
}
} else {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
notComplete = false;
}
adapter.setListener(new CaptionedImagesAdapter.Listener() {
public void onClick(int position) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), AudioActivity.class);
getActivity().startActivity(intent);
break;
case 1:
intent = new Intent(getActivity(), VideoActivity.class);
getActivity().startActivity(intent);
break;
}
}
});
return musicRecycler;
}
}
Here is a small optimization for your 2nd solution: update notifyDataSetChanged() only once after the for loop (put it just outside the for loop). This is better in terms of performance.
I want to fetch 10 records in listview and other records fetch on scroll to bottom. I'm a new in this please help me. Here's my fragment of Java code and adapter:
Latest_Fragment.java
private static final String TAG = LatestFragment.class.getSimpleName();
// Movies json url
private static final String url = "http://abc.news/android/lastest.php?page=1";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private List<Movie> additems;
private ListView listView;
private CustomListAdapter adapter;
boolean flag_loading = true;
private static String Title="title";
private static String Genre="genre";
private static String Rating="rating";
private static String Sec_id="secid";
private static String Category="category";
private static String bitmap="thumbnailUrl";
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.latest_layout, container, false);
//getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent2 = new Intent();
getActivity().setResult(Activity.RESULT_OK, intent2);
list = (ListView) v.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
list.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// flag_loading = false;
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setSec_id(obj.getString("sec_id"));
movie.setCategory(obj.getString("category"));
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("rating"));
// movie.setYear(obj.getString("releaseYear"));
movie.setGenre(obj.getString("genre"));
// Genre is json array
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
Toast.makeText(getActivity().getBaseContext(), "Bummer..There's No Internet connection!", Toast.LENGTH_LONG).show();
}
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), News_Detail.class);
bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();
intent.putExtra("images", bitmap);
final String names = ((TextView) view.findViewById(R.id.title)).getText().toString();
intent.putExtra(Title, names);
String genredescription = ((TextView) view.findViewById(R.id.genre)).getText().toString(); //must for send data
intent.putExtra(Genre, genredescription);
String date = ((TextView) view.findViewById(R.id.rating)).getText().toString();
intent.putExtra(Rating, date);
startActivity(intent);
}
});
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
customlistadapter.java
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
// first row layout change below code is working
#Override
public int getViewTypeCount() { return 2; }
//if remove below code then chage layout randomly
#Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
} else {
return 1;
}
}
// first row layout change above code is working
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
if(position == 0) {
convertView = inflater.inflate(R.layout.list_row2, null);
}else
{
convertView = inflater.inflate(R.layout.list_row, null);
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
final TextView sec_id = (TextView) convertView.findViewById(R.id.sec_id);
final TextView category = (TextView) convertView.findViewById(R.id.category);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText(m.getRating());
// genre
genre.setText(m.getGenre());
sec_id.setText(m.getSec_id());
category.setText(m.getCategory());
// release year
// year.setText(m.getYear());
ImageView btn = (ImageView) convertView.findViewById(R.id.share);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "\n" + "\n" + "http://vasundharadeep.news/News/"+sec_id.getText().toString()+"/"+category.getText().toString());
activity.startActivity(intent);
}
});
return convertView;
}
}
Abstract class
public abstract class HidingScrollListener implements AbsListView.OnScrollListener {
private static final int HIDE_THRESHOLD = 15;
public boolean controlsVisible = true;
public int scrolledDistance = 0;
public int previousTotal = 0;
public boolean loading = true;
public int current_page = 1;
public LinearLayoutManager mLinearLayoutManager;
private int visibleThreshold = 2;
public HidingScrollListener(LinearLayoutManager layoutManager) {
this.mLinearLayoutManager = layoutManager;
}
#Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// int firstVisibleItem =firstVisibleItem;
if (firstVisibleItem == 0) {
if (!controlsVisible) {
onShow();
controlsVisible = true;
}
} else {
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide();
controlsVisible = false;
scrolledDistance = 0;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow();
controlsVisible = true;
scrolledDistance = 0;
}
}
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public abstract void onHide();
public abstract void onShow();
public abstract void onLoadMore(int current_page);
}
// Current Page getter setter
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
Check it out below code
public class MyFragment extends Fragment implements OnScrollListener {
private ListView listView;
private ArrayList<DataModel> dataList = new ArrayList<DataModel>();
private boolean mHasRequestedMore;
onCreateView(…..){
listView = view.findViewById();
listView.setonScrollLestener(this);
callWebservice();
}
#Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
if (!mHasRequestedMore) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (lastInScreen >= totalItemCount) {
mHasRequestedMore = true;
callWebservice();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState{}
I want to create a cache that stores present listview populated from the server which means even if users are not online they can have access to the listview data been loaded before going offline. These are my codes that contains the swipelistlayout and the main class Tab4
public class Tab4 extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
private int index;
ImageSwitcher switcher;
android.os.Handler Handler = new android.os.Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
private String URL_TOP_250 = "http://172.126.43.152/locator/test/refractor2.php?offset=";
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_4,container,false);
listView = (ListView) vi.findViewById(R.id.list4);
listView.setBackgroundColor(Color.WHITE);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
intent.setClass(getActivity(), Newbies.class);
//String text = String.valueOf(movieList.get(position));
String text = movieList.get(position).getSlug();
//Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), Newbies.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
// Movie m = new Movie();
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
String author = movieObj.getString("postAuthor");
String slug = movieObj.getString("postSlug");
String categories = "technologies";
String thumbnailUrl = movieObj.getString("postPic");
String year = movieObj.getString("postDate");
Movie m = new Movie(rank, title, author, slug, categories, thumbnailUrl, year);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
And the SwipeListAdapter class is below...
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView author = (TextView) convertView.findViewById(R.id.author);
//String slug;
TextView category = (TextView) convertView.findViewById(R.id.category);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieList.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
author.setText(m.getAuthor());
// slug.setText(m.getAuthor());
category.setText(m.getCategories());
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Any help will be appreciated. Thanks.
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.