Please any one help how to sort images by name.Here am sharing my code.please any one help.
Here am showing images with grid and list .How to sort images by name in grid and list view.Here am using menu by selecting sort by name and sort by size.
// Main Activity
public class MainActivity extends ActionBarActivity {
public RelativeLayout mainLayout;
View gridView,listView;
CountryAdapterList customListAdapter;
CountryAdapter cutomArrayAdapter;
public int swithNo=0;
public String[] country_Names;
public RelativeLayout relativeLayout;
public int[] country_Images = {R.drawable.banglades, R.drawable.bangladesh,
R.drawable.brazi, R.drawable.brazil, R.drawable.chin,
R.drawable.china, R.drawable.indi, R.drawable.india,
R.drawable.indonesi, R.drawable.indonesia, R.drawable.japa,
R.drawable.japan, R.drawable.nigeri, R.drawable.nigeria,
R.drawable.pakista, R.drawable.pakistan, R.drawable.russi,
R.drawable.russia, R.drawable.unitedstate,
R.drawable.unitedstates };
public String[] country_Name_Sort = { "Bangladesh A", "Pakistan",
"Brazil A", "Brazil", "China A","Bangladesh", "China", "India A", "India",
"Indonesia A", "Russia","Indonesia", "Japan A", "Japan", "Nigeria A",
"Nigeria", "Pakistan A", "Russia A",
"UnitesStates A", "UnitesStates" };
public float[] country_Image_size = {1.36f , 1.36f, 4.12f, 4.12f, 1.47f,
1.47f, 1.79f, 1.79f, 0.299f, 0.299f, 1.50f, 1.50f, 0.285f, 0.285f,
1.85f, 1.85f, 0.330f, 0.330f, 3.42f, 3.42f };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
relativeLayout = new RelativeLayout(this);
customListAdapter = new CountryAdapterList(getApplicationContext(),
country_Name_Sort, country_Image_size, country_Images);
cutomArrayAdapter=new CountryAdapter(getApplicationContext(), country_Name_Sort, country_Image_size, country_Images);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
relativeLayout.setLayoutParams(rlp);
gridView = getLayoutInflater().inflate(R.layout.activity_deatails_grid,
null);
listView = getLayoutInflater().inflate(R.layout.activity_main_listview,
null);
setViewUpdate(swithNo);
((AdapterView<ListAdapter>) gridView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
((AdapterView<ListAdapter>) listView).setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),CountryDetailsScreen.class);
i.putExtra("Position", position);
i.putExtra("Country_Name", country_Name_Sort);
i.putExtra("Country_image", country_Images);
i.putExtra("Country_Image_size", country_Image_size);
startActivity(i);
}
});
}
private void sortAscending () {
List<String> sortedMonthsList = Arrays.asList(country_Name_Sort);
Collections.sort(sortedMonthsList);
country_Name_Sort = (String[]) sortedMonthsList.toArray();
}
#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);
menu.add(1, 1, 0, "Grid View");
menu.add(1, 2, 1, "List View");
menu.add(2, 3, 2, "Sort By Name");
menu.add(2, 4, 3, "Sort By Size");
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.
switch (item.getItemId()) {
case 1:
Log.d("SwithNo", "One");
swithNo=0;
setViewUpdate(swithNo);
break;
case 2:
Log.d("SwithNo", "Two");
swithNo=1;
setViewUpdate(swithNo);
break;
case 3:
Log.d("SwithNo", "Three");
sortAscending();
for(int i=0;i<country_Name_Sort.length;i++)
{
Log.e("Assending ", " "+country_Name_Sort[i]);
}
((ListView) listView).setAdapter(customListAdapter);
listView.invalidate();
setViewUpdate(swithNo);
break;
case 4 : Log.d("Switch", "Four");
}
return true;
}
public void setViewUpdate(int k)
{
((GridView) gridView).setAdapter(cutomArrayAdapter);
((ListView) listView).setAdapter(customListAdapter);
relativeLayout.removeAllViews();
if(k==0)
{
relativeLayout.addView(gridView);
}
else
{
relativeLayout.addView(listView);
}
setContentView(relativeLayout);
}
}
class Country {
int imageId;
String countryName;
Country(int imageId, String countyName) {
this.imageId = imageId;
this.countryName = countyName;
}
}
class CountryAdapter extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
CountryAdapter(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
list = new ArrayList<Country>();
/*Resources resource = context.getResources();
String[] country_Names = resource.getStringArray(R.array.coutry_names);*/
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageView);
country_Name = (TextView) v.findViewById(R.id.countryName);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
class CountryAdapterList extends BaseAdapter {
ArrayList<Country> list;
Context context;
String[] country_Name_Sort;
int[] country_Images;
CountryAdapterList(Context context,String[] country_Name_Sort,float[] country_Image_size,int[] country_Images) {
this.context = context;
this.country_Name_Sort=country_Name_Sort;
this.country_Images=country_Images;
list = new ArrayList<Country>();
for (int i = 0; i < country_Name_Sort.length; i++) {
Country country = new Country(country_Images[i], country_Name_Sort[i]);
list.add(country);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class ViewHolder {
ImageView county_Image;
TextView country_Name;
ViewHolder(View v) {
county_Image = (ImageView) v.findViewById(R.id.imageViewList);
country_Name = (TextView) v.findViewById(R.id.countryNameList);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View row = convertView;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.single_item_listview, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
}
Country cntry = list.get(position);
viewHolder.county_Image.setImageResource(cntry.imageId);
viewHolder.country_Name.setText(cntry.countryName);
return row;
}
}
you should implement Java's Comparator.
ListView list;
//fill list here.
Collections.sort(list, new Comparator<String>() {
public int compare(final String a, final String b) {
return a.compareTo(b));
}
});
you can compare objects too, using their properties.
public int compare(final LatLong a, final LatLong b) {
return a.latitude.compareTo(b.latitude));
}
By using array sorting you can sort your image names in your application
//String array
String[] strNames = new String[]{"John", "Alex", "Chris", "Williams", "Mark", "Bob"};
sort String array using sort method
Arrays.sort(strNames);
Output of above given Java Sort String Array example would be
String array sorted (case sensitive)
Alex
Bob
Chris
John
Mark
Williams
In the same way, before setting your array data to your lisyt view you can sort it by using Arrays.sort(strNames);
hope it helps
Related
I'm looking to some way for sort my items inside my listview. Which is a multi values Listview with 3 items for each row. I use a Custom ListViewAdapter to achieve this, but they are sorted in order of introduction inside the ArraysList. Something like:
1-2-3-4-5-6....
I want to inverse this order, having in top of my Listview the last item introduced:
6-5-4-3-2-1....
Here is my Custom ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
static class ViewHolder {
TextView number;
TextView elapsedTime;
TextView totalTime;
}
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public ArrayList<HashMap<String, String>> list;
Activity activity;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=activity.getLayoutInflater();
final ViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.timer_row, null);
viewHolder = new ViewHolder();
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.elapsedTime = (TextView) convertView.findViewById(R.id.elapsed_time);
viewHolder.totalTime =(TextView) convertView.findViewById(R.id.total_time);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map=list.get(position);
viewHolder.number.setText(map.get(FIRST_COLUMN));
viewHolder.elapsedTime.setText(map.get(SECOND_COLUMN));
viewHolder.totalTime.setText(map.get(THIRD_COLUMN));
return convertView;
}
}
And here is how I call it in my activity:
//ListView Adapter
mListviewLayout = (RelativeLayout)v.findViewById(R.id.listview_times_layout);
mTimesListview = (ListView)v.findViewById(R.id.times_listview);
mTimesArrayList = new ArrayList<HashMap<String,String>>();
mListViewAdapter= new ListViewAdapter(mActivity, mTimesArrayList);
mTimesListview.setAdapter(mListViewAdapter);
Finally, here is how I introduce items inside the Hashmap:
btnNextCicle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isTimerPaused()) {
onTimerStop();
} else {
mListviewLayout.setVisibility(View.VISIBLE);
mCiclesCounter++;
HashMap<String, String> newEntry = new HashMap<String, String>();
newEntry.put(ListViewAdapter.FIRST_COLUMN, "#" + mCiclesCounter);
newEntry.put(ListViewAdapter.SECOND_COLUMN, Util.getTimeForTimer(mElapsedCicleTime));
newEntry.put(ListViewAdapter.THIRD_COLUMN, Util.getTimeForTimer(mTimeInMilliseconds));
mCicleStartTime = SystemClock.elapsedRealtime();
mTimesArrayList.add(newEntry);
}
}
});
You can subclass HashMap<String, Sting> and make it implements Comparable. Then you can use Arrays.sort(yourComparable) to sort the array the way you want.
I am trying to create an android application using a database from Parse.com. I am using a custom adapter to create a listview. I don't find any errors with the code and yet the listeview is not showing up. Nothing there in the logcat as well. Just the listview does not show up.
lv = (ListView)findViewById(R.id.listView);
mProgress = (ProgressBar)findViewById(R.id.check_progress);
mProgress.setVisibility(View.VISIBLE);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Sellers");
query.orderByAscending("Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
studentsList = new ArrayList<Sellers>();
for (ParseObject ob : parseObjects) {
s = new Sellers();
s.setName(ob.getString("Name").toString());
s.setAddress1(ob.getString("Address1").toString());
s.setAddress2(ob.getString("Address2").toString());
s.setShopName(ob.getString("ShopName").toString());
s.setEmail(ob.getString("Email").toString());
s.setPhone(ob.getString("Phone").toString());
s.setZipcode(ob.getString("Zipcode").toString());
studentsList.add(s);
}
adapter = new ListviewAdapter(CheckStatus.this, studentsList);
lv.setAdapter(adapter);
mProgress.setVisibility(View.GONE);
} else {
mProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is the activity where I am invoking the listview.
public class ListviewAdapter extends BaseAdapter{
private final static String TAG = ListviewAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Sellers> sellers;
int layout;
public ListviewAdapter(Context activity, List<Sellers> sellers) {
this.activity = activity;
this.sellers = sellers;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView name ;
TextView shop ;
TextView address1 ;
TextView address2;
TextView phone;
TextView email;
RelativeLayout rl;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.seller_name);
holder.shop = (TextView)v.findViewById(R.id.shop_name);
holder.address1 = (TextView)v.findViewById(R.id.address1);
holder.address2 = (TextView)v.findViewById(R.id.address2);
holder.phone = (TextView)v.findViewById(R.id.phone);
holder.email = (TextView)v.findViewById(R.id.emailID);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Sellers s = sellers.get(position);
// String a = s.Name;
// Log.d(TAG, a);
holder.name.setText(s.getName());
holder.shop.setText(s.getShopName());
holder.address1.setText(s.getAddress1());
holder.address2.setText(s.getAddress2());
holder.phone.setText(s.getPhone());
holder.email.setText(s.getEmail());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is the custom adapter. There are no null pointer exceptions showing up in the logcat. I can't determine why the listview is not getting populated.
Try this;
#Override
public int getCount() {
return sellers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position:
}
You have to implement your code on getCount() by return number of item listview will be created.
Text View in my fragment_main should be showing the String but instead it is showing the package name.
In my Main Activity Class,
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
ListView main_list;
ArrayAdapter<Cinema> adapter;
ArrayList<Cinema> ItemList = new ArrayList<Cinema>();
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v("Check", "1");
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ItemList.addAll(initialization());
ListView main_list = (ListView) rootView.findViewById(R.id.mainlist);
adapter = new ListAdapater(rootView.getContext(), ItemList);
main_list.setAdapter(adapter);
main_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
Intent i = new Intent(rootView.getContext(), CinemaDetails.class);
Bundle b = new Bundle();
b.putParcelable("Cinema", ItemList.get(position));
i.putExtra("Bundle", b);
startActivity(i);
}
});
return rootView;
}
public ArrayList<Cinema> initialization () {
ArrayList<Cinema> tempItemList = new ArrayList<Cinema>();
ArrayList<Movie> movielistone = new ArrayList<Movie>();
Movie movieone = new Movie(101, "MovieOne", "null", 5, "nULL");
Movie movietwo = new Movie(102, "Movietwo", "null", 3, "nuLL");
movielistone.add(movieone);
movielistone.add(movietwo);
Cinema cinemaone = new Cinema(01, "test", "ygn", 55555, movielistone, 3);
Cinema cinematwo = new Cinema(02, "test2", "ygn", 554555, movielistone, 3);
tempItemList.add(cinemaone);
tempItemList.add(cinematwo);
return tempItemList;
}
}
I use Array Adapter and the code for it is
public class ListAdapater extends ArrayAdapter<Cinema> {
private LayoutInflater inflater;
public ListAdapater(Context context, List<Cinema> itemList) {
super(context, R.layout.row, R.id.txt_cinemaname, itemList );
inflater = LayoutInflater.from(context) ;
// TODO Auto-generated constructor stub
}
#Override
public Cinema getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Cinema cinema = this.getItem(position);
TextView txt_name;
TextView txt_movie;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row, null);
txt_name = (TextView) convertView.findViewById(R.id.txt_cinemaname);
txt_movie = (TextView) convertView.findViewById(R.id.txt_moviesonshow);
convertView.setTag(new ItemViewHolder(txt_name, txt_movie));
} else {
ItemViewHolder viewHolder = (ItemViewHolder) convertView.getTag();
txt_name = viewHolder.getName();
txt_movie = viewHolder.getMoviename();
}
txt_name.setText("test");
Log.v("name", txt_name.getText().toString());
txt_movie.setText("");
for (Movie movie : cinema.getMovieonshow()) {
String temp = txt_movie.getText().toString();
txt_movie.setText(temp + movie.getName() + "\n");
}
return super.getView(position, convertView, parent);
}
public static class ItemViewHolder {
private TextView name;
private TextView moviename;
public ItemViewHolder() {}
public ItemViewHolder(TextView name, TextView moviename) {
super();
this.name = name;
this.moviename = moviename;
}
public TextView getName() {
return name;
}
public void setName(TextView name) {
this.name = name;
}
public TextView getMoviename() {
return moviename;
}
public void setMoviename(TextView moviename) {
this.moviename = moviename;
}
}}
I have never had this problem before. I tied to log the Text from the TextView and it shows "test" just like I put it there. Any suggestion? Thanks for reading.
The problem is
return super.getView(position, convertView, parent);
ArrayAdapter, by default, fills the TextView view at the specified resource id (in this case R.id.txt_cinemaname) with the result of item.ToString() (where item is the object at the specified position in the backing array).
Since Cinema does not implement toString(), the default text is produced.
Using return convertView; should fix it.
I can't quite figure out exactly, but why are you passing in R.id.txt_cinemaname in your ListAdapter constructor? The problem looks like you are passing in an Object (that string "com.example... is a pointer to an object, I'm guessing a TextView) rather than a string.
Also, shouldn't you be returning convertView rather than super.getView(position, convertView, parent); in your getView() method?
When end items in a ListView, i upload new, and after update adapter:
ListView lvMain = (ListView) findViewById(R.id.list);
boxAdapter = null;
boxAdapter = new BoxAdapter(this, products);
lvMain.setAdapter(boxAdapter);
But after this, elements are loaded but the scroll position the top. Ie the position of ListView is lost, and look again at the beginning of all
How fix it?
BoxAdapter code:
public class BoxAdapter extends BaseAdapter {
private final Context ctx;
private final LayoutInflater lInflater;
private final ArrayList<ItemInfo> objects;
private final int loadCount = 10;
private int count = 10;
private String name, desc;
BoxAdapter(Context context, ArrayList<ItemInfo> products) {
this.ctx = context;
this.objects = products;
this.lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
//return objects.size();
return this.count;
}
// элемент по позиции
#Override
public ItemInfo getItem(int position) {
return objects.get(position);
}
// id по позиции
#Override
public long getItemId(int position) {
return position;
}
public void loadAdditionalItems() {
this.count += this.loadCount;
if (this.count > this.objects.size()) {
this.count = this.objects.size();
}
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = lInflater.inflate(R.layout.item, parent, false);
ItemInfo p = getItem(position);
TextView desc_id = (TextView) view.findViewById(R.id.desc);
if (p.username.contains("null"))
{
name = "Автор: Неизвестен";
}
else
{
name = "Автор: " + p.username;
}
if(!p.description.contains("null"))
{
desc = p.description.replaceAll("<br />", "");
desc = desc.replaceAll(""", "");
}
else
{
desc = "";
desc_id.setVisibility(View.GONE);
}
((TextView) view.findViewById(R.id.name)).setText(name);
((TextView) view.findViewById(R.id.desc)).setText(desc);
return view;
}
}
P.S setOnScrollListener code:
lvMain.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
ListView lvMain = (ListView) findViewById(R.id.list);
if(firstVisibleItem + visibleItemCount >= totalItemCount) {
boxAdapter.loadAdditionalItems();
loading = false;
}
if (!loading && (lvMain.getLastVisiblePosition() + 10) >= (60))
{
new LoadLastestPost().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
The best solution would be to create a setProducts method in your boxAdapter and then just call boxAdapter.notifyDataSetChanged(). For example:
boxAdapter.setProducts(products);
boxAdapter.notifyDataSetChanged();
If you implement this method, there is no need to call lvMain.setAdapter(boxAdapter) more than once.
To add the setProducts() method to your adapter:
public BoxAdapter extends BaseAdapter {
Context mContext;
ArrayList<ItemInfo> objects;
public BoxAdapter(Context context, ArrayList<ItemInfo> products) {
mContext = context;
objects = products;
}
public View getView(int position, View convertView, ViewGroup parent) {
// inflate and adjust view
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public void setProducts(ArrayList<ItemInfo> newData) {
objects = newData;
}
}
Also, I wouldn't use a count variable. I would just use the size method in the ArrayList. I would remove count altogether.
Below is the class where i am not able to get the resource of the image id. I am trying to fetch all the data from the web service. Here i have posted all the classes from where the images are fetched.I have all the images showing it in the gridView. I am not facing problem in that, however when I click on the image of the gridview it shows me the just the xml file which I have called. I guess I am doing wrong somewhere calling the id here in the FullImageAcitivity file.
DefaultGridView.java
public class DefaultGridView extends Activity {
//int position;
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView=(GridView)findViewById(R.id.grid_view);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
gridView.setAdapter(new ImageAdapter());
}
public class ImageAdapter extends BaseAdapter {
LayoutInflater inflater = LayoutInflater.from(context);
public ImageAdapter() {
// TODO Auto-generated constructor stub
imageLoader.init(ImageLoaderConfiguration.createDefault(DefaultGridView.this));
}
#Override
public int getCount() {
return Global.getPhotos_list().size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
Log.d("position", position+"");
imageLoader.displayImage(Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name"), picture , options,null,context);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("idkey", position); // pass the id
startActivity(i);
}
});
return v;
}
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setas;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setas = (Button) findViewById(R.id.setas);
download = (Button)findViewById(R.id.download);
// get intent data
final Intent i = getIntent();
// Selected image id
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
int id = getIntent().getIntExtra("idkey",-1); //get id
imageView.setImageResource(id);
setas.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.full_image_view);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
List<Item> items;
public ImageAdapter(Context context,List<Item> items) {
inflater = LayoutInflater.from(context);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawable;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
return v;
}
}
Items.java
public class Item {
String name;
int drawable;
public int getDrawable() {
return drawable;
}
public void setDrawable(int drawable) {
this.drawable = drawable;
}
public Item(String name, int id)
{
this.name= name;
this.drawable = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In gridView item click
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
Then in FullImageActivity
int id = getIntent().getIntExtra("idkey"); //get id
imageview.setImageResource(id); // set the drawable to imageview
You can move the below to onCreate of DefaultFridView
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
}
});
Also you need to have the List in DefaultGridView
List<Item> items = new ArrayList<Item>();
Then
items.add(new Item("One", R.drawable.abstact_one));
items.add(new Item("Two", R.drawable.abstract_three));
items.add(new Item("Three", R.drawable.image_two));
items.add(new Item("Four", R.drawable.image_four));
items.add(new Item("Five", R.drawable.image_five));
items.add(new Item("Six", R.drawable.image_nine));
items.add(new Item("Seven", R.drawable.image_ten));
Then
gridView.setAdapter(new ImageAdapter(),items);
Also i don't understand having the ImageAdapter as separate and as a inner class. WHy do you need both
Try this example my be it is usefull
Grieview Display Full Image