【问题标题】:App is crashing while scrolling the listview滚动列表视图时应用程序崩溃
【发布时间】:2015-12-19 06:20:46
【问题描述】:

在我的应用中,我在列表视图中显示数据。滚动浏览列表视图时,我的应用程序崩溃了。我应该做出哪些改变?

正如错误中给出的,我的 RecipeListFragment.java 文件是:

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();
    }
}   

Crashlytics 中显示的错误是:

   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)

【问题讨论】:

    标签: android android-layout android-fragments android-intent android-activity


    【解决方案1】:

    我认为你在下面的 Line 上遇到了错误。

    holder.ratingbar.setRating(Float.valueOf(rating));
    

    表示“rating”里面的值是字符串,请检查。

    【讨论】:

    • 如果评级为空那么rating.trim().length() &gt; 0这个条件呢?
    • 请在您得到想法之前打印评分值。
    • rating 可能包含字符串而不是数字。
    【解决方案2】:

    设置 Rating 采用浮点值,如果你的值是字符串:

     holder.ratingbar.setRating(Float.parseFloat(rating));
    

    【讨论】:

      【解决方案3】:

      使用parseFloat()

      holder.ratingbar.setRating(Float.parseFloat(rating));
      

      代替

      holder.ratingbar.setRating(Float.valueOf(rating));
      

      【讨论】:

        【解决方案4】:

        我不确定您从哪里获得评级的价值。但它试图将字符串的值解析为抛出错误的 Float。

        String rating = recipelist.get(position).getRatings();
        

        还要检查字符串是否为空。

        // 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    
            }
        }  
        

        首先检查 rating 的值(记录它),如果你在那里得到一个浮动,我建议看看this answer:

        float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
        

        【讨论】:

        • 非常感谢。项目成功运行并解决了错误。
        • 实际上字符串为空是问题所在。使用异常处理后,它工作正常。还是谢谢。
        • 是的,肯定有帮助。
        【解决方案5】:

        这个方法的响应应该是float String rating = recipelist.get(position).getRatings();或者要在String中得到它,你必须使用@987654322将它转换成String@这就是你得到NumberFormatException的原因

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多