从mysql的片段中加载ListView

Posted

技术标签:

【中文标题】从mysql的片段中加载ListView【英文标题】:load ListView in fragment from mysql 【发布时间】:2015-06-26 18:31:38 【问题描述】:

我正在尝试在片段中生成列表视图。代码显示没有错误,但是当我尝试启动应用程序时,在进度对话框显示之后应用程序崩溃了。下面是我的 HomeFragment.java 文件。请帮忙。我是android开发的新手。

HomeFragment.java

public class HomeFragment extends ListFragment  

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser2 jParser = new JSONParser2();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://gemini888.tk/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    //@SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
    
        return inflater.inflate(R.layout.all_products,container,false);
    
    @Override
    public void onStart() 
        super.onStart();
        initControls();
    
        //@SuppressLint("NewApi") 
        public void initControls()             

        //testing
     //  if (android.os.Build.VERSION.SDK_INT > 9)
     //   
     //   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     //   StrictMode.setThreadPolicy(policy);
    //   

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView 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();

                // Starting new intent
                Intent in = new Intent(getActivity().getApplicationContext(),EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
           
        );

    

    // Response from Edit Product Activity
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) 
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getActivity().getIntent();
            getActivity().finish();
            startActivity(intent);
        

    

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> 

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            ProgressDialog pDialog;
            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>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // 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);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

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

            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();
            // updating UI from Background Thread
            getActivity().runOnUiThread(new Runnable() 
                public void run() 
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            getActivity(), productsList,
                            R.layout.list_item, new String[]  TAG_PID,
                                    TAG_NAME,
                            new int[]  R.id.pid, R.id.name );
                    // updating listview
                    setListAdapter(adapter);
                
            );

        

    

我得到的 logcat:

04-20 00:04:09.071: I/Choreographer(1257): Skipped 54 frames!  The application may be doing too much work on its main thread.
04-20 00:04:09.251: I/Choreographer(1257): Skipped 109 frames!  The application may be doing too much work on its main thread.
04-20 00:04:09.331: D/All Products:(1257): "success":1,"products":["created_at":"2015-04-15 21:52:09","pid":"1","updated_at":"0000-00-00 00:00:00","price":"1111.00","description":"good","name":"iphone ","created_at":"2015-04-18 02:41:49","pid":"13","updated_at":"0000-00-00 00:00:00","price":"25.00","description":"cheap\n\n","name":"Samsung ","created_at":"2015-04-18 03:26:40","pid":"14","updated_at":"0000-00-00 00:00:00","price":"1000.00","description":"bad\n","name":"xiaomi"]
04-20 00:04:09.391: I/Choreographer(1257): Skipped 46 frames!  The application may be doing too much work on its main thread.
04-20 00:04:09.451: D/AndroidRuntime(1257): Shutting down VM
04-20 00:04:09.451: W/dalvikvm(1257): threadid=1: thread exiting with uncaught exception (group=0xb2a26ba8)
04-20 00:04:09.551: E/AndroidRuntime(1257): FATAL EXCEPTION: main
04-20 00:04:09.551: E/AndroidRuntime(1257): Process: mygp.gptrade, PID: 1257
04-20 00:04:09.551: E/AndroidRuntime(1257): java.lang.NullPointerException
04-20 00:04:09.551: E/AndroidRuntime(1257):     at mygp.gptrade.HomeFragment$LoadAllProducts.onPostExecute(HomeFragment.java:200)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at mygp.gptrade.HomeFragment$LoadAllProducts.onPostExecute(HomeFragment.java:1)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.os.AsyncTask.finish(AsyncTask.java:632)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.os.Looper.loop(Looper.java:136)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at java.lang.reflect.Method.invokeNative(Native Method)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at java.lang.reflect.Method.invoke(Method.java:515)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-20 00:04:09.551: E/AndroidRuntime(1257):     at dalvik.system.NativeStart.main(Native Method)
04-20 00:04:16.831: I/Process(1257): Sending signal. PID: 1257 SIG: 9

tknell: 我得到第二个错误的logcat。

