Question

This error shows up when i do this:

This is in the MainActivity:

ListView lv = ((ListFragment) getActivity()).getListView();

but if I don't cast it to that the app crashes and I get

01-02 22:35:00.285: E/AndroidRuntime(17289): FATAL EXCEPTION: main
01-02 22:35:00.285: E/AndroidRuntime(17289): Process: com.titanhash.teamdoge, PID: 17289
01-02 22:35:00.285: E/AndroidRuntime(17289): java.lang.IllegalStateException: Content view not yet created
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at com.titanhash.teamdoge.WorkersFragment.onCreate(WorkersFragment.java:70)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.view.Choreographer.doCallbacks(Choreographer.java:574)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.view.Choreographer.doFrame(Choreographer.java:543)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.os.Handler.handleCallback(Handler.java:733)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.os.Looper.loop(Looper.java:136)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at android.app.ActivityThread.main(ActivityThread.java:5081)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at java.lang.reflect.Method.invokeNative(Native Method)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at java.lang.reflect.Method.invoke(Method.java:515)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-02 22:35:00.285: E/AndroidRuntime(17289):    at dalvik.system.NativeStart.main(Native Method)

I will post the rest of the code If you guys need it. Ooh also I am calling the list fragment from the MainActivity with:

This is in the MainActivity

case 3:
return WorkersFragment.newInstance("Workers");

And the ListFragment instance:

This is in the ListFragment

public static WorkersFragment newInstance(String text) {
    WorkersFragment pageFragment = new WorkersFragment();

    return pageFragment;
}

Thanks for the help ahead of time!

BIG - EDIT:

Here is the activity code:

package com.titanhash.teamdoge;

import java.util.Locale;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class SuchActivity extends FragmentActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_such);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.such, menu);
    return true;
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
        case 0:
            return TeamdogeFragment.newInstance("Teamdoge");
        case 1:
            return PoolFragment.newInstance("Pool");
        case 2:
            return UserFragment.newInstance("User");
        case 3:
            return WorkersFragment.newInstance("Workers");
        }
        return TeamdogeFragment.newInstance("Teamdoge");

    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        case 3:
            return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }
}
}

Here is the ListFragment code:

package com.titanhash.teamdoge;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.support.v4.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class WorkersFragment extends ListFragment {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "";

    // JSON Node names
    private static final String TAG_DASHDATA = "getdashboarddata";
    private static final String TAG_DATA = "data";
    private static final String TAG_PERSONAL = "personal";
    private static final String TAG_WORKERS = "workers";
    private static final String TAG_ID = "id";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_HASHRATE = "hashrate";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";

    // contacts JSONArray
        JSONArray workers = null;

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList;

    public static WorkersFragment newInstance(String text) {
        WorkersFragment pageFragment = new WorkersFragment();

        return pageFragment;
    }

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

        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email))
                        .getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile))
                        .getText().toString();

                // Starting single contact activity
                Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
                in.putExtra(TAG_ID, name);
                in.putExtra(TAG_USERNAME, cost);
                in.putExtra(TAG_HASHRATE, description);
                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            //pDialog = new ProgressDialog(SuchActivity.this);
            //pDialog.setMessage("Please wait...");
            //pDialog.setCancelable(false);
            //pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            JSONObject jsonObject;

            if (jsonStr != null) {
                try {
                    //JSONObject jsonObj2 = new JSONObject(jsonStr);

                    // Get the root JSONObject
                    jsonObject = new JSONObject(jsonStr);

                    // Get the JSON object named query
                    //JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
                    JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");

                    // Get the JSON object named results inside of the query object
                    //JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
                    JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");

                    // Get the JSON object named quote inside of the results object
                    JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");

                    // Getting JSON Array node
                    workers = personalJSONObject.getJSONArray(TAG_WORKERS);

                    // looping through All Contacts
                    for (int i = 0; i < workers.length(); i++) {
                        JSONObject c = workers.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_USERNAME);
                        String email = c.getString(TAG_HASHRATE);
                        //String address = workers.getString(TAG_ADDRESS);
                        //String gender = workers.getString(TAG_GENDER);

                        // Phone node is JSON Object
                        //JSONObject phone = c.getJSONObject(TAG_PHONE);
                        //String mobile = phone.getString(TAG_PHONE_MOBILE);
                        //String home = phone.getString(TAG_PHONE_HOME);
                        //String office = phone.getString(TAG_PHONE_OFFICE);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, "ID: " + id);
                        contact.put(TAG_USERNAME, name);
                        contact.put(TAG_HASHRATE, email + " kH/s");
                        //contact.put(TAG_PHONE_MOBILE, mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), contactList,
                    R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
                            TAG_HASHRATE }, new int[] { R.id.name,
                            R.id.email, R.id.mobile });

            setListAdapter(adapter);
        }

    }


}

ANOTHER EDIT:

