0

在我的應用程序中,我在listview中顯示數據。滾動瀏覽ListView我的應用程序崩潰。我應該做什麼改變?應用程序在訪問列表視圖時不斷崩潰

的錯誤給我的RecipeListFragment.java文件是:

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

的錯誤被顯示在Crashlytics是:

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) 
+0

不要在'Fragment'中直接使用'getActivity()',因爲它有時會返回'null' ..總是將活動作爲參數傳遞給構造函數。 – AndiGeeky

+0

@AndiGeeky,我應該在班上做什麼改變? –

+0

請檢查我的答案.. !! – AndiGeeky

回答

1

請不要直接在Fragment使用getActivity()因爲有時返回null ..

始終通過activity作爲構造函數中的參數.. !!

請使用以下方法來創建你的Fragment並使用activity引用,而不是getActivity() ..

public static AboutFragment newInstance(Activity activity) { 
     AboutFragment aboutFragment = new AboutFragment(); 
     aboutFragment.mActivity = activity; 
     return aboutFragment; 
    } 

希望這將有助於。

謝謝.. !!