无法在扩展片段的类中执行AsyncTask

时间:2016-03-08 06:44:18

标签: java android android-fragments android-asynctask android-recyclerview

我的AsyncTask,RecyclerAdapter和RecycleViewHolder类在不扩展片段的活动中工作得非常好。但每当我尝试在片段类中执行AsyncTask时,我得到的只是一个IDE红旗(无法访问的Statement)。有人帮我了解如何在一个片段中执行AsyncTask(我使用的是Android工作室1.5.1。我搜索了答案,但失败了,但得到了一个令我满意的。下面是我的代码.-谢谢。

public class TabFragmentNews extends Fragment {
    private static final String ARG_EXAMPLE = "this_is_a_constant";
    private String example_data;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_news, container, false);

       //Executing The Async Task Class Here
        newsupdate();

    }
    //Method For Executing The Async Task
    public void newsupdate() {
           BackgroundTask backgroundTask = new BackgroundTask(getActivity());
            backgroundTask.execute();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        example_data = getArguments().getString(ARG_EXAMPLE);
        Log.i("Fragment created with ", example_data);
    }

    public static TabFragmentNews newInstance(String example_argmument) {
        TabFragmentNews tabFragmentNews = new TabFragmentNews();
        Bundle args = new Bundle();
        args.putString(ARG_EXAMPLE, example_argmument);
        tabFragmentNews.setArguments(args);
        return tabFragmentNews;
    }

    //AsynTask Class for Downloading News Information
    class BackgroundTask extends AsyncTask<Void, News, Void> {

        Context ctx;
        Activity activity;
        RecyclerView recyclerView;
        RecyclerView.Adapter adapter;
        RecyclerView.LayoutManager layoutManager;
        ArrayList<News> arrayList = new ArrayList<>();

        public BackgroundTask(Context ctx) {
            this.ctx = ctx;
            activity = (Activity) ctx;
        }

        String json_string = "http://localhost/app/newtest.php";

        @Override
        protected void onPreExecute() {
            recyclerView = (RecyclerView) activity.findViewById(R.id.news);
            layoutManager = new LinearLayoutManager(ctx);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setHasFixedSize(true);
            adapter = new RecyclerAdapter(arrayList);
            recyclerView.setAdapter(adapter);
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                URL url = new URL(json_string);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = bufferedReader.readLine()) != null) {

                    stringBuilder.append(line + "\n");

                }
                httpURLConnection.disconnect();
                String json_string = stringBuilder.toString().trim();
                JSONObject jsonObject = new JSONObject(json_string);
                JSONArray jsonArray = jsonObject.getJSONArray("server_response");
                int count = 0;
                while (count < jsonArray.length()) {

                    JSONObject JO = jsonArray.getJSONObject(count);
                    count++;
                    News news = new News(JO.getString("details"));
                    publishProgress(news);
                }

                Log.d("JSON STRING", json_string);

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

        @Override
        protected void onProgressUpdate(News... values) {
            arrayList.add(values[0]);
            adapter.notifyDataSetChanged();
        }
    }

    //RecyclerAdapter Class for populating recycler view with Information
    class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {

        ArrayList<News> arrayList = new ArrayList<>();

        public static final int TYPE_HEAD = 0;
        public static final int TYPE_LIST = 1;

        public RecyclerAdapter(ArrayList<News> arrayList) {
            this.arrayList = arrayList;

        }

        @Override
        public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            if (viewType == TYPE_HEAD) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_header, parent, false);
                RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, viewType);
                return recyclerViewHolder;
            } else if (viewType == TYPE_LIST) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_row_layout, parent, false);
                RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, viewType);
                return recyclerViewHolder;
            }

            return null;
        }

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

            if (holder.viewType == TYPE_LIST) {
                final News news = arrayList.get(position - 1);
                holder.Details.setText(news.getDetails());
            }

        }

        @Override
        public int getItemCount() {
            return arrayList.size() + 1;
        }


        //Recycler View Holder Class
        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            TextView Details;
            int viewType;

            public RecyclerViewHolder(View view, int viewType) {
                super(view);

                if (viewType == TYPE_LIST) {

                    Details = (TextView) itemView.findViewById(R.id.team);

                    this.viewType = TYPE_LIST;
                } else if (viewType == TYPE_HEAD) {
                    this.viewType = TYPE_HEAD;
                }

            }
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0)
                return TYPE_HEAD;
            return TYPE_LIST;
        }
    }

}

