第一次将 Spinner 值发送到 php 文件时,只有它的工作

While sending Spinner Value to php file first time only its working

我想将 Spinner 值传递给 php 并获得一些结果并显示到我的 TextView 中。当我使用 Toast 显示选定值时,它的工作 perfect.but 同时将值传递给 php 文件,我感到震惊。我尝试了一些方法。可以解决我的问题吗?

java 文件:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide(); //<< this for hide title bar
        setContentView(R.layout.sales_order);

    fg.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(
                                AdapterView<?> parent, View view, int position, long id) {
                            if(goods_name1.getSelectedItem() !=null && goods_name1.getSelectedItem() !=""){
                                // WebServer Request URL
                                String serverURL = "http://IP/fs/getProductOneStock.php";
                                // Use AsyncTask execute Method To Prevent ANR Problem
                                new LongOperation().execute(serverURL);
                            }
                        }

                        public void onNothingSelected(AdapterView<?> parent) {
                            showToast("Spinner1: unselected");
                        }
                    });
}

// Class with extends AsyncTask class
    private class LongOperation  extends AsyncTask<String, Void, Void> {

        // Required initialization
        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(Sales_Order.this);
        String data ="";
        int sizeData = 0;
        TextView pro_stock1 = (TextView)findViewById(R.id.tv_stock1);
        Spinner fgStock = (Spinner)findViewById(R.id.spinner1);

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.
            //Start Progress Dialog (Message)

            Dialog.setMessage("Please wait..");
            Dialog.show();

            try{
                // Set Request parameter
                data +="&" + URLEncoder.encode("data", "UTF-8") + "="+fgStock.getSelectedItem();

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            /************ Make Post Call To Web Server ***********/
            BufferedReader reader=null;
            // Send data
            try
            {
                // Defined URL  where to send data
                URL url = new URL(urls[0]);
                // Send POST data request
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                // Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;
                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line + "");
                }
                // Append Server Response To Content String
                Content = sb.toString();
            }
            catch(Exception ex)
            {
                Error = ex.getMessage();
            }
            finally
            {
                try
                {
                    reader.close();
                }
                catch(Exception ex) {}
            }
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                pro_stock1.setText("Output : "+Error);

            } else {

                // Show Response Json On Screen (activity)
                pro_stock1.setText( Content );

                /****************** Start Parse Response JSON Data *************/

                String OutputData = "";
                JSONObject jsonResponse;

                try {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse = new JSONObject(Content);

                    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                    /*******  Returns null otherwise.  *******/
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("Finish_goods_mas");

                    /*********** Process each JSON Node ************/

                    int lengthJsonArr = jsonMainNode.length();

                    for(int i=0; i < lengthJsonArr; i++)
                    {
                        /****** Get Object for each JSON node.***********/
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                        /******* Fetch node values **********/
                        String Stock1 = jsonChildNode.optString("Finish_goods_mas").toString();
                        OutputData += Stock1;


                    }
                    /****************** End Parse Response JSON Data *************/

                    //Show Parsed Output on screen (activity)
                    //jsonParsed.setText( OutputData );

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

    }

我的php文件

    <?php
require "db_config.php";
$Goods_name=$_POST['Goods_name'];
$sql = "select goods_min_level from Finish_goods_mas where Goods_name='".$Goods_name."'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      //echo $row['cus_id']."<br />";
      $json['Finish_goods_mas'][]=$row;
}

sqlsrv_free_stmt( $stmt);

echo json_encode($json);
?>

更改 doInBackgroundonPreExecute() 后,Spinner 值未传递到 php 文件,我也无法从 php

取回结果

执行异步任务时,任务经过4个步骤:

1.onPreExecute(),在任务执行前在UI线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

2.doInBackground(Params...),onPreExecute() 执行完毕后立即在后台线程调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递给这一步。计算结果必须由这一步返回,并传回最后一步。此步骤还可以使用 publishProgress(Progress...) 来发布一个或多个进度单元。这些值在 UI 线程的 onProgressUpdate(Progress...) 步骤中发布。

3.onProgressUpdate(Progress...),在调用 publishProgress(Progress...) 后在 UI 线程上调用。执行时间未定义。此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度。例如,它可用于动画进度条或在文本字段中显示日志。 4.onPostExecute(Result),在后台计算完成后在 UI 线程上调用。后台计算的结果作为参数传给这一步

所以 textView.setText(strOrderNo); 在 onPostExecute(Result) 覆盖方法中执行