Automatically load more items in ListView (XML parsing) - android

I've done XML parsing to ListView and right now do i need to implement load-more feature. I know how to indicat, when the user scrolled to the bottom and how to limit the number of items in a ListView. But is there any way how to show more items when the user scrolls to the end of the list?
Here is my adapter class:
public class ClubsAdapter extends ArrayAdapter<LeagueClub> {
ImageLoader imageLoader;
DisplayImageOptions options;
Context mContext;
public static List<LeagueClub> mClubs;
#SuppressWarnings("deprecation")
public ClubsAdapter(Context mContext, int textViewResourceId, List<LeagueClub> clubs) {
super(mContext, textViewResourceId, clubs);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
mClubs=clubs;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("PremierLeague", "getView pos = " + pos);
if(null == row){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
final ImageView clubLogo = (ImageView)row.findViewById(R.id.clubLogo);
TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView aboutTxt = (TextView)row.findViewById(R.id.aboutTxt);
TextView stadiumTxt = (TextView)row.findViewById(R.id.stadiumTxt);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
indicator.setVisibility(View.VISIBLE);
clubLogo.setVisibility(View.INVISIBLE);
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
clubLogo.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View view, FailReason arg2) {
indicator.setVisibility(View.INVISIBLE);
ImageView imageView = (ImageView) view.findViewById(R.id.clubLogo);
imageView.setVisibility(View.VISIBLE);
}
};
imageLoader.displayImage(getItem(pos).getLogo(), clubLogo,options, listener);
nameTxt.setText(getItem(pos).getName());
aboutTxt.setText(getItem(pos).getAbout());
stadiumTxt.setText(getItem(pos).getStadium());
return row;
}
public int getCount() {
return mClubs.size(); //If i set return 10; it limits items to max 10
}
}
And here is my Fragment:
public class Fragment2 extends Fragment {
static PullToRefreshListView mListView;
static ClubsAdapter mAdapter;
Context mContext;
ProgressBar mProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_2, container, false);
mListView = (PullToRefreshListView) rootView.findViewById(R.id.pull_to_refresh_listview1);
mProgress = (ProgressBar) rootView.findViewById(R.id.loading_clubs);
mProgress.setVisibility(View.VISIBLE);
ClubsDownloadTask task = new ClubsDownloadTask();
task.execute();
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
mProgress.setVisibility(View.INVISIBLE);
ClubsDownloadTask task = new ClubsDownloadTask();
task.execute();
}
});
return rootView;
}
private class ClubsDownloadTask extends AsyncTask<Void, Void, Void>{
private ClubsAdapter mAdapter;
#Override
protected Void doInBackground(Void... arg0) {
try {
Downloader.DownloadFromUrl("http://dl.dropboxusercontent.com/s/h2qc41k2yy3c1ir/clubs.xml", getActivity().openFileOutput("clubs.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
}
protected void onPostExecute(Void result){
mListView.onRefreshComplete();
mProgress.setVisibility(View.INVISIBLE);
mAdapter = new ClubsAdapter(getActivity(), -1 , ClubsXmlPullParser.getItemsFromFile(getActivity()));
mListView.setAdapter(mAdapter);
if(ClubsAdapter.mClubs != null){
mAdapter.clear();
for (int i = 0; i < ClubsAdapter.mClubs.size(); i++) {
mAdapter.add(ClubsAdapter.mClubs.get(i));
}
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if(mListView.getRefreshableView().getCount()!=0&&mListView.getRefreshableView().getCount()>0&&mAdapter.getCount()!=0){
if (mListView.getRefreshableView().getLastVisiblePosition() == mListView.getRefreshableView().getAdapter().getCount() - 1
&& mListView.getRefreshableView()
.getChildAt(mListView.getRefreshableView().getChildCount() - 1)
.getBottom() <= mListView.getRefreshableView().getHeight()) {
//Here do I need to load more items
}
}
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getActivity().getCurrentFocus();
if(currentFocus != null) {
currentFocus.clearFocus();
}
}
}
});
}
}
}
}
Thanks for any suggestion!

You can use this adapter https://github.com/commonsguy/cwac-endless
With this adapter, when user scroll to end of list, it will call a function which you can implement to load more items.

Related

Android - Fullscreen Image on click

