MilkaMozhi
MilkaMozhi

Reputation: 83

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

Upvotes: 0

Views: 538

Answers (4)

Sharath kumar
Sharath kumar

Reputation: 4132

Do a null check before using getView() like

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

Also it is better to initialize the button in oncreate view using the rootview intead of getview()

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

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

Upvotes: 1

Ramesh Yogu
Ramesh Yogu

Reputation: 135

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

}
}

Upvotes: 0

Daya Shankar
Daya Shankar

Reputation: 111

you can try with view insteadof getView() in onViewCreated() method.

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

}

Upvotes: 0

Andreas Engedal
Andreas Engedal

Reputation: 801

You return null in your doInBackground, which you then attempt to parse as a JSONArray in your OnPostExecute. Return a proper String from your doInBackground method, and see if that helps.

Upvotes: 2

Related Questions