04-20 05:01:19.800: D/所有产品:(1039): "success":1,"products":["created_at":"2015-04-15 21:52:09"," pid":"1","updated_at":"0000-00-00 00:00:00","price":"1111.00","description":"good","name":"iphone", "created_at":"2015-04-18 02:41:49"," pid":"13","updated_at":"0000-00-00 00:00:00","price":"25.00","description":"便宜\n\n","name":"三星","created_at":"2015-04-18 03:26:40","pid":"14","updated_at":"0000-00-00 00:00:00","price": "1000.00","description":"bad\n","name":"小米"] 04-20 05:01:20.060: I/Choreographer(1039): 跳过 142 帧!应用程序可能在其主线程上做了太多工作。 04-20 05:01:20.560:I/Choreographer(1039):跳过 48 帧!应用程序可能在其主线程上做了太多工作。 04-20 05:01:27.370: I/Choreographer(1039): 跳过 116 帧!应用程序可能在其主线程上做了太多工作。 04-20 05:01:29.990: D/dalvikvm(1039): GC_FOR_ALLOC 释放 301K,10% 释放 3623K/3992K,暂停 351ms,总共 360ms 04-20 05:01:30.760:I/Choreographer(1039):跳过 65 帧!应用程序可能在其主线程上做了太多工作。 04-20 05:01:32.810: D/AndroidRuntime(1039): 关闭 VM 04-20 05:01:32.810: W/dalvikvm(1039): threadid=1: 线程以未捕获的异常退出 (group=0xb2a26ba8) 04-20 05:01:32.920: E/AndroidRuntime(1039): 致命异常: main 04-20 05:01:32.920: E/AndroidRuntime(1039): 进程: mygp.gptrade, PID: 1039 04-20 05:01:32.920: E/AndroidRuntime(1039): android.os.NetworkOnMainThreadException 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 java.net.InetAddress.lookupHostByName(InetAddress.java:385) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 java.net.InetAddress.getAllByName(InetAddress.java:214) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 mygp.gptrade.JSONParser2.makeHttpRequest(JSONParser2.java:62) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 mygp.gptrade.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:131) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 android.os.Handler.handleCallback(Handler.java:733) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 android.os.Handler.dispatchMessage(Handler.java:95) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 android.os.Looper.loop(Looper.java:136) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 android.app.ActivityThread.main(ActivityThread.java:5017) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 java.lang.reflect.Method.invokeNative(Native Method) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 java.lang.reflect.Method.invoke(Method.java:515) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-20 05:01:32.920: E/AndroidRuntime(1039): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-20 05:01:32.920: E/AndroidRuntime(1039): at dalvik.system.NativeStart.main(Native Method)

EditProductActivity.java

公共类 EditProductActivity 扩展 Activity

EditText txtName; EditText txtPrice; EditText txtDesc; EditText txtCreatedAt; Button btnSave; Button btnDelete; String pid; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser2 jsonParser2 = new JSONParser2(); // single product url private static final String url_product_detials = "http://gemini888.tk/android_connect/get_product_details.php"; // url to update product private static final String url_update_product = "http://gemini888.tk/android_connect/update_product.php"; // url to delete product private static final String url_delete_product = "http://gemini888.tk/android_connect/delete_product.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCT = "product"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; private static final String TAG_PRICE = "price"; private static final String TAG_DESCRIPTION = "description"; @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.edit_product); // save button btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); // getting product details from intent Intent i = getIntent(); // getting product id (pid) from intent pid = i.getStringExtra(TAG_PID); // Getting complete product details in background thread new GetProductDetails().execute(); // save button click event btnSave.setOnClickListener(new View.OnClickListener() @Override public void onClick(View arg0) // starting background task to update product new SaveProductDetails().execute(); ); // Delete button click event btnDelete.setOnClickListener(new View.OnClickListener() @Override public void onClick(View arg0) // deleting product in background thread new DeleteProduct().execute(); ); /** * Background Async Task to Get complete product details * */ class GetProductDetails extends AsyncTask<String, String, String> /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Loading product details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); /** * Getting product details in background thread * */ protected String doInBackground(String... params) // updating UI from Background Thread runOnUiThread(new Runnable() public void run() // Check for success tag int success; try // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jsonParser2.makeHttpRequest( url_product_detials, "GET", params); // check your log for json response Log.d("Single Product Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) // successfully received product details JSONArray productObj = json .getJSONArray(TAG_PRODUCT); // JSON Array // get first product object from JSON Array JSONObject product = productObj.getJSONObject(0); // product with this pid found // Edit Text txtName = (EditText) findViewById(R.id.inputName); txtPrice = (EditText) findViewById(R.id.inputPrice); txtDesc = (EditText) findViewById(R.id.inputDesc); // display product data in EditText txtName.setText(product.getString(TAG_NAME)); txtPrice.setText(product.getString(TAG_PRICE)); txtDesc.setText(product.getString(TAG_DESCRIPTION)); else // product with pid not found catch (JSONException e) e.printStackTrace(); ); return null; /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) // dismiss the dialog once got all details pDialog.dismiss(); /** * Background Async Task to Save product Details * */ class SaveProductDetails extends AsyncTask<String, String, String> /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Saving product ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); /** * Saving product * */ protected String doInBackground(String... args) // getting updated data from EditTexts String name = txtName.getText().toString(); String price = txtPrice.getText().toString(); String description = txtDesc.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_PID, pid)); params.add(new BasicNameValuePair(TAG_NAME, name)); params.add(new BasicNameValuePair(TAG_PRICE, price)); params.add(new BasicNameValuePair(TAG_DESCRIPTION, description)); // sending modified data through http request // Notice that update product url accepts POST method JSONObject json = jsonParser2.makeHttpRequest(url_update_product, "POST", params); // check json success tag try int success = json.getInt(TAG_SUCCESS); if (success == 1) // successfully updated Intent i = getIntent(); // send result code 100 to notify about product update setResult(100, i); finish(); else // failed to update product catch (JSONException e) e.printStackTrace(); return null; /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) // dismiss the dialog once product uupdated pDialog.dismiss(); /***************************************************************** * Background Async Task to Delete Product * */ class DeleteProduct extends AsyncTask<String, String, String> /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Deleting Product..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); /** * Deleting product * */ protected String doInBackground(String... args) // Check for success tag int success; try // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // getting product details by making HTTP request JSONObject json = jsonParser2.makeHttpRequest( url_delete_product, "POST", params); // check your log for json response Log.d("Delete Product", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) // product successfully deleted // notify previous activity by sending code 100 Intent i = getIntent(); // send result code 100 to notify about product deletion setResult(100, i); finish(); catch (JSONException e) e.printStackTrace(); return null; /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) // dismiss the dialog once product deleted pDialog.dismiss();

