在异步任务的onPostExecute中获取错误

时间:2016-05-20 06:45:16

标签: android sqlite android-asynctask fragment

您好我从服务器获取数据并存储在sqlite中并显示内部滑动选项卡是动态的。我有时会收到错误,有时候它会正常工作。我不明白为什么会发生崩溃。我试图调试但找不到问题。需要帮助来解决这个问题。

这里是异步任务代码。

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> implements
        OnClickListener {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {
            // ------------------>>
            URL url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            /* optional request header */
            urlConnection.setRequestProperty("Content-Type",
                    "application/json");

            /* optional request header */
            urlConnection.setRequestProperty("Accept", "application/json");

            /* for Get request */
            urlConnection.setRequestMethod("GET");
            int statusCode = urlConnection.getResponseCode();

            if (statusCode == 200) {
                inputStream = new BufferedInputStream(
                        urlConnection.getInputStream());
                String response = convertInputStreamToString(inputStream);

                JSONObject jsono = new JSONObject(response);
                JSONArray jarray = jsono.getJSONArray("product");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject feedObj = jarray.getJSONObject(i);

                    // Actors actor = new Actors();
                    CartItem item = new CartItem();
                    item.setQuantity("0");
                    item.setProductName(feedObj.optString("post_title"));
                    item.setPrice(feedObj.optString("post_excerpt"));
                    item.setProductPrice(feedObj.optString("meta_value"));
                    item.setProductId(ids);
                    item.setProdId(feedObj.optString("ID"));
                    item.setProductTotalPrice("0");
                    item.setImage(feedObj.optString("image_url"));
                    mHelper.addProduct(item);
                   System.out.println("Database price : "+item.getProductPrice());

                }

                return true;
            }

            // ------------------>>

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {

        if (result == false) {
            recyclerView.setVisibility(View.GONE);
            fhfgh.setVisibility(View.VISIBLE);

        } else {

            listAdapter = new FeedListAdapter(getActivity(), mHelper.getAllProducts(ids));// Error on this line.
            recyclerView.setAdapter(listAdapter);
            listAdapter.setOnAddNum(this);
            listAdapter.setOnSubNum(this);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(
                    getActivity()));

        }

    }

这是logcat

05-20 12:08:26.308: E/AndroidRuntime(8564): FATAL EXCEPTION: main
05-20 12:08:26.308: E/AndroidRuntime(8564): java.lang.NullPointerException
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.grotap.adapter.FeedListAdapter.<init>(FeedListAdapter.java:47)
05-20 12:08:26.308: E/AndroidRuntime(8564): at   com.grotap.activity.MyFragment$JSONAsyncTask.onPostExecute(MyFragment.java:350)
05-20 12:08:26.308: E/AndroidRuntime(8564): at com.grotap.activity.MyFragment$JSONAsyncTask.onPostExecute(MyFragment.java:1)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.AsyncTask.finish(AsyncTask.java:631)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-20 12:08:26.308: E/AndroidRuntime(8564): at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at android.os.Looper.loop(Looper.java:137)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at android.app.ActivityThread.main(ActivityThread.java:5283)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at java.lang.reflect.Method.invokeNative(Native Method)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at java.lang.reflect.Method.invoke(Method.java:511)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-20 12:08:26.308: E/AndroidRuntime(8564):     at  dalvik.system.NativeStart.main(Native Method)

这是适配器类