package com.titanhash.teamdoge;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class WorkersFragment extends ListFragment {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://teamdoge.com/index.php?page=api&action=getdashboarddata&api_key=5a0a4793431873828540ae6ddad556075b169180d5b16023a41daec8530b890f&id=2317";

// JSON Node names
private static final String TAG_DASHDATA = "getdashboarddata";
private static final String TAG_DATA = "data";
private static final String TAG_PERSONAL = "personal";
private static final String TAG_WORKERS = "workers";
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_HASHRATE = "hashrate";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
    JSONArray workers = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

public static WorkersFragment newInstance(String text) {
    WorkersFragment pageFragment = new WorkersFragment();

    return pageFragment;
}

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

    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    contactList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
            in.putExtra(TAG_ID, name);
            in.putExtra(TAG_USERNAME, cost);
            in.putExtra(TAG_HASHRATE, description);
            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        //pDialog = new ProgressDialog(SuchActivity.this);
        //pDialog.setMessage("Please wait...");
        //pDialog.setCancelable(false);
        //pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        JSONObject jsonObject;

        if (jsonStr != null) {
            try {
                //JSONObject jsonObj2 = new JSONObject(jsonStr);

                // Get the root JSONObject
                jsonObject = new JSONObject(jsonStr);

                // Get the JSON object named query
                //JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
                JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");

                // Get the JSON object named results inside of the query object
                //JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
                JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");

                // Get the JSON object named quote inside of the results object
                JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");

                // Getting JSON Array node
                workers = personalJSONObject.getJSONArray(TAG_WORKERS);

                // looping through All Contacts
                for (int i = 0; i < workers.length(); i++) {
                    JSONObject c = workers.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_USERNAME);
                    String email = c.getString(TAG_HASHRATE);
                    //String address = workers.getString(TAG_ADDRESS);
                    //String gender = workers.getString(TAG_GENDER);

                    // Phone node is JSON Object
                    //JSONObject phone = c.getJSONObject(TAG_PHONE);
                    //String mobile = phone.getString(TAG_PHONE_MOBILE);
                    //String home = phone.getString(TAG_PHONE_HOME);
                    //String office = phone.getString(TAG_PHONE_OFFICE);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, "ID: " + id);
                    contact.put(TAG_USERNAME, name);
                    contact.put(TAG_HASHRATE, email + " kH/s");
                    //contact.put(TAG_PHONE_MOBILE, mobile);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                getActivity(), contactList,
                R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
                        TAG_HASHRATE }, new int[] { R.id.name,
                        R.id.email, R.id.mobile });

        setListAdapter(adapter);
    }

}


}
Was it helpful?

Solution 2

java.lang.IllegalStateException:Content view not yet created

Move the code in onCreate to onActivityCreated. Override onActivityCreated.

Edit:

public class WorkersFragment extends Fragment {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://teamdoge.com/index.php?page=api&action=getdashboarddata&api_key=5a0a4793431873828540ae6ddad556075b169180d5b16023a41daec8530b890f&id=2317";

    // JSON Node names
    private static final String TAG_DASHDATA = "getdashboarddata";
    private static final String TAG_DATA = "data";
    private static final String TAG_PERSONAL = "personal";
    private static final String TAG_WORKERS = "workers";
    private static final String TAG_ID = "id";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_HASHRATE = "hashrate";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    JSONArray workers = null;
    ListView lv;
    ArrayList<HashMap<String, String>> contactList;

    public static WorkersFragment newInstance(String text) {
        WorkersFragment pageFragment = new WorkersFragment();

        return pageFragment;
    }

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

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        lv = (ListView) getView().findViewById(R.id.listView1); 
        contactList = new ArrayList<HashMap<String, String>>();

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.textView1))
                        .getText().toString();
                String cost = ((TextView) view.findViewById(R.id.textView2))
                        .getText().toString();
                String description = ((TextView) view.findViewById(R.id.textView3))
                        .getText().toString();

                // Starting single contact activity
//                Intent in = new Intent(getActivity().getApplicationContext(),SingleContactActivity.class);
//                in.putExtra(TAG_ID, name);
//                in.putExtra(TAG_USERNAME, cost);
//                in.putExtra(TAG_HASHRATE, description);
//                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }



    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog

            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            try
           {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGet request = new HttpGet(url);
            // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");     

            HttpResponse response = httpclient.execute(request);
            HttpEntity resEntity = response.getEntity();
            String _response=EntityUtils.toString(resEntity);
            if (_response!= null) {

                    //JSONObject jsonObj2 = new JSONObject(jsonStr);

                    // Get the root JSONObject
                    JSONObject jsonObject = new JSONObject(_response);

                    // Get the JSON object named query
                    //JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getpoolstatus");
                    JSONObject getpoolstatusJSONObject = jsonObject.getJSONObject("getdashboarddata");

                    // Get the JSON object named results inside of the query object
                    //JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");
                    JSONObject dataJSONObject = getpoolstatusJSONObject.getJSONObject("data");

                    // Get the JSON object named quote inside of the results object
                    JSONObject personalJSONObject = dataJSONObject.getJSONObject("personal");
                   workers = personalJSONObject.getJSONArray(TAG_WORKERS);


                    for (int i = 0; i < workers.length(); i++) {
                        JSONObject c = workers.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_USERNAME);
                        String email = c.getString(TAG_HASHRATE);
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, "ID: " + id);
                        contact.put(TAG_USERNAME, name);
                        contact.put(TAG_HASHRATE, email + " kH/s");

                        contactList.add(contact); 
                 }
             }
             }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), contactList,
                    R.layout.list_item, new String[] { TAG_ID, TAG_USERNAME,
                            TAG_HASHRATE }, new int[] { R.id.textView1,
                            R.id.textView2, R.id.textView3});

            lv.setAdapter(adapter);
        }

    }
}

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="33dp"
        android:layout_marginTop="40dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignParentRight="true"
        android:layout_marginRight="26dp"
        android:text="TextView" />

</RelativeLayout>

wokers_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >

    </ListView>

</RelativeLayout>

Snap

enter image description here

OTHER TIPS

You can't cast the Activity to a Fragment; they are completely different, and you are already inside the Fragment instance.

You can't call the getList() method from onCreate(), because the Views aren't initialized at this point; you should move that logic to onViewCreated() instead.

You can't do this: ((ListFragment) getActivity()).getListView();

The ListView you're looking for is in the ListFragment you are hosting in that Activity.

Time to go back to school…

Please review the documentation for a ListFragment, an Activity and how to communicate between Fragments (and Activities).

The answer is there and it will help you understand the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top