尚未创建的内容视图

时间:2014-03-10 08:22:23

标签: android

我正在尝试从mysql中检索数据并根据类别选项卡对其进行排序。当我打开尚未创建内容视图的活动时,我的应用程序崩溃。我可以知道这是什么问题吗?

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

类别:

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

3 个答案:

答案 0 :(得分:25)

onCreateView必须只返回代表片段的视图。 View上的其他操作应该在另一个回调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();
 }

答案 1 :(得分:6)

您无法在getListView()中呼叫onCreateView(),因为ListView尚不存在。您需要将该代码放在onViewCreated()

答案 2 :(得分:4)

您可以使用支票

来避免崩溃
if(this.isAdded())   

如果你在异常时调试那部分BooksFragment.getListView - 你会注意到它不存在。