从framgent调用分离的asynctask类

时间:2017-05-05 09:05:04

标签: android mysql android-fragments android-asynctask

我有一个包含回收者视图的片段,我调用asynctask将文件从mysql加载到recyclerview,我首先尝试它的活动它没有问题,但是当我用片段替换它时,它没有'在这里工作我的文件:

BackgroundTask.class

  package com.example.harry.recylcerviewdyn;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
 * Created by FairDz on 19/04/2017.
 */
public class BackgroundTask extends AsyncTask<Void,Promotion,Void>
{
    Context ctx;
    Activity activity;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<Promotion> arrayList= new ArrayList<>();
    public BackgroundTask(Context ctx)
    {
        this.ctx = ctx;
        activity = (Activity) ctx;
    }
    String json_string ="http://10.0.2.2/promotion_info/get_promotion_details.php";
    @Override
    protected void onPreExecute()
    {
       recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(ctx);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        adapter = new RecyclerAdapter(arrayList,ctx);
        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++;
                Promotion promotion = new Promotion(JO.getInt("id"),JO.getString("nom_supermarche"),JO.getString("logo_supermarche"),JO.getString("nom_produit"),JO.getString("logo_produit"),JO.getDouble("prix"),JO.getDouble("promotion_prix"),JO.getString("description"));
                publishProgress(promotion);
            }
            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(Promotion... values) {
        arrayList.add(values[0]);
        adapter.notifyDataSetChanged();
    }
}

Fragment.class

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_test, container, false);

        BackgroundTask backgroundTask = new BackgroundTask(getActivity());
        backgroundTask.execute();
        return view;
    }

我在网站上搜索问题,我找到了一些解决方案,它对我的​​项目无效,比如在framgen类中直接实现asynctask

5 个答案:

答案 0 :(得分:1)

活动时

# -*- coding: utf-8 -*-
import urllib.request
from bs4 import BeautifulSoup

def getHTML(st):
    with urllib.request.urlopen(site+'/',timeout=100) as response:
        return response.read() 

site = 'http://www.e-radio.gr'
soup = BeautifulSoup(getHTML(site), 'html.parser')
# Parse Main Page And get links
lst = list()

for a in soup.body.find_all('a', {'class' : 'erplayer'}):
    item = a.get('href')
    if site in item:
        lst.append(item)
    else:
        lst.append(site + item)

print("\n".join(lst))

片段

 recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);

好方法

删除此行 recyclerView = (RecyclerView)ctx.findViewById(R.id.recyclerView);

答案 1 :(得分:0)

尝试在 onActivityCreated

中调用 AsyncTask
@Override
public void onActivityCreated(Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   new AsyncTask().execute();
}

答案 2 :(得分:0)

registry.enableSimpleBroker("/app", "/topic");
registry.setApplicationDestinationPrefixes("/app", "/topic");

而不是

backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

答案 3 :(得分:0)

你不应该这样乱 - AsyncTask负责在后台执行任务,不包括任何UI小部件依赖 - 当操作时间太长而Activity关闭时会导致内存泄漏。

答案 4 :(得分:0)

不要在后执行中使用recycleler视图。尝试使用回调接口发送ArrayList返回活动,并在不影响视图的活动或片段中实现该接口,并在create视图中设置适配器,仅在回调后使用  adapter.notifyDataSetChanged();。  列表将被刷新,新数据将填充。