0
我的代碼實際上是從一個活動的recyclerview,現在我希望它在一個片段上實現..但是當它將啓動主要的片段應用程序崩潰..是它使用這些相同類型的代碼可以這樣做嗎?我想用一個片段實現我的recyclerview使用asynctask
主要碎片
public class MainFragment extends Fragment {
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
backgroundTask.execute();
return inflater.inflate(R.layout.main_fragment_layout, container, false);
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<Void, Products, Void> {
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Products> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string="http://192.168.0.18/project/json_get_data.php";
@Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recycleView);
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++;
Products products = new Products(JO.getString("name"), JO.getString("type"),JO.getString("price"));
publishProgress(products);
}
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(Products... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
預先感謝您..
我解決了我的問題,通過將後臺任務移動到onStart()...謝謝你,問題已經解決了 – Franzen