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 ..!!
Related
I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
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;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
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.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object 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() {
progressDialog= ProgressDialog.show(getActivity(), "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.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
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*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#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();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
Here is my CartRowHolder
class CartRowHolder {
ImageView icon;
TextView txtprice,txttitle,personalize;
TextView txtquantity;
ImageView imgdelete,imgedit,image;
public CartRowHolder(View v) {
icon=(ImageView)v.findViewById(R.id.imageicon);
txtprice=(TextView)v.findViewById(R.id.txtoprice);
txttitle=(TextView)v.findViewById(R.id.txtotitle);
txtquantity=(TextView)v.findViewById(R.id.txtoquantity);
personalize=(TextView)v.findViewById(R.id.txtpersonalize);
imgdelete=(ImageView)v.findViewById(R.id.imgdelete);
imgedit=(ImageView)v.findViewById(R.id.edit);
}
}
Now in the ListView a ImageView and Delete Button, Edit button is there So as i click on the Edit a Dialogbox is open and in the Dialogbox i want to pass the imageView.....and i have the ImageUrl
class CartAdapter extends BaseAdapter {
Activity activity;
List<CartItem> cartItemList;
ImageLoader imageLoader;
LayoutInflater layoutInflater;
CartItem cartItem;
AppPreferenceManager appPreferenceManager;
public CartAdapter(Activity activity,List<CartItem>cartItemList) {
this.activity=activity;
this.cartItemList=cartItemList;
appPreferenceManager=new AppPreferenceManager(activity);
}
public int getCount() {
return cartItemList.size();
}
#Override
public Object getItem(int position) {
return cartItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
cartItem=cartItemList.get(position);
CartRowHolder cartRowHolder;
Bundle extras = getIntent().getExtras();
TextView tk;
if (extras != null) {
}
if(imageLoader==null) {
imageLoader=new ImageLoader(activity);
}
if(layoutInflater==null) {
layoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null) {
convertView=layoutInflater.inflate(R.layout.order_row,null);
cartRowHolder=new CartRowHolder(convertView);
cartRowHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CartItem cartItem=cartItemList.get(position);
deletCartItem(cartItem.getPid());
}
});
cartRowHolder.imgedit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CartItem cartItem=cartItemList.get(position);
ImageView image;
final EditText personalise;
Button update;
final TextView quan,title1;
final ImageButton plusd,minusd;
final AlertDialog alertDialog;
View view=getLayoutInflater().inflate(R.layout.activity_edit,null);
final AlertDialog.Builder builder=new AlertDialog.Builder(CartActivity.this).setView(view);
update = (Button)view.findViewById(R.id.update);
quan=(TextView)view.findViewById(R.id.quan);
minusd=(ImageButton)view.findViewById(R.id.minus);
plusd=(ImageButton)view.findViewById(R.id.plus);
alertDialog=builder.create();
title1=(TextView)view.findViewById(R.id.TitleView);
title1.setText(cartItemList.get(position).getName());
personalise=(EditText)view.findViewById(R.id.editpersonalize);
personalise.setText(cartItemList.get(position).getPersonalize());
quan.setText(cartItemList.get(position).getQunatity());
image=(ImageView)view.findViewById(R.id.image1);
//imageLoader.DisplayImage(Bitmap.get);
final int num=Integer.parseInt(quan.getText().toString());
final int[] counter = {num};
plusd.setOnClickListener(new View.OnClickListener() {
//int counter=0;
#Override
public void onClick(View v) {
//Toast.makeText(CartActivity.this, "Positive is click", Toast.LENGTH_SHORT).show();
counter[0]++;
quan.setText(""+ counter[0]);
minusd.setClickable(true);
plusd.setClickable(true);
if(counter[0] ==10){
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(SingleItem_Activity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
if(counter[0] >=10) {
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
}
});
minusd.setOnClickListener(new View.OnClickListener() {
// int counter=0;
#Override
public void onClick(View v) {
if(counter[0] ==1) {
minusd.setClickable(false);
}
else{
counter[0] = counter[0] -1;
quan.setText(""+ counter[0]);
if(counter[0] <=1){
minusd.setClickable(false);
plusd.setClickable(true);}
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String update_quan=quan.getText().toString();
String update_personalise = personalise.getText().toString();
updateCartItem(update_quan,cartItem.getPid(),update_personalise);
//Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
cartRowHolder.txttitle.setText(cartItem.getName());
cartRowHolder.txtprice.setText(cartItem.getSubtotal());
cartRowHolder.txtquantity.setText(cartItem.getQunatity());
cartRowHolder.personalize.setText(cartItem.getPersonalize());
imageLoader.DisplayImage(cartItem.getImage(), cartRowHolder.icon);
}
return convertView;
}
OK, you will need to following code:
1) add permission for internet in your manifest
<uses-permission android:name="android.permission.INTERNET" />
2) You will need to update your list adapter
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(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)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
3) update your mainactivity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
4) custom image layout
<?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" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
A bit of explanation:
there is an interface between the activity and the list adapter (IDialog)
as part of the data, each item(person) has a field URL, when the user is clicking on the button, the activity is "notified" by the interface and downloading the appropriate image and showing it in the dialog
After so any hour I find out the Soloution. Now In the Dialog-box i can again download the image.....
imageFileURL="url";
String imageFileURL=cartItemList.get(position).getImage();
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.connect();
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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;
ImageView fav_unfav;
DisplayImageOptions options;
private ProgressDialog progress;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
int counter=8;
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);
new getrecipe().execute();
db = new MyDatabase(getActivity());
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
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();
}
});
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);
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.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite));
}
else{
holder.fav_unfav.setBackgroundDrawable(getResources().getDrawable(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]);
}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"))
{
}
String rating = recipelist.get(position).getRatings();
if(rating!=null && rating.trim().length() > 0)
{
holder.ratingbar.setRating(Float.valueOf(rating));
}
if(holder.imgrecipe!=null){
if (url != null && url.trim().length() > 0)
{
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;
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 is showing in Crashlytics is:
Fatal Exception: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.initialParse(StringToReal.java:176)
at java.lang.StringToReal.parseFloat(StringToReal.java:323)
at java.lang.Float.parseFloat(Float.java:306)
at java.lang.Float.valueOf(Float.java:343)
at com.raccoonfinger.glutenfree.RecipeListFragment$Custom_Adapter.getView(Unknown Source)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4512)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
I think you get error on below Line.
holder.ratingbar.setRating(Float.valueOf(rating));
This means the value inside "rating" is string, please check.
Setting Rating takes float value , in Case ur value is String :
holder.ratingbar.setRating(Float.parseFloat(rating));
use parseFloat()
holder.ratingbar.setRating(Float.parseFloat(rating));
inplace of
holder.ratingbar.setRating(Float.valueOf(rating));
I'm not sure where you are getting the value of rating. But it is attempting to parse that value of string to Float that is throwing your error.
String rating = recipelist.get(position).getRatings();
Also check that the string is not empty.
// if(rating!=null && rating.trim().length() > 0)
if(rating!=null && !rating.isEmpty() && rating.trim().length() > 0)
{
try{
holder.ratingbar.setRating(Float.valueOf(rating));
}
catch (NumberFormatException e){
// TO DO
}
}
Firstly examine the value of rating (log it) and if you are getting a float in there I suggest having a look at this answer:
float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
response of this method should be float String rating = recipelist.get(position).getRatings();or to get it in String you have to convert it into String by using toString();thats why you are getting NumberFormatException
I have checked all the related posts so far, but did not managed to fix this "Out of memory on a 1843216-byte allocation" error my GridView activity generates.
Basically this activity displays the images from the phone's gallery in a GridView (as a multiple image picker), at first it loads everything just fine, at the second try I get the memory error and the GridView skips loading some of the image thumbnails.
I have disabled the memory caching by: ".cacheInMemory(false)", and using only disk caching with fixed ImageView width and height, but still got the memory error.
Could someone help me out? Thanks!
The CustomGalleryActivity, showing all pictures on the phone:
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getAction();
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(getBaseContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.tasksProcessingOrder(QueueProcessingType.LIFO);
//.memoryCache(new WeakMemoryCache());
L.writeLogs(false);
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.destroy();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("all_path", allPath);
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//adapter.changeSelection(v, position);
if (adapter.getSelected().size() >= 15) {
Toast.makeText(getApplicationContext(), "Max. 15 de poze pot fi selectate o data!", Toast.LENGTH_LONG).show();
} else {
adapter.changeSelection(v, position);
}
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
#SuppressWarnings("deprecation")
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
}
And its CustomAdapter:
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater infalter;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public GalleryAdapter(Context c, ImageLoader imageLoader) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.imageLoader = imageLoader;
// clearCache();
}
#Override
public int getCount() {
return data.size();
}
#Override
public CustomGallery getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
boolean isAllSelected = true;
for (int i = 0; i < data.size(); i++) {
if (!data.get(i).isSeleted) {
isAllSelected = false;
break;
}
}
return isAllSelected;
}
public boolean isAnySelected() {
boolean isAnySelected = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
isAnySelected = true;
break;
}
}
return isAnySelected;
}
public ArrayList<CustomGallery> getSelected() {
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
return dataT;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
} else {
data.get(position).isSeleted = true;
}
((ViewHolder) v.getTag()).imgQueueMultiSelected.setSelected(data
.get(position).isSeleted);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = infalter.inflate(R.layout.gallery_item, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView
.findViewById(R.id.imgQueue);
holder.imgQueueMultiSelected = (ImageView) convertView
.findViewById(R.id.imgQueueMultiSelected);
if (isActionMultiplePick) {
holder.imgQueueMultiSelected.setVisibility(View.VISIBLE);
} else {
holder.imgQueueMultiSelected.setVisibility(View.GONE);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgQueue.setTag(position);
try {
imageLoader.displayImage("file://" + data.get(position).sdcardPath,
holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgQueueMultiSelected
.setSelected(data.get(position).isSeleted);
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgQueueMultiSelected;
}
public void clearCache() {
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
}
Try to do this with Picasso library instead of using image loader library. Hope this may helpful for you.
https://github.com/square/picasso