I have a GridView with some images that when its clicked show in full screen.
But when I'm clicking image the app crash for Target must not be null :(
My Activity:
public class ArenaActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arena);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GridView gv = (GridView) findViewById(R.id.grid_view);
gv.setAdapter(new ArenaGridViewAdapter(this));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i = new Intent(ArenaActivity.this, ArenaViewActivity.class);
i.putExtra("position", position);
startActivity(i);
}
});
}
}
My Adapter:
public class ArenaGridViewAdapter extends BaseAdapter {
private Context context = null;
public ArenaGridViewAdapter(Context context) {
this.context = context;
}
public int[] arenaImgs = {
R.drawable.ic_arena_01,
R.drawable.ic_arena_02,
R.drawable.ic_arena_03,
R.drawable.ic_arena_04,
R.drawable.ic_arena_05,
R.drawable.ic_arena_06
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
SquaredImageView view = (SquaredImageView) convertView;
if (view == null) {
view = new SquaredImageView(context);
view.setScaleType(CENTER_CROP);
}
Picasso.with(this.context) //
.load(arenaImgs[position]) //
.placeholder(R.drawable.ic_placeholder) //
.error(R.drawable.ic_error) //
.fit() //
.into(view);
return view;
}
#Override
public int getCount() {
return arenaImgs.length;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
}
And Finally the Fullscreen:
public class ArenaViewActivity extends ActionBarActivity {
public int[] arenaImgs = {
R.drawable.ic_arena_01,
R.drawable.ic_arena_02,
R.drawable.ic_arena_03,
R.drawable.ic_arena_04,
R.drawable.ic_arena_05,
R.drawable.ic_arena_06
};
private ShareActionProvider mShareActionProvider;
private int urlshare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arena);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
int position = i.getExtras().getInt("position");
this.urlshare = position;
ImageView iv = (ImageView) findViewById(R.id.arena_full_view);
Picasso.with(getApplicationContext())
.load(arenaImgs[position])
.fit()
.centerCrop()
.into(iv);
}
}
The error log says that the Target null is in: Picasso.with(getApplicationContext())
I solved the problem. Was a error in layout of fullscreen.
Changed to: setContentView(R.layout.arena_full_view);
Thanks everyone.

getting image id from ImageAdapter

I'am new to android and I've a project of making a grid view of images and onclick on image it shows it , thats the ImageAdapter class code
public class ImageAdapter extends BaseAdapter{
private static LayoutInflater inflater = null;
private Activity activity;
private String mode = "";
int[] images=null ;
public ImageAdapter(Activity act, String mode , int[] images){
inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = act;
this.mode = mode;
this.images= images ;
}
public ImageView getImage(int pos)
{
ImageView im = (ImageView) getItem(pos);
return im ;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return new Integer(images[position]);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if(mode.equalsIgnoreCase("grid")){
if (view == null) {
view = inflater.inflate(R.layout.each_image1, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
} else if(mode.equalsIgnoreCase("gallery")){
if (view == null) {
view = inflater.inflate(R.layout.each_image_gallery, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
}
return view;
}
}
thats my grid activity
public class GridActivity extends Activity {
GridView grid = null;
public static ImageAdapter adapter1 ;
public static ImageAdapter adapter2 ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
adapter1= new ImageAdapter(GridActivity.this, "grid" , Images.images1);
adapter2 = new ImageAdapter(GridActivity.this, "grid" , Images.images2);
Intent i = this.getIntent();
if (i!=null)
{
String unique = i.getExtras().getString("Unique");
if (unique.equals("islam"))
{
Toast.makeText(GridActivity.this, "islam", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter1);
}
if (unique.equals("natural"))
{
Toast.makeText(GridActivity.this, "nat", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter2);
}
}
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
}
}
and this is the activity where it supposes to show any clicked on image
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getExtras().getInt("selectedIntex");
// ImageAdapter adapter = new ImageAdapter(imgPrevActivity.this, "image prev", null);
long Id= GridActivity.adapter1.getItemId(pos);
im.setImageResource((int) Id);
}
}
i've tried to get the position of image clicked on from the grid
then getting the Id from the position
and setting the image view to that ID
but it doesnt work !!
thats where the images are put in arrays
public class Images {
public static int[] images1 = {
R.drawable.buds, R.drawable.cherry_34,
R.drawable.clouds_2, R.drawable.coffee_beans_2,
R.drawable.death_valley_sand_dunes
};
public static int[] images2= {
R.drawable.morning_glory_pool,
R.drawable.pink_flowers, R.drawable.sun_flower,
R.drawable.sunrise_3, R.drawable.yellow_rose_3,
};
}
You have to pass your image resource id with intent. The list item id of adapter is useless because you have new Activity on the screen.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", grid.getAdapter().getItem(pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
and change your code in your ImgPreviewActivity:
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getIntExtra("selectedIntex", 0);
im.setImageResource(pos);
}
}
I think it should work