public class FeedListAdapter extends
    RecyclerView.Adapter<FeedListAdapter.ViewHolder> {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<CartItem> feedItems;
private ArrayList<CartItem> filteredfeedItems;
ImageView plus;
ImageView minus;
String result;
String formattedDate;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int id;
private TextView prices;
private View.OnClickListener onAddNum;
private View.OnClickListener onSubNum;

public FeedListAdapter(Activity activity, ArrayList<CartItem> feedItems) {
    this.activity = activity;
    this.feedItems = feedItems;
    this.filteredfeedItems = feedItems;

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public void setOnAddNum(View.OnClickListener onAddNum) {
    this.onAddNum = onAddNum;
}

public void setOnSubNum(View.OnClickListener onSubNum) {
    this.onSubNum = onSubNum;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(
            R.layout.feed_item, parent, false);
    prices = (TextView) v.findViewById(R.id.timestamp2);
    ViewHolder viewHolder = new ViewHolder(v);
     if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
    // setupClickableViews(v, viewHolder);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    CartItem item = (CartItem) filteredfeedItems.get(position);
    holder.name.setText(item.getProductName());
    holder.assignTo.setText(item.getPrice());
     String rupee = activity.getResources().getString(R.string.Rs);
    holder.price.setText(rupee+" "+item.getProductPrice());
    holder.location.setText((String.valueOf(item.getQuantity())) + "");
    holder.plus.setTag(item.getId());
    holder.plus.setFocusable(true);
    holder.plus.setClickable(true);
    holder.plus.setOnClickListener(onAddNum);
    holder.minus.setTag(item.getId());
    holder.minus.setOnClickListener(onSubNum);
    holder.profilePic.setImageUrl(item.getImage(), imageLoader);
    holder.profilePic.setDefaultImageResId(R.mipmap.ic_launcher);
    holder.profilePic.setErrorImageResId(R.mipmap.ic_launcher);
    //Picasso.with(activity).load(item.getImage()).into(holder.profilePic);
}

/*private void displayImage(int adapterPosition) {
    // TODO Auto-generated method stub
   LayoutInflater inflater = activity.getLayoutInflater();

    View offer = inflater.inflate(R.layout.prompts, null);



    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
       alert.setView(offer);
       alert.setCancelable(true);


      final AlertDialog dialog = alert.create();
      int width = (int)(activity.getResources().getDisplayMetrics().widthPixels*0.80);
      int height = (int)(activity.getResources().getDisplayMetrics().heightPixels*0.50);
      dialog.show();
      dialog.getWindow().setLayout(width, height); 
      dialog.setCanceledOnTouchOutside(true);
      dialog.setCancelable(true);

      CartItem item = (CartItem) filteredfeedItems.get(adapterPosition);

      NetworkImageView viewOffer = (NetworkImageView)offer.findViewById(R.id.viewOffer);
      viewOffer.setImageUrl(item.getImage(),imageLoader);

       viewOffer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
}*/

@Override
public int getItemCount() {
    return filteredfeedItems.size();
}

public long getItemId(int position) {
    return position;

}

class ViewHolder extends RecyclerView.ViewHolder {

    ImageView plus;
    ImageView minus;
    NetworkImageView profilePic;
    TextView name;
    TextView price;
    TextView assignTo;
    TextView location;

    public ViewHolder(View vi) {
        super(vi);

        name = (TextView) vi.findViewById(R.id.name);
        price = (TextView) vi.findViewById(R.id.price);
        assignTo = (TextView) vi.findViewById(R.id.timestamp);

        location = (TextView) vi.findViewById(R.id.timestamp2);
        plus = (ImageView) vi.findViewById(R.id.btnAddToCart1);
        profilePic = (NetworkImageView) vi.findViewById(R.id.profilePic);
        minus = (ImageView) vi.findViewById(R.id.btnAddToCart5);

    }
}

}

这是getAllProducts

     public ArrayList<CartItem> getAllProducts(String ids) {

      SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<CartItem> cityList = null;
        try{
            cityList = new ArrayList<CartItem>();
            String QUERY = "SELECT * FROM "+TABLE_NAME+ " WHERE " +KEY_PRODUCT_ID
                    + " = '" + ids + "'";
            Cursor cursor = db.rawQuery(QUERY, null);
            if(!cursor.isLast())
            {
                while (cursor.moveToNext())
                {
                    CartItem city = new CartItem();
                    city.setId(cursor.getInt(0));
                    city.setQuantity(cursor.getString(1));
                    city.setProductName(cursor.getString(2));
                    city.setPrice(cursor.getString(3));
                    city.setProductPrice(cursor.getString(4));
                    city.setProductId(cursor.getString(5));
                    city.setProductTotalPrice(cursor.getString(6));
                    city.setImage(cursor.getString(7));
                    city.setProdId(cursor.getString(8));
                    cityList.add(city);
                }
            }
            db.close();
        }catch (Exception e){
            Log.e("error",e+"");
        }
        return cityList;


}

1 个答案:

答案 0 :(得分:1)

onPostExecute()方法中,您拨打getActivity()。此方法返回null,因为您的片段尚未附加到活动。确保仅在片段调用getActivity()后才能调用onAttach()