Content view not yet created

I am trying to retrieve the data from mysql and sort it based on the category tab. My application crash when i open the activity with content view not yet created. May I know what is the problem?

03-10 04:12:49.043: E/AndroidRuntime(2251): FATAL EXCEPTION: main
03-10 04:12:49.043: E/AndroidRuntime(2251): java.lang.RuntimeException: Unable to start activity ComponentInfo{my.fyp.inticlassifieds/my.fyp.inticlassifieds.DisplayPostItem}: java.lang.IllegalStateException: Content view not yet created
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.os.Looper.loop(Looper.java:137)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at java.lang.reflect.Method.invokeNative(Native Method)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at java.lang.reflect.Method.invoke(Method.java:525)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at dalvik.system.NativeStart.main(Native Method)
03-10 04:12:49.043: E/AndroidRuntime(2251): Caused by: java.lang.IllegalStateException: Content view not yet created
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at my.fyp.inticlassifieds.BooksFragment.onCreateView(BooksFragment.java:87)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at  android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.Activity.performStart(Activity.java:5143)
03-10 04:12:49.043: E/AndroidRuntime(2251):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
03-10 04:12:49.043: E/AndroidRuntime(2251):     ... 11 more

Class:

public class BooksFragment extends ListFragment {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();
JSONObject json;

ArrayList<Products> productsList = new ArrayList<Products>();

// url to get all products list
private static String url_all_products = "http://10.0.2.2:8000/project/display_items.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_BUDGET = "price";
private static final String TAG_DES = "description";
private static final String TAG_DATE_POSTED = "created_at";
private static final String TAG_CATEGORY = "category";
private static final String TAG_EMAIL = "email";
private static final String TAG_CONTACT = "contact";

// products JSONArray
JSONArray products = null;

ListView lv;
ListAdapter listadapter;


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

    productsList = new ArrayList<Products>();

    lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.des))
                    .getText().toString();
            String price = ((TextView) view.findViewById(R.id.budget))
                    .getText().toString();
            String date = ((TextView) view.findViewById(R.id.date_posted))
                    .getText().toString();
            String category = ((TextView) view.findViewById(R.id.category))
                    .getText().toString();
            String email = ((TextView) view
                    .findViewById(R.id.email_request)).getText().toString();
            String contact = ((TextView) view
                    .findViewById(R.id.contact_request)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getActivity(), DisplayItemInfo.class);
            // sending information to next activity
            in.putExtra(TAG_PID, pid);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_DES, description);
            in.putExtra(TAG_BUDGET, price);
            in.putExtra(TAG_DATE_POSTED, date);
            in.putExtra(TAG_CATEGORY, category);
            in.putExtra(TAG_EMAIL, email);
            in.putExtra(TAG_CONTACT, contact);
            startActivity(in);
        }
    });

    new LoadAllProducts().execute();
    return rootView;
}


class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Intent intent = getIntent();
        // getting attached intent data
        String jsonS = intent.getStringExtra("JSon");

        if (jsonS == null) {
            // getting JSON string from URL
            json = jParser.makeHttpRequest(url_all_products, "GET", params);
        } else {
            try {
                JSONObject Jsonobj = new JSONObject(jsonS);
                json = Jsonobj;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String budget = c.getString(TAG_BUDGET);
                    String description = c.getString(TAG_DES);
                    String category = c.getString(TAG_CATEGORY);
                    String contact = c.getString(TAG_CONTACT);
                    String email = c.getString(TAG_EMAIL);
                    String date = c.getString(TAG_DATE_POSTED);

                    if (category == "Books") {

                        // Create a new Product Obect, set its Values
                        Products mProduct = new Products();
                        mProduct.pid = id;
                        mProduct.name = name;
                        mProduct.price = budget;
                        mProduct.description = description;
                        mProduct.date = date;
                        mProduct.category = category;
                        mProduct.email = email;
                        mProduct.contact = contact;

                        // adding Product to ArrayList
                        productsList.add(mProduct);
                    }
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getActivity(), MainMenu.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    private Intent getIntent() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/

    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();

        if (productsList.size() > 0) {
            /**
             * Updating parsed JSON data into ListView
             * */
            CustomAdapter adapter = new CustomAdapter(getActivity(),
                    productsList);// ,

            if (getListView() != null) {

                // updating listview
                setListAdapter(adapter);
            } else {
                Log.d("ListView-Reference", "ListView is null");
            }
        } else {
            Log.d("Product List", "Products list is empty");
        }
    }
}
}

Answers


onCreateView must only return the view that represent the fragment. Other operations on the View should be performed in another callback, onViewCreated:

  @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {       
      return inflater.inflate(R.layout.list_fragment, container, false);
 }

 @Override 
 public void onViewCreated (View view, Bundle savedInstanceState) {
       productsList = new ArrayList<Products>();

lv = getListView();

// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        // getting values from selected ListItem
        String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                .toString();
        String name = ((TextView) view.findViewById(R.id.name))
                .getText().toString();
        String description = ((TextView) view.findViewById(R.id.des))
                .getText().toString();
        String price = ((TextView) view.findViewById(R.id.budget))
                .getText().toString();
        String date = ((TextView) view.findViewById(R.id.date_posted))
                .getText().toString();
        String category = ((TextView) view.findViewById(R.id.category))
                .getText().toString();
        String email = ((TextView) view
                .findViewById(R.id.email_request)).getText().toString();
        String contact = ((TextView) view
                .findViewById(R.id.contact_request)).getText()
                .toString();

        // Starting new intent
        Intent in = new Intent(getActivity(), DisplayItemInfo.class);
        // sending information to next activity
        in.putExtra(TAG_PID, pid);
        in.putExtra(TAG_NAME, name);
        in.putExtra(TAG_DES, description);
        in.putExtra(TAG_BUDGET, price);
        in.putExtra(TAG_DATE_POSTED, date);
        in.putExtra(TAG_CATEGORY, category);
        in.putExtra(TAG_EMAIL, email);
        in.putExtra(TAG_CONTACT, contact);
        startActivity(in);
    }
});

new LoadAllProducts().execute();
 }

You can't call getListView() in the onCreateView() because the ListView doesn't exist yet. You need to put that code inside onViewCreated().


You can avoid crash by using check

if(this.isAdded())   

if you debug that part BooksFragment.getListView int the moment of exception - you will notice it's not exist.


Need Your Help

Texture2D.Bounds.Intersect, but the Bounds never move? - XNA, .Net 4.0

visual-studio-2010 .net-4.0 xna intersection texture2d

I am still shiny new to XNA, so please forgive any stupid question and statements in this post (The added issue is that I am using Visual Studio 2010 with .Net 4.0 which also means very few examples

Forcing A Postback Asp.Net

c# asp.net vb.net

Please take a look at the following click event...