Search clears all object in ListView

I've got a problem with my search filter. When i start typing, all objects are gone and no search is performed. Only after refresh are they back. When I try to proof via Toast, that if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) in adapter is called, no toast views.
Do you have any idea, where the problem could be? Thanks in advance!
My MainActivity class with EditText listener
public class MainActivity extends ActionBarActivity{
private ListView mListView;
private AnimalAdapter mAdapter;
ProgressBar mProgressBar;
EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add your initialization code here
Parse.initialize(this, "code", "code");
ParseObject.registerSubclass(Animal.class);
ParseAnalytics.trackAppOpened(getIntent());
View header = getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView = (ListView) findViewById(R.id.animal_list);
mListView.setVisibility(View.INVISIBLE);
mListView.addHeaderView(header);
mProgressBar = (ProgressBar) findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
}
public void updateData(){
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
query.orderByAscending("animal");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar.setVisibility(View.INVISIBLE);
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Intent refreshIntent = new Intent(MainActivity.this, MainActivity.class);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(refreshIntent);
overridePendingTransition(0,0);
return true;
}
return super.onOptionsItemSelected(item);
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
updateData();
return null;
}
#Override
protected void onPostExecute(Void result) {
mListView = (ListView) findViewById(R.id.animal_list);
// Pass the results into ListViewAdapter.java
mAdapter = new AnimalAdapter(MainActivity.this, new ArrayList<Animal>());
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
mListView.setTextFilterEnabled(true);
mEditText = (EditText) findViewById(R.id.search_animal);
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
mListView.setVisibility(View.VISIBLE);
String text = mEditText.getText().toString()
.toLowerCase(Locale.getDefault());
mAdapter.filter(text);
}
});
}
}
}
My Adapter class with filter method
public class AnimalAdapter extends ArrayAdapter<Animal> implements Filterable{
private Context mContext;
private List<Animal> mAnimals;
ImageLoader imageLoader;
ArrayList<Animal> array;
DisplayImageOptions options;
Activity activity;
private Filter animalFilter;
private List<Animal> animaly;
#SuppressWarnings("deprecation")
public AnimalAdapter(Context context, List<Animal> objects) {
super(context, R.layout.animal_row_item, objects);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
this.mContext = context;
this.mAnimals = objects;
this.animaly = objects;
}
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.animal_row_item, null);
}
final Animal animal = mAnimals.get(position);
TextView animalView = (TextView) convertView.findViewById(R.id.animal_text);
TextView areaView = (TextView) convertView.findViewById(R.id.area_text);
final ImageView animalPic = (ImageView)convertView.findViewById(R.id.animal_pic);
final ProgressBar indicator = (ProgressBar)convertView.findViewById(R.id.progress);
indicator.setVisibility(View.VISIBLE);
animalPic.setVisibility(View.INVISIBLE);
//Setup a listener we can use to switch from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
animalPic.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View view, FailReason arg2) {
}
};
imageLoader.displayImage(getItem(position).getImgUrl(), animalPic,options, listener);
animalView.setText(animal.getAnimal());
areaView.setText(animal.getArea());
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MoreActivity.class);
intent.putExtra("about", animal.getAbout());
intent.putExtra("animal", animal.getAnimal());
intent.putExtra("imgUrl", animal.getImgUrl());
getContext().startActivity(intent);
}
});
return convertView;
}
public int getCount() {}
return mAnimals.size();
public void filter(String text) {
if (text.length() == 0) {
mAnimals.addAll(animaly);
Toast.makeText(getContext(), "text 0", Toast.LENGTH_SHORT).show();
} else {
mAnimals.clear();
for (Animal wp : animaly) {
if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) {
Toast.makeText(getContext(), "contains", Toast.LENGTH_SHORT).show();
mAnimals.add(wp);
}
}}
notifyDataSetChanged();
}
}
I just solved this with doing it a little bit different way. For great tutorial check/codes:
For tutorial check this.
For the whole codes check this.
Good luck and have a great day!

notifyDataSetChanged() doesn't work with my adapter for gridview

