Raja Sekhar
Raja Sekhar

Reputation: 67

How to populate ListView in a fragment from PHP JSON data?

I have a fragment (homePageFrag) containing a ListView . When I'm trying to populate it using JSON data from a URL, it's not working. The ListView is being empty. However, it is showing up when I'm giving static data from an ArrayList.

What I want to achieve is populating the ListView inside a Fragment from JSON data obtained from a URL. The HP_JSON_Download is working as intended was I'm using a ListView in a Activity, but in the fragment, its not showing up any data.

homePageFrag.java

public class homePageFrag extends Fragment implements HP_JSON_Download.download_complete {

    boolean open = false;  Context applicationContext;

    public ListView list;
    public ArrayList<HPEntity> countries = new ArrayList<HPEntity>();
    public HP_ListAdapter adapter;

    private final String bus_id[] = {"a1"};
    private final String bus_destination[] = {"A1"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file

        View view = inflater.inflate(R.layout.homepage_lv, container, false);

        list = (ListView) view.findViewById(R.id.homepageListView);
        adapter = new HP_ListAdapter(this);
        list.setAdapter(adapter);

        HP_JSON_Download download_data = new HP_JSON_Download((HP_JSON_Download.download_complete) this);
        download_data.download_data_from_link("http://www.xyz.in/MyApi/Api.php");

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("E-RTC");
    }

    public void get_data(String data) {
        Toast.makeText(getApplicationContext(),"xx",Toast.LENGTH_SHORT).show();

        try {
            JSONArray data_array=new JSONArray(data);

            for (int i = 0 ; i < data_array.length() ; i++) {
                JSONObject obj=new JSONObject(data_array.get(i).toString());

                HPEntity add=new HPEntity();
                add.name = obj.getString("id");
                add.code = obj.getString("name");

                countries.add(add);
            }

            adapter.notifyDataSetChanged();

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

    public Context getApplicationContext() {
        return applicationContext;
    }
}

HP_ListAdapter.java

public class HP_ListAdapter  extends BaseAdapter {

    homePageFrag main;

    Context mContext;
    public HP_ListAdapter(Context mContext) {
        this.mContext = mContext;
    }

    HP_ListAdapter(homePageFrag main) {
        this.main = main;
    }

    @Override
    public int getCount() {
        return  main.countries.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    static class ViewHolderItem {
        TextView name;
        TextView code;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolderItem holder = new ViewHolderItem();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.homepage_item, null);

            holder.name = (TextView) convertView.findViewById(R.id.busID);
            holder.code = (TextView) convertView.findViewById(R.id.busNAME);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolderItem) convertView.getTag();
        }

        holder.name.setText(this.main.countries.get(position).name);
        holder.code.setText(this.main.countries.get(position).code);

        return convertView;
    }
}

HPEntity.java

public class HPEntity {
    String name;
    String code;
}

HP_JSON_Download.java

public class HP_JSON_Download  implements  Runnable  {

    public download_complete caller;

    public interface download_complete {
         void get_data(String data);
    }

    HP_JSON_Download(download_complete caller) {
        this.caller = caller;
    }

    private String link;
    public void download_data_from_link(String link) {
        this.link = link;
        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        threadMsg(download(this.link));
    }

    private void threadMsg(String msg) {
        if (!msg.equals(null) && !msg.equals("")) {
            Message msgObj = handler.obtainMessage();
            Bundle b = new Bundle();
            b.putString("message", msg);
            msgObj.setData(b);
            handler.sendMessage(msgObj);
        }
    }

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            String Response = msg.getData().getString("message");
            caller.get_data(Response);
        }
    };

    public static String download(String url) {
        URL website;
        StringBuilder response = null;
        try {
            website = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) website.openConnection();
            connection.setRequestProperty("charset", "utf-8");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));

            response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null)
                response.append(inputLine);

            in.close();

        } catch (Exception  e) {
            return "";
        }

        return response.toString();
    }
}

Upvotes: 0

Views: 94

Answers (1)

Reaz Murshed
Reaz Murshed

Reputation: 24231

I would suggest you to modify your adapter like this.

public class HP_ListAdapter  extends BaseAdapter {
    public ArrayList<HPEntity> countries = new ArrayList<HPEntity>();
    Context mContext;

    public HP_ListAdapter(Context mContext, ArrayList<HPEntity> countries) {
        this.mContext = mContext;
        this.countries = countries;
    }

    @Override
    public int getCount() {
        return  countries.size();
    }

    @Override
    public Object getItem(int position) {
        return countries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    static class ViewHolderItem {
        TextView name;
        TextView code;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolderItem holder = new ViewHolderItem();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.homepage_item, null);

            holder.name = (TextView) convertView.findViewById(R.id.busID);
            holder.code = (TextView) convertView.findViewById(R.id.busNAME);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolderItem) convertView.getTag();
        }

        holder.name.setText(this.countries.get(position).name);
        holder.code.setText(this.countries.get(position).code);

        return convertView;
    }
}

Now initialize your adapter from your onCreateView function in your Fragment like this. You are passing the wrong context to your adapter initialization by using this. You should have used getActivity() instead.

adapter = new HP_ListAdapter(getActivity(), countries);

Upvotes: 1

Related Questions