Asynctask中的线程争用

时间:2015-01-26 14:30:51

标签: java android rest android-asynctask

当我的程序执行asynctask时,我遇到线程争用问题,asynctask的当前目的是连接到ftp服务器并基于成功的连接,然后发出get HTTP解析请求以访问JSON数据我需要写入本地SQLite数据库。

我在理解线程争用方面略有新意,但我已经阅读了特定的this article我怀疑它是一个僵局。

下面是我运行应用程序时调用的调试窗口。我是在设备而不是模拟器上这样做的:

DEBUG WINDOW

以下是asynctask代码:

/**
 * 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();
        //pDialog = new ProgressDialog(AllProductsActivity.this);
        //pDialog.setMessage("Loading products. Please wait...");

        Log.i("LoadAllProducts", "LoadAllProducts - 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>();

        Log.i("LoadAllProducts", "URL: " + url_all_products);

        ftpConnectLoginAndUpload = new FTPConnectLoginAndUpload();

        if(ftpConnectLoginAndUpload.execute()) {

            // Check your log cat for JSON response
            Log.d("LoadAllProducts ", "About to execute JSONObject json = jParser.makeHttpRequest(url_all_products, \"GET\", params);");                

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

            // Check your log cat for JSON response
            Log.d("LoadAllProducts ", 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); // products is a variable holding the value from the 2nd key-value pairing.

                    // 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 price = c.getString("price");
                        String created_at = c.getString("created_at");
                        String updated_at = c.getString("updated_at");

                        Log.d("LoadAllProducts ", "JSON item var i.e. id:" + id);
                        Log.d("LoadAllProducts ", "JSON item var i.e. name:" + name);
                        Log.d("LoadAllProducts ", "JSON item var i.e. price:" + price);
                        Log.d("LoadAllProducts ", "JSON item var i.e. created_at:" + created_at);
                        Log.d("LoadAllProducts ", "JSON item var i.e. updated_at:" + updated_at);

                        // 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(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }*/
        } else {

        }

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

        Log.i("LoadAllProducts", "LoadAllProducts - dismiss the dialog after getting all products");
        // updating UI from Background Thread
        /*runOnUiThread(new Runnable() {
            public void run() {
               //Updating parsed JSON data into ListView
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });*/

    }

}

以下是FTP登录代码:

//!< FTP Connect, Login And Upload
public class FTPConnectLoginAndUpload {

    //!< 
    private void showServerReply(FTPClient ftpClient) {
        String[] replies = ftpClient.getReplyStrings();

        if (replies != null && replies.length > 0) {
            for (String aReply : replies) {
                System.out.println("---> showServerReply(FTPClient ftpClient) - SERVER: " + aReply);
            }
        }
    }

    //!< 
    public boolean execute() {

        // Boston's FTP login credentials
        String server = "XX.XXX.XXX.XX";
        int port = 21;
        String user = "XXXXXXXX_XXXXXX";
        String pass = "XXXXXXXX";

        // Time out period after connection attempt
        int timeOut = 5000;

        boolean ftpResult;

        // FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server
        // This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface
        FTPClient ftpClient = new FTPClient();

        // Execute FTP process
        try {

            // Set connection timeout in milliseconds
            ftpClient.setConnectTimeout(timeOut);

            // Sets the timeout in milliseconds to use when reading from the data connection. 
            ftpClient.setDataTimeout(timeOut);

            // Connect using provided server and port numb
            ftpClient.connect(server, port);

            System.out.println("\n---> ftpClient.connect(server, port) has been executed.\n---> Server used was " 
                    + server + " and port number used was: " + port);

            System.out.println("\n---> ftpClient.getReplyString() returns: " + ftpClient.getReplyString());

            // Returns server reply
            System.out.println("\n---> Server reply is as follows:");
            showServerReply(ftpClient);
            System.out.println("---> End of server reply");

            // Get server reply code
            int replyCode = ftpClient.getReplyCode();
            System.out.println("\n---> ftpClient replyCode is: " + replyCode);

            // Determine if a reply code is a positive completion response. All codes beginning with a 2 are positive completion responses. 
            // The FTP server will send a positive completion response on the final successful completion of a command. 
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("\n---> Operation failed. Server reply code: " + replyCode);

                ftpResult = false;

                return ftpResult;
            } else {
                System.out.println("\n---> Operation successful. Server reply code: " + replyCode);

                // Attempt login
                boolean success = ftpClient.login(user, pass);
                System.out.println("\n---> ftpClient.login(user, pass); has been called.");

                // Determine log in success
                if (!success) {
                    System.out.println("\n ---> Unable to login to the server");
                    ftpResult = false;

                    return ftpResult;
                } else {
                    System.out.println("\n---> Successfully logged into server");

                    ftpResult = true;
                }

                // 
                ftpClient.enterLocalPassiveMode();

                // Show server reply after logging in 
                System.out.println("\n---> Server response after logging in is as follows:");

                showServerReply(ftpClient);

                System.out.println("---> End of server response after logging");

                return ftpResult;
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();

            ftpResult = false;

            return ftpResult;
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();

                    ftpResult = false;

                    return ftpResult;
                }
            } catch (IOException ex) {
                ex.printStackTrace();

                ftpResult = false;

                return ftpResult;
            }
        }
    }   
}

0 个答案:

没有答案