这是新闻信息类:

public class News {
    private String details;

    public News(String details)
    {
        this.setDetails(details);
    }

    public String getDetails()
    {

        return details;
    }

    public void setDetails(String details)
    {
        this.details = details;
    }

}

我在执行AsyncTask- newsupdate();

的公共视图onCreateView中得到一个红旗(无法访问的语句)

2 个答案:

答案 0 :(得分:4)

问题出在您的onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

只需像这样改变你的onCreateView ..

<强>解决方案:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   //Executing The Async Task Class Here
    newsupdate();
    return inflater.inflate(R.layout.fragment_news, container, false);
}

<强>更新

public class TabFragmentNews extends Fragment {
     private static final String ARG_EXAMPLE = "this_is_a_constant";
     private String example_data;
     private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_news, container, false);

    recyclerView = (RecyclerView) view.findViewById(R.id.news);

    //Executing The Async Task Class Here
    newsupdate();
    return view;
}

//Method For Executing The Async Task
public void newsupdate() {
       //BackgroundTask backgroundTask = new BackgroundTask(getActivity());
       //backgroundTask.execute();
       new BackgroundTask(getActivity()).execute();
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    example_data = getArguments().getString(ARG_EXAMPLE);
    Log.i("Fragment created with ", example_data);
}

public static TabFragmentNews newInstance(String example_argmument) {
    TabFragmentNews tabFragmentNews = new TabFragmentNews();
    Bundle args = new Bundle();
    args.putString(ARG_EXAMPLE, example_argmument);
    tabFragmentNews.setArguments(args);
    return tabFragmentNews;
}

//AsynTask Class for Downloading News Information
class BackgroundTask extends AsyncTask<Void, News, Void> {

    Context ctx;
    Activity activity;
    //RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<News> arrayList = new ArrayList<>();

    public BackgroundTask(Context ctx) {
        this.ctx = ctx;
        activity = (Activity) ctx;
    }

    String json_string = "http://localhost/app/newtest.php";

    @Override
    protected void onPreExecute() {
        //recyclerView = (RecyclerView) activity.findViewById(R.id.news);
        layoutManager = new LinearLayoutManager(ctx);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        adapter = new RecyclerAdapter(arrayList);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            URL url = new URL(json_string);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            httpURLConnection.disconnect();
            String json_string = stringBuilder.toString().trim();
            JSONObject jsonObject = new JSONObject(json_string);
            JSONArray jsonArray = jsonObject.getJSONArray("server_response");
            int count = 0;
            while (count < jsonArray.length()) {
                JSONObject JO = jsonArray.getJSONObject(count);
                count++;
                News news = new News(JO.getString("details"));
                publishProgress(news);
            }

            Log.d("JSON STRING", json_string);

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

    @Override
    protected void onProgressUpdate(News... values) {
        arrayList.add(values[0]);
        adapter.notifyDataSetChanged();
    }
}

//RecyclerAdapter Class for populating recycler view with Information
class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {

    ArrayList<News> arrayList = new ArrayList<>();

    public static final int TYPE_HEAD = 0;
    public static final int TYPE_LIST = 1;

    public RecyclerAdapter(ArrayList<News> arrayList) {
        this.arrayList = arrayList;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEAD) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_header, parent, false);
            RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, viewType);
            return recyclerViewHolder;
        } else if (viewType == TYPE_LIST) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_row_layout, parent, false);
            RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, viewType);
            return recyclerViewHolder;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, final int position) {
        if (holder.viewType == TYPE_LIST) {
            final News news = arrayList.get(position - 1);
            holder.Details.setText(news.getDetails());
        }
    }

    @Override
    public int getItemCount() {
        return arrayList.size() + 1;
    }

    //Recycler View Holder Class
    class RecyclerViewHolder extends RecyclerView.ViewHolder {
        TextView Details;
        int viewType;

        public RecyclerViewHolder(View view, int viewType) {
            super(view);
            if (viewType == TYPE_LIST) {
                Details = (TextView) itemView.findViewById(R.id.team);
                this.viewType = TYPE_LIST;
            } else if (viewType == TYPE_HEAD) {
                this.viewType = TYPE_HEAD;
            }

        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0)
            return TYPE_HEAD;
        return TYPE_LIST;
    }
  }
}

答案 1 :(得分:0)

只是这样做。

//Method For Executing The Async Task
public void newsupdate() {
    new BackgroundTask().execute();
}