简体   繁体   English

带有异步任务的片段中的列表视图

[英]List view in fragment with Async Task

my error log I tried to load list view in my fragment.But my app crashes on clicking the button to populate my listview. 我的错误日志我试图在片段中加载列表视图。但是我的应用程序在单击按钮填充列表视图时崩溃。 I don't know what error i did.Any help will be appreciated. 我不知道我做了什么错误。任何帮助将不胜感激。 I have tried most of the stuffs regarding this..But nothing works well .(i have removed some codes to avoid clumsy look) 我已经尝试了大多数与此有关的东西。但是没有什么效果很好 。(我删除了一些代码以避免笨拙的外观)

Here is my Fragment code : 这是我的片段代码:

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);

            }

        });

    }

// My Async task starts here //我的异步任务从这里开始

 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();
            }

You return null in your doInBackground, which you then attempt to parse as a JSONArray in your OnPostExecute. 您在doInBackground中返回null,然后尝试在OnPostExecute中将其解析为JSONArray。 Return a proper String from your doInBackground method, and see if that helps. 从doInBackground方法返回正确的String,看看是否有帮助。

Do a null check before using getView() like 在像使用getView()之前做一个空检查

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

Also it is better to initialize the button in oncreate view using the rootview intead of getview() 另外最好使用getview()的rootview intead在oncreate视图中初始化按钮。

EDIT : 编辑

Your network call which your are doing has to be moved to doInBackground as it should be done in background thread and fetch the result.The fetched result should be added to the list in onPostExecute.Hope this helps you 您正在进行的网络调用必须移至doInBackground,因为它应该在后台线程中完成并获取结果。获取的结果应添加到onPostExecute的列表中。希望这对您有所帮助

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();
    }
  }
}

Try this code 试试这个代码

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();
   }
    }
  }

}
}

you can try with view insteadof getView() in onViewCreated() method. 您可以在onViewCreated()方法中尝试使用视图代替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();
        }
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM