I have developed and launched an Android application. It works fine on my Android phone, but it crashes on several devices.
*BugSense gives me the following error:*
0 java.lang.NullPointerException
1 at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
2 at android.widget.ArrayAdapter.(ArrayAdapter.java:128)
3 **at com.challenger.app.ChallengeAdapter.(ChallengeAdapter.java:27)**
4 at com.challenger.app.AllChallenges.fitChallenges(AllChallenges.java:142)
5 at com.challenger.app.AllChallenges$1.onSuccess(AllChallenges.java:108)
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class AllChallenges extends Fragment {
Button loginButton;
ListView listView2, listView1;
TextView textView;
int category = 0;
View view;
List<Challenge> challenge_data;
public AllChallenges(int cat) {
category = cat;
}
public AllChallenges() {
// TODO Auto-generated constructor stub
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.allchallenges, container, false);
if(getActivity()!=null){
load();
}
return view;
}
public void load() {
loadOld();
if (!AppSettings.refreshed[category + 1]) {
update();
}
}
public void loadOld() {
Log.d("Challenge", "Updating " + category);
JSONArray a = AppSettings.loadChallenges(category, getActivity());
if (a != null) {
fitChallenges(makeArray(a));
}
}
public void update() {
Log.d("Challenge", "getChallenges/" + category);
RequestParams a = new RequestParams();
if (AppSettings.logged) {
a.put("fb_id", AppSettings.facebookId);
a.put("fb_authkey", AppSettings.facebookAuthToken);
}
NetworkClient.receiveJSON("getChallenges/" + category, a,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray chalList) {
Log.d("Challenge", "Downloaded " + category);
AppSettings.saveChallenges(category, chalList,
getActivity());
fitChallenges(makeArray(chalList));
AppSettings.refreshed[category + 1] = true;
}
});
}
public Challenge[] makeArray(JSONArray list) {
challenge_data = new ArrayList<Challenge>();
try {
for (int i = 0; i < list.length(); i++) {
JSONObject chal = (JSONObject) list.get(i);
String[] arr = {};
if (chal.has("friends"))
arr = JSONArrToArr(chal.getJSONArray("friends"));
Log.e("Boolean", chal.getString("active"));
challenge_data.add(new Challenge(chal.getInt("id"), chal
.getString("title"), chal.getInt("category"), chal
.getInt("taken_by"), arr, chal.getBoolean("active"),
chal.getString("text"), chal.getInt("streak"), chal
.getInt("percentage")));
}
return challenge_data.toArray(new Challenge[challenge_data.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void fitChallenges(Challenge[] chalArray) {
**ChallengeAdapter adapter = new ChallengeAdapter(getActivity(),
R.layout.list_row, chalArray);** //
listView1 = (ListView) view.findViewById(R.id.listView1);
listView1.setAdapter(adapter);
OnItemClickListener listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("listener", "am ID" + id + "position " + position);
int n = (int) id;
String title = challenge_data.get(n).toStringArray()[1];
Log.i("listener", "am ID" + id + "position " + position
+ " title " + title);
int people = challenge_data.get(n).peopleInt;
String category = challenge_data.get(n).toStringArray()[0];
String description = challenge_data.get(n).toStringArray()[5];
int streak = challenge_data.get(n).streak;
int percentage = challenge_data.get(n).percentage;
int chal_id = challenge_data.get(n).id;
boolean active = challenge_data.get(n).active;
((AllChallengesPager) getActivity()).showDetailed(chal_id,
title, "" + people, category, active, description, ""
+ streak, "" + percentage);
}
};
listView1.setOnItemClickListener(listener);
}
public String[] JSONArrToArr(JSONArray arr) {
String[] newArr = {};
try {
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
list.add(arr.getString(i));
}
newArr = list.toArray(new String[list.size()]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newArr;
}}
public class ChallengeAdapter extends ArrayAdapter<Challenge> {
Context context;
int layoutResourceId;
Challenge data[] = null;
Typeface a;
public ChallengeAdapter(Context context, int layoutResourceId,
Challenge[] data) {
**super(context, layoutResourceId, data);** //in this line code crashes
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
a = Typeface.createFromAsset(context.getAssets(),
"fonts/roboto_condensed.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChallengeHolder holder = null;
Challenge challenge = data[position];
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChallengeHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.list_image);
holder.txtTitle = (TextView) row.findViewById(R.id.challenge);
holder.txtPeople = (TextView) row.findViewById(R.id.peopleNumber);
holder.friendThumbs = (LinearLayout) row
.findViewById(R.id.friendThumbs);
row.setTag(holder);
} else {
holder = (ChallengeHolder) row.getTag();
}
holder.friendThumbs.removeAllViews();
for (int i = 0; i < challenge.friendIds.length; i++) {
holder.friendThumbs.addView(createIcon(challenge.friendIds[i],
context));
}
holder.txtTitle.setText(challenge.title);
holder.txtTitle.setTypeface(a);
holder.imgIcon.setImageResource(challenge.icon);
holder.txtPeople.setText(challenge.peopleString);
return row;
}
static class ChallengeHolder {
public LinearLayout friendThumbs;
ImageView imgIcon;
TextView txtTitle;
TextView txtPeople;
}
public ImageView createIcon(String friendID, Context cont) {
ImageView icon = new ImageView(context);
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
(int) cont.getResources().getDimension(R.dimen.fbIconSize),
(int) cont.getResources().getDimension(R.dimen.fbIconSize));
par.setMargins(0, 0, 15, 0);
icon.setLayoutParams(par);
Log.e("ID " + friendID, "log");
final String myurl = AppSettings.profilePictureUrl(friendID);
icon.setImageResource(R.drawable.default_fb_icon_small);
((MyApplication) ((Activity) context).getApplication())
.loadImageSimple(myurl, icon);
return icon;
}
}
I guess that the cause of this problem is context equal to null got from the method getActivity, but don't know how to deal with this problem. Could anyone explain how to solve the problem?
I think onActivityCreated method override and implement for this code, and its working fine may be...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity()!=null){
load();
}
}
And Fragment lifecyle must read for this doc Documentation
Most likely your Fragment is detached from your activity at this stage as this is called in an external thread JsonHttpResponseHandler.
You have a good explanation here:
https://stackoverflow.com/a/11536337/891479
You should not call
if(getActivity()!=null){
load();
}
in onCreateView.
onViewCreated is called after onCreateView and as per the docs
The fragment's view hierarchy is not however attached to its parent
at this point.
I think if I remember correctly its better to use getActivity().getApplicationContext()
Related
I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}
I have made a custom adapter to populate my gridView. What I am doing is that i am trying to populate the gridview with two different data(that too are custom) which are: Movies and FavouriteMovies. when the dridview is updated using Movies it updates just fine but when it FavouriteMovies it does not. I am storing FavouriteMovies in a sqlite db and then querying it to return a cursor.the data returns perfectly and there is no error. the main problem is with my MoviesAdapter. inside this when i add Movies to adapter it adds to the list inside MoviesAdapter and it works perfectly but when I add FavouriteMovies to the adapter it does not add it inside the favouriteList inside MoviesAdapter and its size is always zero.
please help!!
here is my MoviesAdapter:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MoviesAdapter extends BaseAdapter {
private Context mContext;
List<Movies> list = new ArrayList<>();
List<FavouriteMovies> favouriteList = new ArrayList<>();
public MoviesAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
#Override
public Object getItem(int position) {
if (list != null)
return list.get(position);
else
return favouriteList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
if (list != null) {
Movies movies = list.get(position);
String posterPath = movies.posterPath;
final String POSTER_FINAL_URL = Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_LARGE + posterPath;
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster);
} else {
FavouriteMovies favouriteMovies = favouriteList.get(position);
byte[] bb = favouriteMovies.posterImage;
moviePoster.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
return convertView;
}
public void add(Movies movies) {
list.add(movies);
}
public void offlineAdd(FavouriteMovies favouriteMovies) {
favouriteList.add(favouriteMovies);
}
public void clear() {
list.clear();
}
}
and here is where I am adding to the adapter:
#Override
protected void onPostExecute(Movies[] strings) {
if (strings != null) {
mMoviesAdapter.clear();
for (Movies moviesStr : strings) {
mMoviesAdapter.add(moviesStr);
}
}else if(mFavouriteMovies != null){
mMoviesAdapter.clear();
for(FavouriteMovies favouriteMoviesStr : mFavouriteMovies){
mMoviesAdapter.offlineAdd(favouriteMoviesStr);
}
}
Log.v("FetchMoviesTask","Count :" + mMoviesAdapter.getItem(0));
mMoviesAdapter.notifyDataSetChanged();
}
So sorry for my crude language.
You will always have count == 0 if you set your favorite movies.
List<Movies> list = new ArrayList<>();
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
This will always return a count of 0 since list never is null. You favorite movies get ignored.
Solutions
Since you are only displaying either movies or favorites you should use 2 adapters. If you don't want to do this,
Use a boolean. Just set showFavorites to true, and display those. Or if you keep your null checks,
set the List<Movie> = null; when displaying favorited, then it will also work.
use following adapter:-
boolean[] CheckedItem_Adap;
ImageLoader imgload;
int headercount = 0, childCount;
LinkedList<HashMap<String, String>> allData;
LinkedList<HashMap<String, String>> temp_Header;
LinkedList<HashMap<String, String>> temp_child = new LinkedList<HashMap<String, String>>();
ArrayList<String> header;
ArrayList<String> childCount1;
private int[] mSectionIndices;
private String[] mSectionLetters;
private LayoutInflater inflater;
private Activity context;
public Adapter_UserTimeLine_StickyGrid(Activity context1, LinkedList<HashMap<String, String>> list, boolean[] checkedItems, ArrayList<String> childCountArray, ArrayList<String> headerarray, LinkedList<HashMap<String, String>> temp_Headers_LinkList) {
this.CheckedItem_Adap = checkedItems;
allData = list;
inflater = LayoutInflater.from(context1);
imgload = new ImageLoader(context1);
childCount1 = childCountArray;
header = headerarray;
temp_Header = temp_Headers_LinkList;
context = context1;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
return allData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.sticky_listitems, parent, false);
}
holder.ivPostPic_Sticky = (ImageView) convertView.findViewById(R.id.ivPostPic_Sticky);
holder.ivSelectedToDelete_Sticky = (ImageView) convertView.findViewById(R.id.ivSelectedToDelete_Sticky);
holder.rlPostSticky_ManageSticky = (RelativeLayout) convertView.findViewById(R.id.rlPostSticky_ManageSticky);
if (CheckedItem_Adap[position] == true) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
} else if (CheckedItem_Adap[position] == false) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
}
if (allData.get(position).get("media_type").equals("text")) {
holder.ivPostPic_Sticky.setImageResource(R.drawable.line_small);
} else {
imgload.DisplayImage(Constants.Imge_baseUrl + allData.get(position).get("video_thumb"),
holder.ivPostPic_Sticky);
}
holder.rlPostSticky_ManageSticky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserTimeLine_Activity.isDeleteSelected) {
if (CheckedItem_Adap[position] == false) {
UserTimeLine_Activity.Selected_PostIds.add(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
CheckedItem_Adap[position] = true;
} else {
UserTimeLine_Activity.Selected_PostIds.remove(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
CheckedItem_Adap[position] = false;
}
for (int i = 0; i < UserTimeLine_Activity.Selected_PostIds.size(); i++) {
Log.e("postid", i + "-" + UserTimeLine_Activity.Selected_PostIds.get(i) + "");
}
if (UserTimeLine_Activity.Selected_PostIds.get(0).equals(UserTimeLine_Activity.Selected_PostIds.get(0))) { }
} else {
String media_type = allData.get(position).get("media_type");
String post_id = allData.get(position).get("post_id");
Intent in = new Intent(context, PostDetails_UserOwn_TimeLIne_Activity.class);
in.putExtra("media_type", media_type);
in.putExtra("post_id", post_id);
in.putExtra("position", String.valueOf(position));
in.putExtra("post_User_Name", allData.get(position).get("post_User_Name"));
context.startActivity(in);
}
}
});
return convertView;
}
#Override
public int getCountForHeader(int i) {
int c = Integer.valueOf(childCount1.get(i));
return c;
}
#Override
public int getNumHeaders() {
return temp_Header.size();
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder = new HeaderViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.headersticky_managepost, parent, false);
}
temp_Header.get(position).get("post_datetime");
TextView tvDate_Sticky = (TextView) convertView.findViewById(R.id.tvDate_Sticky);
for (int i = 0; i < temp_Header.size(); i++) {
}
String Date = temp_Header.get(position).get("post_datetime");
String FormatedDate = parseDateToddMMyyyy(Date);
tvDate_Sticky.setText(FormatedDate);
return convertView;
}
public String parseDateToddMMyyyy(String time) {
String inputPattern = "yyyy-MM-dd";
String outputPattern = "MMM-dd-yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
class HeaderViewHolder {
TextView tvDate_Sticky;
}
class ViewHolder {
ImageView ivPostPic_Sticky, ivSelectedToDelete_Sticky;
RelativeLayout rlPostSticky_ManageSticky;
}
}
I am creating an application in which I am parsing data using Json parsing. I've implemented listview and in my response i have totalpage and current page objects,
A new user will get items from the first page. While the user is scrolling through the listview, the list expands with items from the next page (and the next and the next etc.)
this is my response
http://pastie.org/10259792
The following is code I've tried:
HomeFragment
public class HomeFragment extends Fragment {
// Listview Adapter
ListViewAdapter adapters;
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONparserr jsonParser = new JSONparserr();
ArrayList<HashMap<String, String>> WebsiteList;
// albums JSONArray
JSONArray data = null;
String link_url;
ArrayList<HashMap<String, String>> arrayTemplist;
private AutoCompleteTextView inputSearch;
private ListView lv;
private static final String URL_ALBUMS = "";
private static final String WEBSITE_MENU_ID ="Brand_name";
private static final String TAG_MATCH="data";
//private static final String TAG_NAME="Brand_name";
private static final String TAG_PROFILE="id";
private static final String TAG_CAST="Company";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.listpehlu);
cd = new ConnectionDetector(getActivity());
WebsiteList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
inputSearch = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextViewhomefrag);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < WebsiteList.size(); i++)
{
String currentString =WebsiteList.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(WebsiteList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist,R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapters);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Selected_Product_Listing tf = new Selected_Product_Listing();
Bundle bundle = new Bundle();
bundle.putString("prducts_name", WebsiteList.get(position).get((WEBSITE_MENU_ID)));
// bundle.putString("prducts_name", aList.get(position).get(INTEREST_ACCEPT_NAME));
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
// Toast.makeText(getActivity(),"lets"+ WebsiteList.get(position).get(convertToBase64(convertToBase64(WEBSITE_MENU_ID))), Toast.LENGTH_LONG).show();
}
});
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
}
}
});
return rootView;
}
public String convertToBase64(String text) {
byte[] data = null;
try {
data = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
}
class LoadAlbums extends AsyncTask<String, String, String> {
private JSONObject jsonObj;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
if (json != null) {
try {
jsonObj = new JSONObject(json);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_MATCH);
String totpage=jsonObj.getString("total_page");
System.out.println("Total Page"+totpage);
String curpage=jsonObj.getString("current_page");
System.out.println("Total Page"+curpage);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(WEBSITE_MENU_ID,c.getString(WEBSITE_MENU_ID));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_CAST, c.getString(TAG_CAST));
WebsiteList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
ListAdapter adapter = new SimpleAdapter(
getActivity(), WebsiteList,
R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapter);
}
}
EndlessAdapter
public class EndLessAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> items;
private int layoutId;
public EndLessAdapter(Context context, List<String> items, int LayoutId) {
super(context,LayoutId,items);
this.context = context;
this.items = items;
this.layoutId = LayoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layoutId,parent,false);
TextView tView = (TextView)convertView.findViewById(R.id.txt);
tView.setText(items.get(position));
return convertView;
}
}
EndlessLisView
public class EndlessListView extends ListView implements OnScrollListener {
private Context context;
private View footer;
private boolean isLoading;
private EndLessListener listener;
private BaseAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
// 4
public void addNewData() {
this.removeFooterView(footer);
// adapter.addAll(products);
adapter.notifyDataSetChanged();
isLoading = false;
}
public void setLoading()
{
isLoading = false;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
if(getAdapter() == null)
return;
if(getAdapter().getCount() == 0)
return;
int l = visibleItemCount + firstVisibleItem;
System.out.println("List View Total Item Count = "+totalItemCount+" , l = "+l+", is_loading = "+isLoading);
if(l >= totalItemCount && !isLoading){
// add footer layout
this.addFooterView(footer);
// set progress boolean
isLoading = true;
System.out.println("$$$$$$$$$ call loaddata $$$$$$$$$$$");
// call interface method to load new data
listener.loadData();
}
}
// Calling order from MainActivity
// 1
public void setLoadingView(int resId) {
footer = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null); // footer = (View)inflater.inflate(resId, null);
this.addFooterView(footer);
System.out.println("addfooter ====######");
}
// 2
public void setListener(EndLessListener listener) {
this.listener = listener;
}
// 3
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
this.removeFooterView(footer);
}
public void removeFooter(){
this.removeFooterView(footer);
}
}
You can achieve this by using the following library in Github
https://github.com/nicolasjafelle/PagingListView
Simple create your PagingAdapter and add it to com.paging.listview.PagingListView.
You have to implements the new Pagingable interface and its onLoadMoreItems() method. For example:
listView.setHasMoreItems(true);
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
if (pager < 3) {
new CountryAsyncTask(false).execute();
} else {
listView.onFinishLoading(false, null);
}
}
});
Finally you can use the onFinishLoading(boolean hasMoreItems, List newItems) method to update the list.
listView.onFinishLoading(true, newItems);
Also remember to use this package in your layout files:
<com.paging.listview.PagingListView
android:id="#+id/paging_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Hello here you can find the nostra library for lazy loading and then you can
implement the following example for lazzy loading
https://github.com/nostra13/Android-Universal-Image-Loader
you can achieve Lazy loading by using the below
code
Lets start the coding about the lazy loading.
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;
public class ImageListActivity extends Activity implements OnItemClickListener{
private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}
activity_main.xml
<button android:id="#+id/button_listview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ListView ImageLoad">
imagelist.xml
<listview android:id="#+id/listView_image" android:layout_height="match_parent" android:layout_width="match_parent">
</listview>
item_list_row.xml
<imageview android:adjustviewbounds="true" android:contentdescription="#string/descr_image" android:id="#+id/image" android:layout_height="72dip" android:layout_margin="3dip" android:layout_width="72dip" android:scaletype="centerCrop">
<textview android:id="#+id/text" android:layout_gravity="left|center_vertical" android:layout_height="wrap_content" android:layout_marginleft="20dip" android:layout_width="fill_parent" android:textsize="22sp">
For the Example above you need to download the library universal image loader you can download the library ... happy coding :)
you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.
This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks
Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.
First, you need variable for current_page which initialize with 0
You have to know when to stop. You response has total_page field for that. Save and add validation
Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called
listener.loadData();
to request new data. But you still need to add listener for that. You already have
public void setListener(EndLessListener listener) {
this.listener = listener;
}
You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.
endlessListView.setListener(this);
Try Loading data when listview reaches it's end. Implement OnScrollListener in your fragment. Refer this link Android - ListView to load more items when reached end
You MUST use Paging 3 library to resolve all problems in simplest way.
ListView XMl:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/orderlistview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
/>
</LinearLayout>
OrderList class
public class OrderList {
int _orderId;
int _orderincrement_id;
String _orderstatus;
String _orderdate;
String _ordership_to;
String _ordertotal;
String _ordercurrency_symbol;
// Empty constructor
public OrderList() {
}
// constructor
public OrderList(int _orderId, int _orderincrement_id, String _orderstatus,
String _orderdate, String _ordership_to, String _ordertotal,
String _ordercurrency_symbol) {
this._orderId = _orderId;
this._orderincrement_id = _orderincrement_id;
this._orderstatus = _orderstatus;
this._orderdate = _orderdate;
this._ordership_to = _ordership_to;
this._ordertotal = _ordertotal;
this._ordercurrency_symbol = _ordercurrency_symbol;
}
public int get_orderId() {
return _orderId;
}
public void set_orderId(int _orderId) {
this._orderId = _orderId;
}
public int get_orderincrement_id() {
return _orderincrement_id;
}
public void set_orderincrement_id(int _orderincrement_id) {
this._orderincrement_id = _orderincrement_id;
}
public String get_orderstatus() {
return _orderstatus;
}
public void set_orderstatus(String _orderstatus) {
this._orderstatus = _orderstatus;
}
public String get_orderdate() {
return _orderdate;
}
public void set_orderdate(String _orderdate) {
this._orderdate = _orderdate;
}
public String get_ordership_to() {
return _ordership_to;
}
public void set_ordership_to(String _ordership_to) {
this._ordership_to = _ordership_to;
}
public String get_ordertotal() {
return _ordertotal;
}
public void set_ordertotal(String _ordertotal) {
this._ordertotal = _ordertotal;
}
public String get_ordercurrency_symbol() {
return _ordercurrency_symbol;
}
public void set_ordercurrency_symbol(String _ordercurrency_symbol) {
this._ordercurrency_symbol = _ordercurrency_symbol;
}
}
Activity
public class OrderListFragment extends Fragment {
View rootView;
ListView lv;
List<OrderList> list ;
MyListAdapter adt;
DatabaseHandler db ;
ProgressDialog progress;
SharedPreferences pref;
public OrderListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmentorderlist, container,
false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
if(list.size() == 0){
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data.....");
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String customer_id = pref.getString("customer_id", null);
Log.v("log_tag", "customer_id"+customer_id);
if(customer_id != null){
Log.v("log_tag", "customer_id 2332 ::: "+customer_id);
new FetchOrderListData().execute(customer_id);
}
}
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Bundle bundle = new Bundle();
bundle.putString("orderlist_increment_id", list.get(position).get_orderincrement_id()+"");
Fragment fragment = new OrderdetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = OrderListFragment.this
.getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = fragmentManager
.beginTransaction();
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.Frame_Layout, fragment)
.commit();
}
});
return rootView;
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custom_orderlistdata,
null);
TextView ordernumbertxt = (TextView) convertView
.findViewById(R.id.ordernumberTxt);
TextView orderdate = (TextView) convertView
.findViewById(R.id.orderdateTxt);
TextView orderamount = (TextView) convertView
.findViewById(R.id.orderAmountTxt);
TextView orderSatusTxt = (TextView) convertView
.findViewById(R.id.orderSatusTxt);
ordernumbertxt.setText(Html.fromHtml("<b>Order Number : </b>"+list.get(position).get_orderincrement_id()+""));
orderdate.setText(list.get(position).get_orderdate());
orderSatusTxt.setText(list.get(position).get_orderstatus());
String parts = list.get(position).get_ordertotal();
double d = Double.parseDouble(parts);
double dval = roundTwoDecimals(d);
orderamount.setText(Html.fromHtml("<b>Total : </b>"+list.get(position).get_ordercurrency_symbol()+" "+dval));
return convertView;
}
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
private class FetchOrderListData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject listSize = null;
Integer cust_id = Integer.parseInt(args[0]);
try {
listSize = DBAda.getAllOrderListData(cust_id);
////*** call your HTTP Service over here ***////
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listSize;
}
protected void onPostExecute(JSONObject jsonObj) {
db = new DatabaseHandler(getActivity());
if (progress != null) {
progress.hide();
}
if (jsonObj == null) {
return;
}
JSONArray json;
try {
json = jsonObj.getJSONArray("records");
for (int i = 0; i < json.length(); i++) {
JSONObject jobj;
try {
jobj = json.getJSONObject(i);
int order_id = Integer.parseInt(jobj.getString("order_id").toString());
int order_IncrementId = Integer.parseInt(jobj.getString("increment_id").toString());
String orderStatus = jobj.getString("status");
String orderdate = jobj.getString("date");
String ordershipto = jobj.getString("ship_to");
String ordertotal = jobj.getString("order_total");
String ordersymbol = jobj.getString("currency_symbol");
//db.addWishlistItem(new WishList(entity_id,quentity,comment,name,short_description,thumbnails,itemId));
db.addOrderListItem(new OrderList(order_id, order_IncrementId, orderStatus, orderdate, ordershipto, ordertotal, ordersymbol));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
}
}
}
I have a custom BaseAdapter class that creates views for comments, usernames, and numbers. This BaseAdapter receives this information from An AsyncTask. The AsyncTask runs when the user reaches the bottom of the listView. The problem is the BaseAdapter wont add new data. When I try to add new data it deletes the current data in the list and then adds the new data. I want it to keep all the data and just add data to the bottom of the listView. All of these classes are in the same Activity. Here is my current code.
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
mainListView = (ListView) findViewById(android.R.id.list);
class EndlessScrollListener implements OnScrollListener {
private int i = 0;
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
new loadComments().execute();
mainListView.smoothScrollToPosition(0);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
mainListView.setOnScrollListener(new EndlessScrollListener());
You try this :
public class Comment {
String username;
String content;
String number;
}
Class Adapter:
public class CommentAdapter extends BaseAdapter {
private List<Comment> listComment;
private Context context;
public CommentAdapter(List<Comment> listComment, Context context) {
super();
this.listComment = listComment;
this.context = context;
}
#Override
public int getCount() {
return listComment.size();
}
#Override
public Comment getItem(int position) {
return listComment.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.comment_item, null);
}
final TextView textViewUsername = (TextView) v
.findViewById(R.id.comment_Username);
final TextView textViewNumber = (TextView) v
.findViewById(R.id.comment_number);
final TextView textViewContent = (TextView) v
.findViewById(R.id.comment_Content);
final String username = listComment.get(position).getUsername();
final String number= listComment.get(position).getNumber();
String content = listComment.get(position).getContent();
textViewUsername.setText(username);
textViewNumber.setText(number);
textViewContent.setText(content);
return v;
}
}
When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();
package com.example.baseadapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] title = new String[] {
"image 1", "image 2", "image 3", "image 4"
};
public static final Integer[] images = {
R.drawable.aa, R.drawable.bb, R.drawable.cc, R.drawable.cc, R.drawable.dd
};
ListView listview;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < title.length; i++) {
RowItem item = new RowItem(images[i], title[i]);
rowItems.add(item);
}
listview = (ListView)findViewById(R.id.listview);
customBaseAdapter cba = new customBaseAdapter(this, rowItems);
listview.setAdapter(cba);
listview.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "item selected", Toast.LENGTH_LONG).show();
}
public class customBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
public customBaseAdapter(Context context, List<RowItem> listItem) {
this.context = context;
rowItem = listItem;
Log.d("const", "const");
}
#Override
public int getCount() {
Log.d("count", "count");
return rowItem.size();
}
#Override
public Object getItem(int arg0) {
Log.d("item", "item");
return rowItem.get(arg0);
}
#Override
public long getItemId(int position) {
Log.d("const", "item id");
return rowItem.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("const", "getview");
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
RowItem rowitem = (RowItem)getItem(position);
TextView textForTitle;
ImageView imgForImage;
convertView = inflater.inflate(R.layout.inflate, null);
textForTitle = (TextView)convertView.findViewById(R.id.textview);
imgForImage = (ImageView)convertView.findViewById(R.id.imageview);
textForTitle.setText(rowitem.getTitle());
imgForImage.setImageResource(rowitem.getImageId());
return convertView;
}
}
public class RowItem {
int imageId;
String title;
public RowItem(int imageId, String title) {
this.imageId = imageId;
this.title = title;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getTitle() {
return title;
}
public void setStringTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});