第三个日志猫 (没有 runOnUiThread) 04-21 04:34:25.747: E/WindowManager(1154): android.view.WindowLeaked: Activity mygp.gptrade.EditProductActivity 已泄露窗口 com.android.internal.policy.impl.PhoneWindow$DecorViewb2e99188 VE... .R.....ID 0,0-320,96 最初添加在这里 04-21 04:34:25.747: E/WindowManager(1154): 在 android.view.ViewRootImpl.(ViewRootImpl.java:348) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.Dialog.show(Dialog.java:286) 04-21 04:34:25.747: E/WindowManager(1154): 在 mygp.gptrade.EditProductActivity$GetProductDetails.onPreExecute(EditProductActivity.java:111) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.os.AsyncTask.execute(AsyncTask.java:535) 04-21 04:34:25.747: E/WindowManager(1154): 在 mygp.gptrade.EditProductActivity.onCreate(EditProductActivity.java:72) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.Activity.performCreate(Activity.java:5231) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.ActivityThread.access$800(ActivityThread.java:135) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.os.Handler.dispatchMessage(Handler.java:102) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.os.Looper.loop(Looper.java:136) 04-21 04:34:25.747: E/WindowManager(1154): 在 android.app.ActivityThread.main(ActivityThread.java:5017) 04-21 04:34:25.747: E/WindowManager(1154): 在 java.lang.reflect.Method.invokeNative(Native Method) 04-21 04:34:25.747: E/WindowManager(1154): 在 java.lang.reflect.Method.invoke(Method.java:515) 04-21 04:34:25.747: E/WindowManager(1154): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-21 04:34:25.747: E/WindowManager(1154): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-21 04:34:25.747: E/WindowManager(1154): at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

你不能在你的 doInbackground 中使用 Intent 当我在活动中这样做时,没有问题。当将其移动到片段时,则无法 d. getActivity().getApplicationContext() 将此更改为 getActivity( 【参考方案1】:

您声明成员pDialog 并使用它在onPostExecute 方法中关闭对话框,但在onPreExecute 方法中您声明另一个pDialog 变量来保存创建的对话框而不是您的成员。因此,当您尝试关闭对话框时,成员变量pDialog 为空。

要解决此问题,请删除 onPreExecute 中的另一个 pDialog 变量:

旧:

ProgressDialog pDialog;
pDialog = new ProgressDialog(getActivity());

新:

pDialog = new ProgressDialog(getActivity());

【讨论】:

当我点击列表中的项目时,它也崩溃了。意图有问题吗? EditProductActivity.java 第 131 行 (GetProductDetails.run) 中,您可以在 UI 线程中访问网络(没有 AsyncTask)。这在 Android 中是不允许的,这就是它崩溃的原因。 我添加了 editProductActivity.java 我尝试删除 runOnUiThread 但它仍然崩溃。 它在第二个 logcat 之下。对不起,我不知道如何编辑它。 但是没有runOnUiThread,错误信息应该是不同的,你也可以发布那个错误日志吗?【参考方案2】:

将此代码添加到您的 postExecute 方法中

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

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_PID, id);
                map.put(TAG_NAME, name);

                // adding HashList to ArrayList
                productsList.add(map);
            
         else 
            // no products found
            // Launch Add New product Activity
            Intent i = new Intent(getActivity().getApplicationContext(),
                    NewProductActivity.class);
            // Closing all previous activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        

【讨论】:

以上是关于从mysql的片段中加载ListView的主要内容,如果未能解决你的问题,请参考以下文章

在活动OnCreate中加载片段

如何获取 HTML5 视频中加载的当前片段百分比?

我无法在片段中加载数据 json

只有在被选中时才在 ViewPager 中加载片段

php 在没有模板的插件中加载文本片段

在扩展片段活动android的类中加载soundpool