I have a GridView and adapter for GridView (BasketAdapter extends BaseAdapter).
I load data in GridView from sharedpref file.
After I change data, I resave sharedpref file with data and call notifyDataSetChanged().
But notifyDataSetChanged() doesn't work unfortunately.
If I create new adapter and set it to my GridView, it works.
Can anyone help me with this issue?
Here is my code:
public class FragmentBasket extends SherlockFragment {
// my gridview
GridView gvCatalogAllStoneBasket;
// list of data from shared pref
ArrayList<CatalogItem> catalogItemBasket = new ArrayList<CatalogItem>();
ActionMode mode;
public static CatalogItem catalogItem;
// id variables for actionmode's actions
static final int ID_DELETE = 1;
static final int ID_EDIT = 2;
// shared pref id string
static String SHARED_PREFS_FILE = "basket";
// my adapter
BasketAdapter adapter = null;
public FragmentBasket() {
}
#Override
public void onStart() {
super.onStart();
// loading saved data from file
new GetCatalogAllStoneBasket().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.EDIT_ITEM_BASKET");
IntentFilter intentFilterDelete = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterEdit);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid, container, false);
gvCatalogAllStoneBasket = (GridView)view.findViewById(R.id.gvCatalogAllStoneBasket);
gvCatalogAllStoneBasket.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// start action mode and send id of clicked item
mode = getSherlockActivity().startActionMode(new ActionModeOfBasket(String.valueOf(view.getTag())));
return false;
}
});
return view;
}
private final class ActionModeOfBasket implements ActionMode.Callback
{
String itemId;
public ActionModeOfBasket(String itemId) {
// get id from clicked item
this.itemId = itemId;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0, ID_EDIT, 0, "Edit")
.setIcon(android.R.drawable.ic_menu_edit)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
menu.add(0, ID_DELETE, 1, "Delete")
.setIcon(android.R.drawable.ic_menu_delete)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// get file
SharedPreferences sPref = getActivity().getSharedPreferences(SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
// open file for reading, writing
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
switch (item.getItemId())
{
// if clicked del button
case ID_DELETE:
// delete item
bHelper.DelItem(itemId);
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
// if clicked edit button
case ID_EDIT:
// edit item
bHelper.EditItem(itemId, getFragmentManager());
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
class GetCatalogAllStoneBasket extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
SharedPreferences sPref = getActivity().getSharedPreferences(FragmentCatalogStonePosition.SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
try {
if(sPref.getString(FragmentCatalogStonePosition.TASK, null) != null)
{
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
catalogItemBasket = bHelper.GetAllItems();
}
} catch (Exception e) {
Log.d(MainActivity.tag, e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(adapter);
}
}
class Receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().toString() == "com.example.myproject.ADD_ITEM_BASKET")
{
}
else if(intent.getAction().toString() == "com.example.myproject.EDIT_ITEM_BASKET")
{
// this code doesn't work (((
adapter.notifyDataSetChanged();
// this one successfully works
BasketAdapter bAdapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(bAdapter);
}
else if(intent.getAction().toString() == "com.example.myproject.DELETE_ITEM_BASKET")
{
}
}
}
class BasketAdapter extends BaseAdapter
{
Context context = null;
ArrayList<CatalogItem> data = null;
public BasketAdapter(Context context, ArrayList<CatalogItem> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
public CatalogItem getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
}
return view;
}
}
}
Your convertView isn't null in case the View is recycled, so your getView() should be something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
}
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
return view;
}
and since you have your own ArrayList inside your adapter, you have to update this one as well. Just add this method to your BasketAdapter:
public void changeModelList(List<CatalogItem> models) {
this.data = models;
notifyDataSetChanged();
}
and use it instead of notifyDataSetChanged().
it's not tested, but i think this is your problem.

Progress dialog not showing in button click event in listview

I have a button in each list item of list view. In that button click event i have some codes to run. In click event im showing the progress dialog before the code runs. but its not getting shown. After all the codes in click event completes in the end progress dialog gets shown. Plz help me.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
TheListViewM = (ListView) findViewById(R.id.lvItems);
ImageAdapter anImageAdapterM =new ImageAdapter(this);
TheListViewM.setAdapter(anImageAdapterM);
}
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
if (ConvertViewP == null) {
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
}
TextView textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
textView1.setText("asdfg");
final Spinner spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spQuantity.setAdapter(QuantityAdapter1);
Button btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
Try this one.
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
class ViewHolder {
Button btn1;
TextView textView1;
Spinner spQuantity;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
ViewHolder holder;
if (ConvertViewP == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
holder.textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
holder.spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
holder.btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
ConvertViewP.setTag(holder);
}
else{
holder = (ViewHolder) ConvertViewP.getTag();
}
holder.textView1.setText("asdfg");
holder.spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spQuantity.setAdapter(QuantityAdapter1);
holder.btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
}

Categories

Resources