如何在同一屏幕上从JSON发送和接收数据

时间:2014-05-20 07:17:40

标签: php android json

我正在创建一个应用程序,其中有一个搜索屏幕,该屏幕从用户获取搜索数据并将其发送到服务器,然后服务器将搜索结果发送回用户。

我的问题是我能够发送数据,但我不知道如何在同一个类中实现接收数据。我创建了其他应用程序,在这些应用程序中,它们可以在同一个类中发送或接收,但不能同时发送或接收。

我正在使用json解析来发送/接收数据。

在android代码中,我还没有完成接收部分,因为我不知道如何使用发送功能添加接收功能。

抱歉我的英语不好。

这是我的php服务器代码

<?php
$hostname_localhost ="localhost";
$database_localhost ="testdb";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

 mysql_select_db($database_localhost, $localhost);

//$unique_id = $_POST['unique_id'];
$carat1 = $_POST['carat1'];
$carat2 = $_POST['carat2'];
$color1 = $_POST['color1'];
$color2 = $_POST['color2'];
$cut1 = $_POST['cut1'];
$cut2 = $_POST['cut2'];
$shape1 = $_POST['shape1'];
$shape2 = $_POST['shape2'];
$stones = $_POST['stones'];


//$query_search = "Select * from search where (unique_id, carat1, carat2, color1, color2 , cut1, cut2, shape1, shape2, stones ) VALUES('$unique_id', '$carat1','$carat2','$color1','$color2','$cut1', '$cut2', '$shape1', '$shape2', '$stones')";
$query_search ="Select * from search where  carat = '$carat1' or carat = '$carat2' and color = '$color1' or color =  '$color2' and cut = '$cut1' or cut = '$cut2' and shape = '$shape1 or shape = '$shape2' and stones ='$stones";
$query_exec = mysql_query($query_search) or die(mysql_error());


    while($row=mysql_fetch_assoc($query_exec))
            $json_output[]=$row;
      echo "search";
    print(json_encode($json_output));

    mysql_close();

//$rows = mysql_num_rows($query_exec);
//echo $rows;

?>

这是我的Android代码。

public class QuickSearch extends Activity {

