Android在另一个异步任务中调用异步任务?

时间:2014-02-13 19:23:13

标签: java android http asynchronous

我正在尝试在另一个Async方法中进行异步调用我不确定我是否正确地执行此操作,或者甚至是否可能。第一次调用从数据库中获取partID,然后第二次获取该部分的lotNumbers。我这样做的理由是能够遍历并将关联的partLotNumebrs放在Spinner中并在Listview中显示Spinners列表。我究竟做错了什么?这甚至可能吗?我知道你不能在主要内部进行HTTP调用,所以我不确定是否有其他方法可以做到这一点。

我得到的错误。

02-13 11:04:16.431: E/AndroidRuntime(1369): FATAL EXCEPTION: main
02-13 11:04:16.431: E/AndroidRuntime(1369): java.lang.NullPointerException
02-13 11:04:16.431: E/AndroidRuntime(1369):     at com.cbs.iomamobile.ViewOrderlineAssemblyActivity$getPartLotNumbers.onPostExecute(ViewOrderlineAssemblyActivity.java:258)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at com.cbs.iomamobile.ViewOrderlineAssemblyActivity$getPartLotNumbers.onPostExecute(ViewOrderlineAssemblyActivity.java:1)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.os.AsyncTask.finish(AsyncTask.java:602)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.os.Looper.loop(Looper.java:137)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at android.app.ActivityThread.main(ActivityThread.java:4340)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at java.lang.reflect.Method.invokeNative(Native Method)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at java.lang.reflect.Method.invoke(Method.java:511)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-13 11:04:16.431: E/AndroidRuntime(1369):     at dalvik.system.NativeStart.main(Native Method)

它指向这一行

textView.setText(temp.getString("name"));

似乎我的Spinner或textView都不是有效的,不知道为什么。

assembly.class

public class ViewOrderlineAssemblyActivity extends ListActivity{
    // Progress Dialog
    private ProgressDialog pDialog;

    String productName;
    String olid;
    String assemblyName;

    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();

    // url to get all orders list
    private static String url_get_assembly_parts = "http://10.0.2.2/android_connect/get_assembly_parts.php";

    // url to get all orders list
    private static String url_get_part_partlotnumbers = "http://10.0.2.2/android_connect/get_part_partLotNumbers.php";



    // orders JSONArray
    JSONArray assembly = null;
    JSONArray parts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_assemblies);

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        assemblyName = i.getStringExtra("assemblyName");
        olid = i.getStringExtra(TAG_OLID);

        Log.d("assemblyName", "" + assemblyName);

        // Loading orders in Background Thread
        new LoadAllAssemblyParts().execute();



    }

    // Response from Edit Order Activity
    @Override
    protected 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 = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all assemblyparts by making HTTP Request
     * */
    class LoadAllAssemblyParts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
        }

        /**
         * getting All orders from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("assemblyName", assemblyName));   

            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_get_assembly_parts, "GET", params);

            // Check log cat for JSON reponse
            Log.d("All partID's: ", json.toString());

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

                if (success == 1) {
                    // orders found
                    // Getting Array of Parts
                    assembly = json.getJSONArray("assembly");

                    // looping through All Parts
                    for (int i = 0; i < assembly.length(); i++) {

                        JSONObject c = assembly.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString("partID");
                        String name = c.getString("assemblyName");

                        new getPartLotNumbers().execute(id);
                    }
                } else {
                    // no part ID's 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 after getting all orders
        }

    }

    class getPartLotNumbers extends AsyncTask<String, String, JSONArray>{

        Spinner spinner;
        TextView textView;

        @Override
        protected JSONArray doInBackground(String... args) {            

            JSONArray parts = null;
            int success;
            String partID = args[0];

            try{
                // Building Parameters 
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("partID", partID));

                // getting part Lot Numbers by making HTTP request
                // Note that part Lot Numbers will use GET request
                JSONObject json = jsonParser.makeHttpRequest(url_get_part_partlotnumbers, "GET", params);

                // check log for json response
                Log.d("List of PartID's", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);

                if(success == 1){

                    // successfully received part Lot Numbers
                    parts = json.getJSONArray("parts"); // JSON Array

                }else{
                    // part Lot Numbers not not found
                }

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

            //return array of part Lot Numbers
            return parts;
        }

        protected void onPostExecute(JSONArray products){
            //spinner and textview
            spinner = (Spinner) findViewById(R.id.LotNumbers);
            textView = (TextView) findViewById(R.id.partName);

            //list of partLotNumbers
            List<String> partLotNumberList = new ArrayList<String>();

            //move list from JSON to List
            try{
                for(int i=0;i<products.length();i++){
                    JSONObject temp = products.getJSONObject(i);

                    partLotNumberList.add(temp.getString("partLotNumber"));
            }

            //get Part Name
            JSONObject temp = products.getJSONObject(0);
            textView.setText(temp.getString("name"));

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

            //adapter for Spinner           
            ArrayAdapter<String> adp1=new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, partLotNumberList);           
            adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            //set the adapter to the spinnner
            spinner.setAdapter(adp1);                       
        }

    }
}

all_assembly_parts.xml

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

<!-- Main ListView 
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

view_assembly_parts.xml

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

    <TextView
        android:id="@+id/partName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Spinner
        android:id="@+id/LotNumbers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

好的,我会先解决崩溃问题。

您有一个仅包含列表的ListActivity。我猜你发布的两个布局文件是用于显示信息的自定义单元格。在AsyncTask中,当您调用findViewById()时,它会查看活动的布局(仅包含列表视图)而不是每个单元格的布局。这就是为什么你将它们都变为null的原因,因为活动中没有这样的项目。如果要更新单元格中的信息,则不是这样做的。

您需要查看自定义单元格,列表视图。谷歌举一个简单的例子。

希望这有助于理解崩溃。