使用异步任务列出片段中的视图

时间:2017-09-19 09:33:38

标签: java android json listview android-fragments

my error log 我试图在我的片段中加载列表视图。但是我的应用程序在单击按钮以填充列表视图时崩溃了。我不知道我做了什么错误。任何帮助都将受到赞赏。我已经尝试了大部分关于此事的东西......但没有什么效果很好。(我删除了一些代码以避免笨拙的样子)

这是我的片段代码:

public class Func extends Fragment {

    ArrayList<Flowers> flowersList = new ArrayList<Flowers>();

    String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";

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

        FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
        ListView listView=(ListView)rootView.findViewById(R.id.listView);
        listView.setAdapter(adapter);

        return rootView;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Button b = (Button)getView().findViewById(R.id.button);

        b.setOnClickListener( new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                new BackTask().execute(url);

            }

        });

    }

//我的异步任务从这里开始

 public class BackTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                Log.d("testhtt2", "test");
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                Log.d("test44", sb.toString());
                return sb.toString();

            } catch (Exception e) {
                e.printStackTrace();
                return null;

            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;

                    }
                }

                return result;
            }
        }
  @Override
        protected void onPostExecute(String s){
            try {
                JSONArray ar =new JSONArray(s);
                for (int i = 0; i < ar.length(); i++){
                    JSONObject jsonObject=ar.getJSONObject(i);
                    Flowers flowers= new Flowers();
                    flowers.setName(jsonObject.getString("NAME"));
                    flowersList.add(flowers);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

4 个答案:

答案 0 :(得分:2)

在doInBackground中返回null,然后尝试在OnPostExecute中将其解析为JSONArray。从doInBackground方法返回一个合适的String,看看是否有帮助。

答案 1 :(得分:1)

在使用getView()之前进行空检查,如

if(getView()!=null){
//Your code     
}

最好使用getview()的rootview intead初始化oncreate视图中的按钮

修改

您正在进行的网络调用必须移至doInBackground,因为它应该在后台线程中完成并获取结果。获取的结果应该添加到onPostExecute的列表中.Hope这可以帮助您

public class SampleClass extends AsyncTask<String, Void, String> {

@Override
protected void onPreExecute(){
    super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
    BufferedReader reader = null;
    String result=null;
    try {
        URL url = new URL(strings[0]);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        StringBuilder sb = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        Log.d("testhtt2", "test");
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        Log.d("test44", sb.toString());
        result= sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
        result= null;

    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                result= null;

            }
        }
        return result;
    }
}

@Override
protected void onPostExecute(String s){
    try {
        JSONArray ar =new JSONArray(s);
        for (int i = 0; i < ar.length(); i++){
            JSONObject jsonObject=ar.getJSONObject(i);
            Flowers flowers= new Flowers();
            flowers.setName(jsonObject.getString("NAME"));
            flowersList.add(flowers);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
  }
}

答案 2 :(得分:0)

试试此代码

public class Listview extends Fragment {

ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";

ListView listview;
View rootView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (rootView!= null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        rootView = inflater.inflate(R.layout.tab2, container, false);
    } catch (InflateException ignored) {
    }

    listView=(ListView)rootView.findViewById(R.id.listView);
    Button b = (Button)rootView.findViewById(R.id.button);
    b.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new BackTask().execute(url);
        }

    });
    return view;
}
private class BackTask extends AsyncTask<String,String,String>{

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... strings) {
        return null;
    }
    @Override
    protected void onPostExecute(String s){
         try {
           JSONArray ar =new JSONArray(s);
           for (int i = 0; i < ar.length(); i++){
           JSONObject jsonObject=ar.getJSONObject(i);
           Flowers flowers= new Flowers();
           flowers.setName(jsonObject.getString("NAME"));
           flowersList.add(flowers);
     }
    FlowerAdapter adapter=new FlowerAdapter(getActivity(),R.layout.flower_list_xml,flowersList);
    listView.setAdapter(adapter);

    } catch (JSONException e) {
    e.printStackTrace();
   }
    }
  }

}
}

答案 3 :(得分:0)

你可以在onViewCreated()方法中使用view而不是getView()来尝试。

  public class ListView extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab2, container, false);
    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Button b = (Button) view.findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new BackTask().execute("http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData");
        }
    });
}

private class BackTask extends AsyncTask<String, Void, String> {
    String result;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... params) {
        try {
            result = Utility.executeHttpGet(params[0]);
        } catch (Exception e) {
            Log.e("ListView", e.getMessage(), e);
        }
        return result;
    }
    @Override
    protected void onPostExecute(String s) {
        try {
            JSONArray ar = new JSONArray(s);
            for (int i = 0; i < ar.length(); i++) {
                JSONObject jsonObject = ar.getJSONObject(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

}