    Button search;
    RadioGroup stones;
    RadioButton single,twin,selected_value;
    EditText to,from,unique_id;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;
    Intent f1;
    String radiovalue;
    String str_color1,str_color2,str_clarity1, str_clarity2, str_shape1,str_shape2, str_cut1,str_cut2,str_carat1,str_carat2;
    Spinner color1,color2,shape1,shape2,clarity1,clarity2,cut,cut2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quicksearch);

        search=(Button)findViewById(R.id.search);
      //  submit=(Button)findViewById(R.id.submit);
        to=(EditText)findViewById(R.id.to);
        from=(EditText)findViewById(R.id.from);
       // unique_id=(EditText)findViewById(R.id.unique_id);
        tv = (TextView)findViewById(R.id.tv);
        stones=(RadioGroup)findViewById(R.id.radioGroup);
        single=(RadioButton)findViewById(R.id.single);
        twin=(RadioButton)findViewById(R.id.twin);


        f1 = new  Intent(QuickSearch.this,Search_result.class);





         color1=(Spinner)findViewById(R.id.color1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.color1, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        color1.setAdapter(adapter);


         color2=(Spinner)findViewById(R.id.color2);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.color2, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        color2.setAdapter(adapter2);


         shape1=(Spinner)findViewById(R.id.shape);
        ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.shape, android.R.layout.simple_spinner_item);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        shape1.setAdapter(adapter3);


         shape2=(Spinner)findViewById(R.id.shape2);
        ArrayAdapter<CharSequence> adapter8 = ArrayAdapter.createFromResource(this, R.array.shape2, android.R.layout.simple_spinner_item);
        adapter8.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        shape2.setAdapter(adapter8);



         clarity1=(Spinner)findViewById(R.id.clarity1);
        ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(this,
                R.array.clarity1, android.R.layout.simple_spinner_item);
        adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        clarity1.setAdapter(adapter4);



         clarity2=(Spinner)findViewById(R.id.clarity2);
         ArrayAdapter<CharSequence> adapter5 = ArrayAdapter.createFromResource(this,R.array.clarity2, android.R.layout.simple_spinner_item);
        adapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        clarity2.setAdapter(adapter5);


         cut=(Spinner)findViewById(R.id.cut);
        ArrayAdapter<CharSequence> adapter6 = ArrayAdapter.createFromResource(this,R.array.cut, android.R.layout.simple_spinner_item);
        adapter6.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cut.setAdapter(adapter6);

         cut2=(Spinner)findViewById(R.id.cut2);
        ArrayAdapter<CharSequence> adapter7 = ArrayAdapter.createFromResource(this,R.array.cut2, android.R.layout.simple_spinner_item);
        adapter7.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cut2.setAdapter(adapter7);

        search.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View view) {


                   str_color1= color1.getSelectedItem().toString();
                   str_color2= color2.getSelectedItem().toString();
                   str_shape1=shape1.getSelectedItem().toString();
                   str_shape2=shape2.getSelectedItem().toString();
                   str_clarity2=clarity2.getSelectedItem().toString();

                   str_clarity1=  clarity1.getSelectedItem().toString();
                   str_cut1=cut.getSelectedItem().toString();
                   str_cut2=cut2.getSelectedItem().toString();
                   str_carat1=to.getText().toString().trim();
                   str_carat2=from.getText().toString().trim();
                   int selectedId = stones.getCheckedRadioButtonId();

                   // find the radiobutton by returned id
                   selected_value = (RadioButton) findViewById(selectedId);
                   radiovalue= selected_value.getText().toString();




                   dialog = ProgressDialog.show(QuickSearch.this, "","Searching...", true);

                   if(str_color1=="Color To:" || str_color2=="Color  From:" || str_clarity1=="Color To:" || str_clarity2 =="Color From:"
                           || str_cut1 == "Cut To:" || str_cut2 == " Cut From:" || str_shape1=="Shape To:" || str_shape2 =="Shape From"
                           || radiovalue=="" || str_carat1==null || str_carat2==null)
                   {

                       Toast.makeText(getApplicationContext(), "Please enter all the field", Toast.LENGTH_SHORT).show();

                   }
                   else
                   {


                   new Thread(new Runnable() {
                       public void run() {
                           Search();
                       }
                   }).start();
               }}
           });
    }

    void Search(){
        try{

            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://192.168.0.106/test/search.php"); // make sure the url is correct.
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(2);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
            nameValuePairs.add(new BasicNameValuePair("carat1",str_carat1.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("carat2",str_carat2.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("color1",str_color1.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("color2",str_color2.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("shape1",str_cut1.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("shape2",str_cut2.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("stones",radiovalue.toString().trim()));

            // $Edittext_value = $_POST['Edittext_value'];

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response);
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText("Response from PHP : " + response);
                    dialog.dismiss();
                }
            });

            if(response.equalsIgnoreCase("Search")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(QuickSearch.this, "Searching Successful", Toast.LENGTH_SHORT).show();
                    }
                });

               // startActivity(new Intent(QuickSearch.this, LoginScreen.class));
                //f1.putExtra("unique_id", unique_id.getText());
                //st/artActivity(f1);


            }else{
                showAlert();
            }

        }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }
    }
    public void showAlert(){
        QuickSearch.this.runOnUiThread(new Runnable() {
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(QuickSearch.this);
                builder.setTitle("Searching Error.");
                builder.setMessage("Problem in Searching. Please try again later")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
    }


}

这是从我的Android手机发送数据后来自php服务器的响应。

8350-8350/com.diamond.traders W/InputEventReceiver﹕ Attempted to finish an input event but the input event receiver has already been disposed.
05-20 13:09:48.841    8350-8434/com.diamond.traders W/SingleClientConnManager﹕ Invalid use of SingleClientConnManager: connection still allocated.
    Make sure to release the connection before allocating another one.
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ Response : <br />
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: cut1 in C:\wamp\www\test\search.php on line <i>17</i></th></tr>
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
05-20 13:09:49.211    8350-8434/com.diamond.traders I/System.out﹕ <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0550</td><td bgcolor='#eeeeec' align='right'>146400</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\test\search.php' bgcolor='#eeeeec'>..\search.php<b>:</b>0</td></tr>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ </table></font>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <br />
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: cut2 in C:\wamp\www\test\search.php on line <i>18</i></th></tr>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0550</td><td bgcolor='#eeeeec' align='right'>146400</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\test\search.php' bgcolor='#eeeeec'>..\search.php<b>:</b>0</td></tr>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ </table></font>
05-20 13:09:49.221    8350-8434/com.diamond.traders I/System.out﹕ You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Signature Ideal' and stones ='Single' at line 1

2 个答案:

答案 0 :(得分:1)

我现在没有我的IDE,但你可以尝试使用AsyncTask及其onPostExecute Callback这样:

//method in your Activity/Fragment to recieve data
    private void askServer(String... params){
        Search searcher = new Search(){
            public void onPostExecute(String response){
                //this method is called on UI-Thread when the Asynctask is finished
                //check response for errors
                if(response.equals("")){
                    Toast.makeText(MainActivity.this, "Error on response", Toast.LENGTH_SHORT).show();
                }else{
                    //handle your response eg fill a textView etc pp

                }
            }
        }

        searcher.execute
    }

    //Your Asynctask
    public class Search() extends Asynctask<String, Void, String>{

        doInBackground(String param){
            String response = "";
                try{
                    httpclient=new DefaultHttpClient();
                    httppost= new HttpPost("http://192.168.0.106/test/search.php"); // make sure the url is correct.
                    //add your data
                    nameValuePairs = new ArrayList<NameValuePair>(2);
                    // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
                    nameValuePairs.add(new BasicNameValuePair("carat1",param[0].trim()));




                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    //Execute HTTP Post Request

                    response= httpclient.execute(httppost);

                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    response = httpclient.execute(httppost, responseHandler);



                }catch(Exception e){
                    dialog.dismiss();
                    System.out.println("Exception : " + e.getMessage());
                }
                return response;
    }

另请查看DOCU

这个很棒的教程页面LINK

答案 1 :(得分:0)

对于搜索功能,您不必在PHP中创建两个用于发送和接收的Web服务,对于每个搜索调用,搜索Web服务将打印搜索结果。在您的PHP代码中,您打印“搜索”,将其替换为您从数据库获得的结果,从Android代码中获取响应结果并显示它们而不是“搜索成功”。

如果您不想更改服务,请在发送数据后调用接收部分,并在UI线程上运行的线程中显示结果。