I am using ParseQueryAdapter like so:
public class MyPostedSalesAdapter extends ParseQueryAdapter<Sale> {
static String mTAG = "LocalSalesAdapter";
static ParseUser mCurrentUser = ParseUser.getCurrentUser();
public MyPostedSalesAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<Sale>() {
#SuppressWarnings("unchecked")
public ParseQuery<Sale> create() {
#SuppressWarnings("rawtypes")
ParseQuery query = new ParseQuery("Sales");
query.orderByDescending("createdAt");
query.whereEqualTo("postedBy", mCurrentUser.getUsername());
try {
int salesAmount = query.count();
ProfileActivity.setTextView(salesAmount);
} catch (ParseException e) {
e.printStackTrace();
}
return query;
}
});
}
#Override
public View getItemView(Sale sale, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.listview_cell, null);
}
super.getItemView(sale, v, parent);
ParseImageView saleImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile photoFile = sale.getParseFile("photo");
if (photoFile != null) {
saleImage.setParseFile(photoFile);
saleImage.loadInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
}
});
} else {
// Clear ParseImageView if the object has no photo, set placeholder.
saleImage.setImageResource(R.drawable.placeholder);
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView_listView_saleTitle);
titleTextView.setText(sale.getSaleTitle());
TextView priceTextView = (TextView) v.findViewById(R.id.textView_listView_salePrice);
priceTextView.setText(sale.getSalePrice());
return v;
}
}
And simply onResume, setting the adapter to ListView like so:
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
// Setting up currentUser to current logged in user
// If user is not logged in, present them with Login Activity
if (mCurrentUser == null || !isUserOnline())
{
presentUserWithLogin();
}
else
{
mOwnSalesAdapter = new MyPostedSalesAdapter(this);
mOwnSalesAdapter.loadObjects();
mUserSales.setAdapter(mOwnSalesAdapter);
}
}
I did this onResume, thinking every time the Activity is loaded, new data is pulled using query and displayed in the ListView. However this is not the case, and occasionally will act like this. Normally I have to close the entire app for the ListView to update properly and display any updates to the data. Even If I were to logout of the current parse user, and login on another account without closing the app, the previous user's posts sometimes appear as well in the listview. What am I doing wrong? I never encountered such problems with working in iOS. Also noticed if I were to delete an Item from Parse and go back, usually the item still appears in the ListView.
Hi just call in onResume()
if(mOwnSalesAdapter!=null)
mOwnSalesAdapter.notifyDataSetChanged();
Related
I, am new to android. and I created one view pager which fetching image from firebase. and It's working fine. but there are some loopholes in that view pager which I failed to solve.
1) My View-pager not getting update on real-time basis. Means when ever I modify image in firebase. it's does't effect on real-time basis. I have to close my app and then have to start it again for seeing those updates.
2) When I am removing item from my list in firebase. My app getting crashed and in Logcat this exception is thrown.
java.lang.IndexOutOfBoundsException: Index: -1, Size: 5
at java.util.ArrayList.add(ArrayList.java:483)
at com.release.pack.lootbox.Fragments.HomeFragment$7.onEvent(HomeFragment.java:294)
at com.release.pack.lootbox.Fragments.HomeFragment$7.onEvent(HomeFragment.java:281)
Here is my code:
Slider Image Adapter:
public class SliderImageAdapter extends SliderViewAdapter<SliderImageAdapter.SliderAdapterVH> {
public List<Banner> bannerList;
public Context context;
public SliderImageAdapter(Context context, List<Banner> bannerList) {
this.bannerList = bannerList;
this.context = context;
}
#Override
public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_myshop, parent, false);
return new SliderAdapterVH(inflate);
}
#Override
public void onBindViewHolder(final SliderAdapterVH viewHolder, final int position) {
Glide.with(viewHolder.itemView)
.load(bannerList.get(position).getmSliderImage())
.fitCenter()
.into(viewHolder.imageViewBackground);
}
#Override
public int getCount() {
return bannerList.size();
}
class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
View itemView;
ImageView imageViewBackground;
ImageView imageGifContainer;
TextView textViewDescription;
public ProgressBar progressBar;
public ImageView imageViewFailed;
public SliderAdapterVH(View itemView) {
super(itemView);
imageViewBackground = itemView.findViewById(R.id.iv_auto_image_slider);
imageGifContainer = itemView.findViewById(R.id.iv_gif_container);
textViewDescription = itemView.findViewById(R.id.tv_auto_image_slider);
progressBar = itemView.findViewById(R.id.featured_deal_progress);
imageViewFailed = itemView.findViewById(R.id.featured_deal_img_failed_to_load);
this.itemView = itemView;
}
}
}
Home Fragment :
private SliderImageAdapter sliderImageAdapter;
private List<Banner> bannerList;
bannerList = new ArrayList<>();
sliderImageAdapter = new SliderImageAdapter(getActivity(),bannerList);
sliderMyshop = view.findViewById(R.id.imageSlider);
sliderMyshop.setSliderAdapter(sliderImageAdapter);
sliderMyshop.setIndicatorAnimation(IndicatorAnimations.WORM); //set indicator animation by using SliderLayout.IndicatorAnimations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
sliderMyshop.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
sliderMyshop.setIndicatorSelectedColor(Color.WHITE);
sliderMyshop.setIndicatorUnselectedColor(Color.GRAY);
sliderMyshop.startAutoCycle();
mFirestore.collection("Banner").orderBy("priority", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot documentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
assert documentSnapshots != null;
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String doc_id = doc.getDocument().getId();
Banner banner = doc.getDocument().toObject(Banner.class).withDocId(doc_id);
bannerList.add(doc.getNewIndex(), banner);
sliderImageAdapter.notifyDataSetChanged();
} else if (doc.getType() == DocumentChange.Type.MODIFIED) {
String docID = doc.getDocument().getId();
Banner changedModel = doc.getDocument().toObject(Banner.class).withDocId(docID);
if (doc.getOldIndex() == doc.getNewIndex()) {
// Item changed but remained in same position
bannerList.set(doc.getOldIndex(), changedModel);
// sliderImageAdapter.notifyItemChanged(doc.getOldIndex());
} else {
// Item changed and changed position
bannerList.remove(doc.getOldIndex());
bannerList.add(doc.getNewIndex(), changedModel);
// sliderImageAdapter.notifyItemMoved(doc.getOldIndex(), doc.getNewIndex());
}
} else if (doc.getType() == DocumentChange.Type.REMOVED) {
// remove
bannerList.remove(doc.getOldIndex());
// sliderImageAdapter.notifyItemRemoved(doc.getOldIndex());
}
}
}
});
When I am adding a new image in firebase it's getting update on real-time basis. but not when I am doing modification in my image. or removing the item from my list.
Getting crashed
bannerList.add(doc.getNewIndex(), banner);
This line is the reason for the IndexOutOfBoundsException.
(java.lang.IndexOutOfBoundsException: Index: -1, Size: 5)
doc.getNewIndex() is returning -1. and list can not accept -1 as an index. so please check your doc.getNewIndex().
For realtime update
bannerList.clear();
add this code before your for loop, otherwise redundant data will be added and you can not update the new changes.
See this: The snapshot handler will receive a new query snapshot every time the query results change (that is, when a document is added, removed, or modified).
for every changes whole collection will be fetched
I am working on a Bitcoin dashboard for Android. The following fragment uses the entered wallet address to display the balance in BTC. When an address is entered, it will add to the listview. When an item in the listview is selected, it will set the edittext to that address.
It is not yet complete, but for now it is throwing an error with the message, "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."
I currently have two example addresses in place for testing. If I select one then the other then the first again etc. it works fine. The error appears when I select one, press the button, then select the other.
public class WalletFragment extends Fragment {
ArrayList<String> savedWallets;
ArrayAdapter<String> listAdapter;
String newWalletAddress, jsonString, address, balance;
JSONObject jsonObj, data;
Double balanceDouble;
DecimalFormat df = new DecimalFormat("#.####");
private WalletListener listener;
public interface WalletListener {
void onCreateWallet(String newWalletAddress);
}
public WalletFragment() {
// Required empty public constructor
}
public static WalletFragment newInstance(ArrayList<String> wallets) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
fragment.setArguments(args);
return fragment;
}
public static WalletFragment newInstance(ArrayList<String> wallets, String json) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
args.putString("jsonString", json);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof WalletListener) {
listener = (WalletListener) context;
}
else {
throw new ClassCastException(context.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wallet, container, false);
ListView lv = (ListView) v.findViewById(R.id.walletListView);
df.setRoundingMode(RoundingMode.CEILING);
final EditText walletAddressEditText = (EditText) v.findViewById(R.id.walletAddressEditText);
TextView addressTV = (TextView) v.findViewById(R.id.walletAddresstextView);
TextView balanceTV = (TextView) v.findViewById(R.id.walletBalanceTextView);
savedWallets = getArguments().getStringArrayList("savedWallets");
if (savedWallets == null) {
savedWallets = new ArrayList<>();
}
savedWallets.add("198aMn6ZYAczwrE5NvNTUMyJ5qkfy4g3Hi");
savedWallets.add("1L8meqhMTRpxasdGt8DHSJfscxgHHzvPgk");
// TODO remove test addresses
jsonString = getArguments().getString("jsonString");
if (jsonString != null) {
try {
jsonString = getArguments().getString("jsonString");
jsonObj = new JSONObject(jsonString);
data = new JSONObject(jsonObj.getString("data"));
balance = data.getString("balance");
balanceDouble = Double.parseDouble(balance);
address = data.getString("address");
String walletAddressText = getResources().getString(R.string.wallet_address, address);
addressTV.setText(walletAddressText);
String walletBalanceText = getResources().getString(R.string.wallet_balance, df.format(balanceDouble));
balanceTV.setText(walletBalanceText);
// TODO add viewing for other wallet data at some point
} catch (Exception e) {
Log.d("TickerException", e.toString());
}
}
listAdapter = new ArrayAdapter<>(getActivity(), R.layout.main_list_rows, savedWallets);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String address = savedWallets.get(position);
Log.d("wallet", "Selected: " + address);
walletAddressEditText.setText(address);
}
});
Button button = (Button) v.findViewById(R.id.createWalletButton);
View.OnClickListener ocl = new View.OnClickListener() {
#Override
public void onClick(View view) {
newWalletAddress = walletAddressEditText.getText().toString();
if (walletAddressEntryStructuralValidation(newWalletAddress)) {
if (newWalletAddress != null) {
listener.onCreateWallet(newWalletAddress);
}
else {
Toast.makeText(getActivity(), "newWalletAddress is null", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getActivity(), "Please enter a valid wallet address (length is currently " + newWalletAddress.length() + ").", Toast.LENGTH_SHORT).show();
}
}
};
// TODO check if wallet is already on list
button.setOnClickListener(ocl);
return v;
}
public boolean walletAddressEntryStructuralValidation(String address) {
return ((address.length() > 25) &&
(address.length() < 36) && (
(address.substring(0,1).equals("1") ||
(address.substring(0,1).equals("3")))));
}
// Wallet addresses are 26-35 alphanumeric characters and begin with 1 or 3
}
I believe this is all the relevant code but I will be closely watching this thread if anyone needs to request additional source.
That message means that the contents of the adapter (the order of items you see in getItem) changed but notifyDataSetChanged or similar function wasn't called. When changing the items in your adapter contents (which in this case is the savedWallets array list) you must call one of those functions.
Note: If you're adding several objects at once, you only need to call it once after all are added/removed. If you're mutating an object but not adding/removing it, you do not need to call it, but calling it may be the easiest way of doing a redraw.
I have been searching SO threads for answers but couldn't figure out my issue from previous discussion. I have a listview which loads about 50 images (it used to be about 100 but this was barely loading any images at all). After grabbing my JSON content (including image URL) from an api endpoint, through an adapter, my code puts it inside the listview.
Currently, with 50 images, picasso will load one image at a time as I scroll down on the feed. I feel as if keeping the scroll fixed on one item in the listview will make that image load faster. As I scroll up, however, it puts the placeholder back in and reloads the image again. Is there a way to solve this issue?
public class MainActivity extends Activity {
private List<Post> myPosts = new ArrayList<Post>();
protected String[] mBlogPostTitles;
public static final String TAG = MainActivity.class.getSimpleName();//prints name of class without package name
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable()) {
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask(); // new thread
getBlogPostsTask.execute();// don't call do in background directly
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void populateListView() {
ArrayAdapter<Post> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.postsListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Post>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// make sure we have a view to work with
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent,false);
}
//find the post to work with
Post currentPost = myPosts.get(position);
Context context = itemView.getContext();
String imageURL = currentPost.getImage();
if(imageURL == null || imageURL.isEmpty()){
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_image);
imageView.setVisibility(View.GONE);
}else{
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_image);
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
.error(R.drawable.stadiumarcadium)
.into(imageView);
imageView.setVisibility(View.VISIBLE);
}
//Username
TextView userText = (TextView) itemView.findViewById(R.id.item_txtUser);
userText.setText(currentPost.getUser());
//Time of post
TextView timeText = (TextView) itemView.findViewById(R.id.item_txtTime);
timeText.setText("" + currentPost.getTime());
//The actual post
TextView postText = (TextView) itemView.findViewById(R.id.item_txtPost);
postText.setText("" + currentPost.getPost());
//The actual post
TextView likesText = (TextView) itemView.findViewById(R.id.item_txtLikes);
likesText.setText("" + currentPost.getLikes());
return itemView;
}
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, List> {
#Override
protected List doInBackground(Object[] params) {
int responseCode = -1;//need to have this variable outside scope of try/catch block
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(""); /// api endpoint redacted
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK){ //could have used just 200 value
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
for(int i=0; i < jsonPosts.length(); i++ ){
JSONObject jsonPost = jsonPosts.getJSONObject(i);
int post_id = Integer.parseInt(jsonPost.getString("id"));
String post_user = jsonPost.getString("user");
String post_account = jsonPost.getString("account");
int post_time = Integer.parseInt(jsonPost.getString("time"));
String post_post = jsonPost.getString("post");
String post_image = jsonPost.getString("image");
int post_likes = Integer.parseInt(jsonPost.getString("likes"));
myPosts.add(new Post(post_id, post_user, post_account, post_time, post_post, post_image, "profile picture here", post_likes));
}
}else{
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(TAG, "Exception caught");
}
catch (IOException e){
Log.e(TAG, "Exception caught");
}
catch (Exception e){//must be in this order, this is the last, general catch
Log.e(TAG, "Exception caught", e);
}
return null;
}
#Override
protected void onPostExecute(List result) {
// call populateListView method here
populateListView();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
EDIT:
I have updated my code into a view holder pattern, created two separate views (one for a post with an image, one for a post with just text) and also included Picasso's new scroll detection capabilities.
I have seen an improvement in some of the images loading quicker, at least when the view is focused while scrolling, the image is more likely to load now. However, on scroll up those same images that were once loaded, disappear. It feels as if Picasso is only loading 4-5 images at a time and replacing the ones already loaded to make room. My updated code is below:
public class MainActivity extends Activity {
private List<Post> myPosts = new ArrayList<Post>();
protected String[] mBlogPostTitles;
public static final String TAG = MainActivity.class.getSimpleName();//prints name of class without package name
...
private void populateListView() {
Activity activity = MainActivity.this;
ArrayAdapter<Post> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.postsListView);
list.setAdapter(adapter);
list.setOnScrollListener(new SampleScrollListener(activity));
}
private class MyListAdapter extends ArrayAdapter<Post>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myPosts);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
String imageURL = myPosts.get(position).getImage();
if(imageURL == null || imageURL.isEmpty()){
return 1; // text based
}else{
return 0; // image based
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PostViewHolder holder;
int type = getItemViewType(position);
View itemView = convertView;
// make sure we have a view to work with
if (itemView == null) {
holder = new PostViewHolder();
if(type == 1) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
} else {
itemView = getLayoutInflater().inflate(R.layout.image_post_view, parent, false);
holder.image = (ImageView) itemView.findViewById(R.id.item_image);
}
holder.user = (TextView) itemView.findViewById(R.id.item_txtUser);
holder.time = (TextView) itemView.findViewById(R.id.item_txtTime);
holder.post = (TextView) itemView.findViewById(R.id.item_txtPost);
holder.likes = (TextView) itemView.findViewById(R.id.item_txtLikes);
itemView.setTag(holder);
} else {
holder = (PostViewHolder) itemView.getTag();
}
//find the post to work with
Post currentPost = myPosts.get(position);
if(type != 1) {
Context context = itemView.getContext();
String imageURL = currentPost.getImage();
Picasso.with(context).setIndicatorsEnabled(true);
//Picasso.with(context).setLoggingEnabled(true);
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
//.skipMemoryCache()
.error(R.drawable.stadiumarcadium)
.fit()
.into(holder.image);
}
//Username
holder.user.setText(currentPost.getUser());
//Time of post
holder.time.setText("" + currentPost.getTime());
//The actual post
holder.post.setText(currentPost.getPost());
//Likes for the post
holder.likes.setText("" + currentPost.getLikes());
return itemView;
}
}
public class SampleScrollListener implements AbsListView.OnScrollListener {
private final Context context;
public SampleScrollListener(Context context) {
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
final Picasso picasso = Picasso.with(context);
if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_TOUCH_SCROLL) {
picasso.resumeTag(context);
} else {
picasso.pauseTag(context);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// Do nothing.
}
}
...
}
Where is the issue coming from? Should I be preloading these images somehow in the cache? While I have already looked into Picasso's new priority feature, should I be telling Picasso somehow to load images in the order in which they appear in my listview? Any ideas? How can I "keep" images that have already been loaded on scroll up?
use resize with picasso
Picasso.with(context)
.load(imageURL)
.tag(context)
.placeholder(R.drawable.kanye8080s)
.error(R.drawable.stadiumarcadium)
.into(imageView)
.resize(x,y);
//This would definitely help
The size of the memory cache of Picasso is limited so it does not generate out of memory errors when scrolling long lists. Once the images are out of the memory cache, the placeholder will be displayed while the image is reloaded from either the disk cache or the network.
The disk cache is enabled by default so the reload time should be very fast. You can use setIndicatorsEnabled(true) to see where the images are being loaded from.
If you are finding that Picasso is reloading the images from network, this is probably a problem with the HTTP headers being sent from the server. I don't believe Picasso actually caches the images on disk itself, instead relying on the HTTP layer, which will obey a no-cache header, and will reload from network if the expire time elapses.
I'd look at two things.
Number one is the sizes of the images being loaded. I don't know what the default maximum cache size is in Picasso, but it sounds like you may be exceeding it with just a few images, causing the others to be evicted from the cache.
Number two is probably not the core issue, but also contributes to performance.
You are doing a lot findViewById() calls, which are fairly expensive.
Look into the "ViewHolder" pattern for "caching" those lookups.
Edit - see Jake Wharton's answer to a similar question for more detail
Use :
recyclerview.getRecycledViewPool().setMaxRecycledViews(0, 0);
This solved my issue
I would suggest you to use GLIDE for image loading. Since GLIDE is fast and with its cache loading feature you can get super fast image loading, With GLIDE you get lot of features..
Download here
https://github.com/bumptech/glide
I am trying to populate data from my main activity using the adapter below. When i run the activity the screen remains blanked. I believe it has to do with the ArrayList which is null perhaps. Can someone tell me why my data is not being displayed. am on this bug for three days now :/
public class CopyOfSecondWheelAdapter extends AbstractWheelTextAdapter {
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
public ImageLoader imageLoader;
Convertor main;
public CopyOfSecondWheelAdapter(Context context) {
super(context, R.layout.count_layout, NO_RESOURCE);
setItemTextResource(R.id.country_name);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
ImageView img = (ImageView) view.findViewById(R.id.flag);
imageLoader.DisplayImage(PostList.get(index).getDevise(), img);
System.out.println("get item count:"+getItemsCount() );
TextView text = (TextView)view.findViewById(R.id.lib);
text.setText(PostList.get(index).getQuotite());
return view;
}
#Override
public int getItemsCount() {
return PostList.toArray().length;
}
#Override
protected CharSequence getItemText(int index) {
return PostList.get(index).getDevise().toString();
}
}
UPDATE:
In my Main class i have already an
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
which is populated.
Here is my main class that is my convertor.class
ArrayList<convertor_pst> PostList = new ArrayList<convertor_pst>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.convertor);
context = this;
text_devise_two = (TextView)findViewById(R.id.text_spacetwo);
final WheelView country = (WheelView) findViewById(R.id.country);
country.setVisibleItems(10);
country.setViewAdapter(new FirstWheelAdapter(this));
edt_validate = (EditText)findViewById(R.id.edt_validate);
current_type_loc = (TextView)findViewById(R.id.current_type_loc);
refresh_header= (TextView)findViewById(R.id.refresh_header);
//set current time
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
String formattedDate = df.format(c.getTime());
refresh_header.setText(getResources().getString(R.string.mise_a_jour)+" "+formattedDate);
image_one = (ImageView)findViewById(R.id.image_one);
image_two = (ImageView)findViewById(R.id.image_two);
final WheelView currency = (WheelView) findViewById(R.id.currency);
currency.setVisibleItems(10);
currency.setViewAdapter(new CopyOfSecondWheelAdapter(this));
country.addChangingListener(new OnWheelChangedListener() {
#Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!scrolling) {
}
}
});
country.addScrollingListener( new OnWheelScrollListener() {
#Override
public void onScrollingStarted(WheelView wheel) {
scrolling = true;
}
#Override
public void onScrollingFinished(WheelView wheel) {
scrolling = false;
//1.
wheelSelector(country.getCurrentItem());
}
});
currency.addScrollingListener( new OnWheelScrollListener() {
#Override
public void onScrollingStarted(WheelView wheel) {
scrolling = true;
}
#Override
public void onScrollingFinished(WheelView wheel) {
scrolling = false;
//1.
secondWheel(currency.getCurrentItem());
}
});
country.setCurrentItem(1);
currency.setCurrentItem(3);
new loadingTask().execute();
}
/*1. Change currency */
public void wheelSelector (int id){
if (id==0){
current_type_loc.setText("EUR");
image_one.setBackgroundResource(R.drawable.eur);
}else {
current_type_loc.setText("USD");
image_one.setBackgroundResource(R.drawable.usd);
}
}
class loadingTask extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(Convertor.this, "", "Chargement en cours..", true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
doc = Jsoup.parse(getxml,"", Parser.xmlParser());
taux = doc.select("taux");
for (int i = 0; i < taux.size(); i++) {
PostList.add(new convertor_pst(taux.get(i).getElementsByTag("devise").text().toString(),
taux.get(i).getElementsByTag("dateCours").text().toString(),
taux.get(i).getElementsByTag("libelle").text().toString(),
taux.get(i).getElementsByTag("quotite").text().toString(),
taux.get(i).getElementsByTag("fixing").text().toString()));
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
envelope =
"soap content"
String requestEnvelope=String.format(envelope, "28-03-2013","true");
getxml = Util.CallWebService(URL,SOAP_ACTION,requestEnvelope);
System.out.println(getxml);
return null;
}
}
public void secondWheel(int index){
text_devise_two.setText(PostList.get(index).getDevise());
edt_validate.setText(" "+PostList.get(index).getFixing());
}
/*
*
* (non-Javadoc)
* #see android.app.Activity#onPause()
* check if activity go to background
*/
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Util.isApplicationBroughtToBackground(Convertor.this)==true){
startActivity(new Intent(Convertor.this,Compte.class));
}
}
}
This is the original wheel adapter class
public class CopyOfSecondWheelAdapter extends AbstractWheelTextAdapter {
ArrayList<convertor_pst> PostList;
public ImageLoader imageLoader;
// Countries names
private String countries[] =
new String[] {"EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD","EUR", "USD"};
// Countries flags
private int flags[] = new int[] {R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd,R.drawable.eur, R.drawable.usd};
/**
* Constructor
*/
Convertor main;
public CopyOfSecondWheelAdapter(Context context) {
super(context, R.layout.count_layout, NO_RESOURCE);
setItemTextResource(R.id.country_name);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
ImageView img = (ImageView) view.findViewById(R.id.flag);
img.setImageResource(flags[index]);
TextView text = (TextView)view.findViewById(R.id.lib);
text.setText("code");
return view;
}
#Override
public int getItemsCount() {
return countries.length;
}
#Override
protected CharSequence getItemText(int index) {
return countries[index];
}
}
As far as I understand
currency.setViewAdapter(new CopyOfSecondWheelAdapter(this));
this line creates the adapter, but you fill it up at this line :
new loadingTask().execute();
which is after, so you must call
yourAdapter.notifyDataSetChanged();
on your adapter to update the data.
Android Developer Help says
notifyDataSetChanged()
Notifies the attached observers that the
underlying data has been changed and any View reflecting the data set
should refresh itself.
So in your case you must
create an adapter (yourAdapter = new CopyOfSecondWheelAdapter ....)
assign it with the setViewAdater (WheelView.setViewAdapter(yourAdapter))
in the "postExecute" of your async task, do a call with yourAdapter.notifyDataSetChanged();
By the way, I am not sure to understand what you are doing, but in case you need to have a set of data displayed at two different locations, you don't need to duplicate (create a copy). The two list display can share the same adapter.
UPDATE
You have done an update to your question and I answer to that update :
In the original adapter the countries are not loaded in the async task. So when you assign the adapter, the display show the correct values because they are present in the adapter at the moment you assign it.
In your case, you load the values in the async task. When you create the adapter it is empty and you assign it empty, so the display shows an empty list. You should notify your display of the data change.
So in the original, no need to notify as the data is the correct one at the time of assignment. In your case you have to implement a notifyDataSetChanged(). Or change the type of adapter you are extending.
If I see it correctly, you have 2 times a variable name PostList which confuses you. One is created in your activity and one in your adapter and ass you call add() to the variable of your activity, the list in your adapter never gets the items.
Create a setter for the list in your adapter and set the list in your onPostExecute().
I have a custom adapter that visualize each row in the list of Orders.
public class OrderRowAdapter extends BaseAdapter implements OnClickListener {
OrderList items_;
LayoutInflater inflater_;
int list_view_resource_id_;
private final String TAG = "OrderRowAdapter";
public OrderRowAdapter(Context context, int list_view_resource_id,
OrderList items) {
this.list_view_resource_id_ = list_view_resource_id;
this.items_ = items;
this.inflater_ = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public Object getItem(int position) {
return items_.getOrders(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG, "View updated for item in position = " + position);
View v = convertView;
if (v == null) {
v = inflater_.inflate(list_view_resource_id_, parent);
}
Order item = items_.getOrders(position);
if (item != null) {
TextView order_info_tv = (TextView) v.findViewById(R.id.order_info);
TextView order_status_tv = (TextView) v.findViewById(R.id.order_status);
if (order_info_tv != null) {
order_info_tv.setText(
String.format("For customer: %s\nTotal of %d items", item.getCustomerId(), item.getItemsCount()));
}
if (order_status_tv != null) {
order_status_tv.setText("Status: " + getStatusText(item.getStatus()));
}
}
return v;
}
public int getCount() {
if (items_ == null) {
Log.d(TAG, "Null so get count returned 0");
return 0;
} else {
Log.d(TAG, "Get count returned " + items_.getOrdersCount());
return items_.getOrdersCount();
}
};
After querying new list of orders from a web service, I want to update the content of the ListView, so I have my Activity does the updating before calling notifyDataSetChanged()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orders);
initThreading();
findViews();
setUrls();
// Load the list of order from disk
try {
order_list_ = OrderList.parseFrom(new FileInputStream(
"/sdcard/orderList.bin"));
} catch (FileNotFoundException e) {
Log.e(TAG, "Cannot find the file", e);
} catch (IOException e) {
Log.e(TAG, "Cannot read the file", e);
}
order_row_adapter_ = new OrderRowAdapter(OrderActivity.this,
R.layout.order_row, order_list_);
orders_listview_.setAdapter(order_row_adapter_);
// Request new updates from the server
updateOrderInformation(-1);
}
public void updateOrders(InputStream new_order_stream) {
Log.d(TAG, "Updating order UI");
try {
order_list_.parseFrom(new_order_stream);
} catch (IOException e) {
Log.e(TAG, "IOException" , e);
}
runOnUiThread(new Runnable() {
public void run() {
guiUpdateOrders();
}
});
}
private void guiUpdateOrders() {
order_row_adapter_.notifyDataSetChanged();
Log.d(TAG, "Dataset notified that it has changed. GUI update anytime now.");
}
But, the getView() method of OrderRowAdapter is never called. The ListView is never updated.
It turns out the problem with my getView() not being called is because it is not visible. My layout xml has the upper TextView with fill_parent for its height. Thus the entire view only has that single TextView visible.
Solution: check the graphical view of the layout in question to make sure the ListView is visible.
Make sure BaseAdapter methods
registerDataSetObserver(DataSetObserver observer)
unregisterDataSetObserver(DataSetObserver observer)
are not overridden.
To change the content of your ListView, you must keep using the same reference to the List. Here you're creating another list and assigning it to the items_ variable (which does not contain the list itself, it's just a place to store a reference to a List), but your View still has a reference to the old list.
Instead of items_ = new_order_list this should work :
items_.clear();
items_.addAll(new_order_list);
EDIT :
To explain it better, try to create a new variable named old_items :
public void setNewOrderList(List<Order> new_order_list)
{
Log.d(TAG, "New Order List available. Num items = " + new_order_list.size());
List<Order> old_items = items_; // store the reference to the old list
items_ = new_order_list;
Log.d(TAG, "items_.size() = " + items_.size());
Log.d(TAG, "old_items.size() = " + old_items.size()); // The old list still exists, and it's the one used by your ListView
notifyDataSetChanged();
}
If all above answers not working try with invalidateViews()
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them).
Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.
listView.invalidateViews()
My sample implementation,
lvitems.post(new Runnable() {
#Override
public void run() {
lvitems.invalidateViews(); //invalidate old
CustomAdapter customAdapter=new CustomAdapter(context, names, images); // load new data
customAdapter.notifyDataSetChanged();// call notifydatasetChanged
}
});
If any mistake in this answer please correct my mistakes.