Hi,
I try to refresh my data with a tweet app which I am making. When I delete a following person by cliking on the button "following_del", I want that my list view being refreshed without the user I just deleted. Do you have any idea do to this? I am in a baseAdaptor class. Thanks
public class UsersAdapter extends BaseAdapter implements DialogInterface.OnShowListener {
private List<User> mUsers;
Integer BUTTON_ACTIVATE = 0;
public List<User> getUsers() {
return mUsers;
}
public Context context;
public void setUsers(List<User> users) {
mUsers = users;
}
public UsersAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return mUsers != null ? mUsers.size() : 0;
}
#Override
public User getItem(int position) {
return mUsers.get(position);
}
#Override
public long getItemId(int position) {
// if (getItem(position).getId() == null) {
return 0;
// } else {
// return getItem(position).getId().hashCode();
// }
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.follower_item, parent, false);
BUTTON_ACTIVATE = 0;
}
final User user = getItem(position);
TextView handleView = (TextView) convertView.findViewById(R.id.handle);
handleView.setText(user.getHandle());
TextView statusView = (TextView) convertView.findViewById(R.id.status);
Log.i(context.getClass().getName(), "Je suis dans ce context2");
ImageButton button_del = (ImageButton) convertView.findViewById(R.id.add_following);
button_del.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (AccountManager.isConnected(context)) {
new AsyncTask<String, Void, Integer>() {
#Override
protected Integer doInBackground(String... arg) {
try {
String handle = AccountManager.getUserHandle(context);
String token = AccountManager.getUserToken(context);
String content = user.getHandle();
if (handle.compareTo(content) != 0) {
new ApiClient().postdelFollowing(handle, token, content);
return 1;
}
} catch (IOException e) {
return 0;
}
}
#Override
protected void onPostExecute(Integer success) {
if (success == 1) {
Toast.makeText(context, "Vous ne suivez plus " + user.getHandle(), Toast.LENGTH_SHORT).show();
if (context.getClass().getName().compareTo(FollowingActivity.class.getName()) == 0) {
Intent intent = new Intent(context, FollowingActivity.class);
intent.putExtras(FollowingFragment.newArgument(UsersFragment.user));
context.startActivity(intent);
}
} else {
Toast.makeText(context, "Une erreur s'est produite", Toast.LENGTH_SHORT).show();
}
}
}.execute();
} else {
new AlertDialog.Builder(context)
.setMessage("Veuillez vous connecter")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
});
return convertView;
}
}
Related
List view of ratings I am getting from web service I need to store the response of ratings in database. Ratings are storing but not according to the position if I given ratings to 1st person it is storing it to another please help me out.
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty()) {
// courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
// convertView = null;
if (convertView == null) {
TabviewHolder = new ViewHolder();
//LayoutInflater inflater = getLayoutInflater();
inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
// TabviewHolder.rating.setOnRatingBarChangeListener(setOnRatingBarChangeListener(TabviewHolder, position));
TabviewHolder.rating.setTag(position);
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.FacultyName.setTag(position);
my_name = mFac.getEmployeename().toString();
my_email = mFac.getEmployeeid().toString();
feedbackresult = String.valueOf(rating);
// ratingBar.setRating(rating);
//my_rating = mFac.getRatingStar();
TabviewHolder.rating.setRating(mFac.getRatingStar());
// TabviewHolder.rating.setTag(position);
// my_rating = hi.toString();
// rating.setOnRatingBarChangeListener(getApplicationContext());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult = String.valueOf(rating);
hi = feedbackresult;
// if(!fromUser) return;
// Faculty item = getItem(position);
// item.setRatingStar(rating);
int index = (Integer) (ratingBar.getTag());
mFac.setRatingStar(Float.parseFloat(feedbackresult));
//amount=Float.parseFloat(feedbackresult);
// TabviewHolder.rating.setRating(Float.parseFloat(feedbackresult));
Log.d("feedback", "feedback is: " + feedbackresult);
}
});
return convertView;
}
/*private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final ViewHolder holder, final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
FacultyName item = getItem(position);
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}*/
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Faculty getItem(int position) {
return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
progressDialog = ProgressDialog.show(Feedback.this, "Faculty Feedback!", "Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
} else {
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
/* #Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end**/
//**************************SECOND ASYNC TASK*********************************
private class SendFeedbackSyncerBg extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Feedback.this, "Faculty Feedback!", "Uploading your ratings", true);
}
#Override
protected Void doInBackground(String... params) {
//Call Web Method from webService
// FeedBackResponse=WebService.sendfeedback(programtype,employeemailid,employeename,feedbackresult);
// uploaddata = parid(faculty_name, email, rate, "getUserInfo");
uploaddata = parid(rate, my_name, my_email, "getUserInfo");
return null;
}// doInBackground Process
#Override
//Once WebService returns response
protected void onPostExecute(Void result) {
progressDialog.dismiss();
if (uploaddata == false) {
Toast.makeText(getApplicationContext(), "Not Done!", Toast.LENGTH_SHORT).show();
} else {
courseEmptyLayout.setVisibility(LinearLayout.GONE);
Toast.makeText(getApplicationContext(), "Thanks for Feedback!!", Toast.LENGTH_SHORT).show();
}
}// End of onPostExecute
/* #Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getApplicationContext(), "Faculty Feedback!", "Uploading your ratings", true);
}*/
}
I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
DisplayImageOptions options;
private ProgressDialog progress;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container, false);
context = getActivity();
lvrecipe = (ListView) rootView.findViewById(R.id.lvrecipe);
// adView = (MoPubView)rootView. findViewById(R.id.mopub_sample_ad);
new getrecipe().execute();
db = new MyDatabase(getActivity());
// recipelist = DataManager.recipelist;
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
/* if(recipeid!=null){
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();*/
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
// adddisplay();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if (recipelist != null) {
return recipelist.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (recipelist != null) {
return recipelist.get(position);
} else {
return 0;
}
}
#Override
public long getItemId(int position) {
if (recipelist != null) {
return position;
} else {
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
holder.txtduration = (TextView) convertView.findViewById(R.id.txtduration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (recipelist != null) {
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if (isfav) {
holder.fav_unfav.setImageResource(R.drawable.favourite);
} else {
holder.fav_unfav.setImageResource(R.drawable.favourites);
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try {
String[] prep = recipelist.get(position).getPrep_time().split(" ");
String[] cook = recipelist.get(position).getCooking_time().split(" ");
int totalTime = Integer.parseInt(prep[0]) + Integer.parseInt(cook[0]);
holder.txtduration.setText(""+totalTime+" min");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl + "recipe/" + recipelist.get(position).getRecipeid() + ".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (recipelist.get(position).getVideo_link().equals("none")) {
// holder.imgvideo.setVisibility(View.GONE);
}
String rating = recipelist.get(position).getRatings();
if (rating != null && rating.trim().length() > 0) {
holder.ratingbar.setRating(Float.valueOf(rating));
}
//holder.imgrecipe.setImage(url,getResources().getDrawable(R.drawable.cusine));
if (holder.imgrecipe != null) {
if (url != null && url.trim().length() > 0) {
//final ProgressBar pbar = holder.pbar;
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {
}
}
return convertView;
}
class ViewHolder {
TextView txttile, txtduration;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
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);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}}
The errors that are showing in Crashlytics is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.raccoonfinger.salad.RecipeListFragment.connectionerror(RecipeListFragment.java:381)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:335)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:296)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please do not use getActivity() directly in Fragment because sometimes it returns null..
Always pass activity as a parameter in constructor..!!
Please use below method to create your Fragment and use activity reference instead of getActivity()..
public static AboutFragment newInstance(Activity activity) {
AboutFragment aboutFragment = new AboutFragment();
aboutFragment.mActivity = activity;
return aboutFragment;
}
Hope it will help.
Thanks ..!!
Im reusing an Integer value that is calculated in th AsyncTask class and i need to create new instances of this class very often because the function calculated in the background needs to be done for every element of a ListView.
Im initializing a new BackgroundTask so i use this code in the main method called ShowItems(final Item item)
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
Till here it works. then i need to create a new mBackgroundTask in a ToggleButton and this is where the problem arrises. i can't use this while defining the new class as i'll be getting the instance of the ToggleButton and not the original AsyncResponse
Here is my complete code
public interface AsyncResponse {
Integer processFinish(Integer result);
}
and
public class ItemView extends LinearLayout implements AsyncResponse{
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
public ToggleButton followButton;
public String nextFollowAction = "";
public Integer result1 = 77;
public BackgroundTask mBackgroundTask = null;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
//mBackgroundTask.delegate = this;
// TODO Auto-generated constructor stub
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
prezzo = (TextView)findViewById(R.id.tvPrezzo);
scadenza = (TextView)findViewById(R.id.tvScadenza);
followers = (TextView)findViewById(R.id.tvFollowers);
ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
followButton = (ToggleButton)findViewById(R.id.btnFollow);
}
public void showItems(final Item item) {
prezzo.setText(item.getPrezzo());
ic_thumbnail.setImageBitmap(item.getIcon());
scadenza.setText(item.getPrezzo());
followers.setText("Followers: " + item.getFollowers());
hProgressBar.setProgress(item.getCoefficient());
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
if (result1 != null){
Log.i("result1 = ", Integer.toString(result1));
askForFollowing(result1, nextFollowAction, item);
}
followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Log.i("followButton", "toggle enabled");
followButton.getTextOn();
//error
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)1);
//askForFollowing(statusCode, nextFollowAction, item);
//increaseFollowers(item);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
} else {
// The toggle is disabled
Log.i("followButton", "toggle disabled");
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)2);
followButton.getTextOff();
followButton.setBackgroundResource(R.drawable.action_object_button_green);
}
}
});
}
public void askForFollowing(int statusCode, String nextFollowAction, Item item){
//Status code: 0 --> OK
if(statusCode == 0) {
Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
changeFollowStatus(nextFollowAction, item);
}
// Status code 108 --> Oggetto giĆ seguito
else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 108", "statusCode == 108");
nextFollowAction = "kUnfollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
}
// Status code 122 --> Oggetto non ancora seguito
else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 122", "statusCode == 122");
nextFollowAction = "kFollowAction";
followButton.setEnabled(false);
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
}
else {
// Altrimenti gestisco l'errore
Log.i("errore status code LVA", "devo gestire l'errore");
}
}
public void changeFollowStatus(String action, Item item){
Log.i("changeFollowStatus action", action);
if(action.contains("kFollowAction")) {
Log.i("changeFollowStatus", "1");
nextFollowAction = "kUnfollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
followButton.getTextOn();
increaseFollowers(item);
}
else if(action.contains("kUnfollowAction")){
Log.i("changeFollowStatus", "2");
nextFollowAction = "kFollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
followButton.getTextOff();
decreaseFollowers(item);
}
}
public void increaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void decreaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
#Override
public Integer processFinish(Integer result) {
Log.i("method processFinish", Integer.toString(result));
Log.i("method processFinish", "method");
return result;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class BackgroundTask extends AsyncTask<Long, Void, Integer> {
//public AsyncResponse delegate;
private AsyncResponse listener;
public BackgroundTask(AsyncResponse listener){
this.listener = listener;
}
#Override
protected Integer doInBackground(Long... params) {
// TODO: attempt authentication against a network service.
int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
Log.i("doInBackground", Integer.toString(i));
return i;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
}
#Override
protected void onPostExecute(Integer result) {
mBackgroundTask = null;
result1 = listener.processFinish(result);
//delegate.processFinish(result);
//ItemView
//Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
}
#Override
protected void onCancelled() {
mBackgroundTask = null;
//showProgress(false);
}
}
}
more code
public class ListViewAdapter extends ArrayAdapter<String> {
private LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<Item> items;
public Bitmap icon;
//private ViewHolder viewHolder = new ViewHolder();
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<Item> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
#Override
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
} else {
view = (ItemView) convertView;
}
Item item = items.get(position);
view.showItems(item);
return view;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View v) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
}
If i understood this correctly, i think ItemView.this will solve your issue here.
Note: As pointed out in comment, you should run single AsyncTask to loop through all list items instead of creating new AsyncTask for each item.
I'm having trouble with getting the correct items after deleting an item in my ListView.
The position should fit to the index of the item in an ArrayList, but after deleting an item in the ListView, the positions are incorrect (and might even give an indexoutofbounds exception.
I bet it has something to do with the Views position, but I just can't find the error.
I have this ListActivity class with an inner BaseAdapter class:
public class MSMobilMyStocksActivity extends ListActivity {
static MyStocksCtr myStocksCtr;
static ListView listview;
static EfficientAdapter adap;
boolean downloadSuccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystockslist);
mContext = this;
listview = getListView();
myStocksCtr = MyStocksCtr.getInstance(mContext);
adap = new EfficientAdapter(this);
setListAdapter(adap);
if (isOnline())
new InsertDataTask().execute();
else {
startTimer();
Toast.makeText(mContext, "Du har ingen internetforbindelse", 1000)
.show();
}
}
public static boolean updateData() {
return myStocksCtr.downloadJson();
}
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
try {
listview.setEnabled(false);
} catch (Exception e) {
}
}
// can use UI thread here
#Override
protected void onPostExecute(final Void unused) {
if (isOnline()) {
if (downloadSuccess) {
try {
if (myStocksCtr.getArray().size() == 0) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else if (myStocksCtr.getArray().size() == 1
&& myStocksCtr.getArray().get(0)
.getString("FH_FULLNAME").equals("-")) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else {
adap.notifyDataSetChanged();
}
} catch (JSONException e) {
Toast.makeText(mContext, "JSONException", 2000).show();
}
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
startTimer();
try {
listview.setEnabled(true);
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
downloadSuccess = false;
if (isOnline()) {
try {
if (updateData())
downloadSuccess = true;
} catch (Exception e) {
Toast.makeText(mContext, "Fejl under download af data",
2000).show();
downloadSuccess = false;
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
return null;
}
}
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mylistitem, null);
holder = new ViewHolder();
holder.stockName = (TextView) convertView
.findViewById(R.id.stockName1);
holder.stockPrice = (TextView) convertView
.findViewById(R.id.stockValue1);
holder.stockChange = (TextView) convertView
.findViewById(R.id.stockChange1);
holder.stockPctChange = (TextView) convertView
.findViewById(R.id.stockPctChange1);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent i = new Intent(mContext, MSStockDetailActivity.class);
Bundle b = new Bundle();
b.putInt("position", position); //Your id
b.putBoolean("isMyStocks", true);
i.putExtras(b); //Put your id to your next Intent
mContext.startActivity(i);
} catch (Exception e) {
Toast.makeText(mContext, "OnClick error ", 2000)
.show();
}
}
});
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
final CharSequence[] items = {
"See stock details",
"Delete the stock \"" + holder.stockName.getText()
+ "\" from the list", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setTitle("Configure list");
builder.setItems(items,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int item) {
if (item == 1) {
myStocksCtr.removeStock(holder.ric);
adap.notifyDataSetChanged();
} else if (item == 2) {
}
Toast.makeText(mContext, items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_FULLNAME");
holder.stockName.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_RIC");
holder.ric = result;
} catch (JSONException e) {
e.printStackTrace();
}
// + String.valueOf(position));
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_PRC");
if (String.valueOf(result.charAt(result.length() - 2)).equals(
".")) {
result += "0";
}
;
holder.stockPrice.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
holder.position = position;
return convertView;
}
static class ViewHolder {
String ric;
TextView stockName;
TextView stockPrice;
TextView stockPctChange;
TextView stockChange;
int position;
}
#Override
public Filter getFilter() {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return myStocksCtr.getArray().size();
}
#Override
public JSONObject getItem(int position) {
return myStocksCtr.getArray().get(position);
}
}
This is some of the things in my stocks controller (where the array is):
public class MyStocksCtr {
private static MyStocksCtr INSTANCE = null;
ArrayList<String> myStocksArray;
JSONCtr jsonCtr;
static Context mContext;
boolean isRunning = false;
ArrayList<JSONObject> myArray;
MyStocksCtr(Context mContext) {
this.mContext = mContext;
jsonCtr = new JSONCtr(mContext);
myStocksArray = new ArrayList<String>();
myArray = new ArrayList<JSONObject>();
}
}
public static MyStocksCtr getInstance(Context context){
mContext = context;
if(INSTANCE == null) {
INSTANCE = new MyStocksCtr(mContext);
}
return INSTANCE;
}
public ArrayList<JSONObject> getArray() {
return myArray;
}
public boolean downloadJson() {
if (!myStocksArray.isEmpty()) {
String myStocksString = "";
for (String s : myStocksArray)
myStocksString += (s + "%2C");
myStocksString = myStocksString.substring(0,
myStocksString.length() - 3);
jsonCtr.getJSON(preStocksUrl + myStocksString + postStocksUrl);
myArray.clear();
myArray.addAll(jsonCtr.getArray());
return true;
} else {
return false;
}
}
public void removeStock(String newStock) {
JSONObject toRemove = null;
for (JSONObject obj : myArray) {
try {
if (obj.getString("FH_RIC").equals(newStock)) {
toRemove = obj;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Kunne ikke fjerne objekt", 1000)
.show();
}
}
if (toRemove != null){
myStocksArray.remove(newStock);
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
saveMyStocks();
}
}
}
In my jsonCtr I remove and get the array:
public ArrayList<JSONObject> getArray() {
return rics1;
}
public void removeRic(Object o){
rics1.remove(o);
}
When i have removed an object from the list, the list is updated, so the item is no longer there. But the positions of the views are all messed up, and some of them are outofbounds.
I'm guessing it has something to do with the position in GetView is final, but I'm not sure? And if that is the problem, how do I correct it?
Hmm, I didn't looked at every detail of your code but i think you're missing to call myAdaper.notifyDataSetChanged() after changing your array.
Edit
That*s really tough to look trough because it's a lot of code you post here. So here is what I got. I can't see what's going on in here (on stock remove) but there must be something wrong I think:
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
Please don't post the whole code of that too, try to reduce it to the actual problem. I wont check the whole code again...