繁体   English   中英

Android http响应不起作用

[英]Android http response doesn't work

您好,我正在尝试创建一个活动,其中android将值发送到php脚本,该脚本将值插入mysql数据库,然后响应出现在android textview中。 当我运行该应用程序并单击该按钮时,出现对​​话框,显示“正在创建聊天室..”,并且当该过程完成时,对话框消失,并且在textview中没有任何响应,但是我发现这些值已成功插入数据库中。 我的代码有什么问题?

注意:我没有收到任何错误,该应用程序也没有崩溃,并且我在清单中添加了Internet权限。

这是java代码:

public class SubmitRoomActivity extends Activity {
    String username;
    String ccolor;
    String crname;
    Button b;
    EditText et,pass;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response2;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;
    public final static String CHATTER_NAME = "com.gowemto.gowemto.USERNAME";
    public final static String CHATTER_COLOR = "com.gowemto.gowemto.CCOLOR";
    public final static String CHATROOM_NAME = "com.gowemto.gowemto.CRNAME";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_room);

        b = (Button)findViewById(R.id.subroom);  

        tv = (TextView)findViewById(R.id.logerr2);

             Intent intent = getIntent();
              username = intent.getStringExtra(SelectRoomActivity.CHATTER_NAME);
              ccolor = intent.getStringExtra(SelectRoomActivity.CHATTER_COLOR);
              crname = intent.getStringExtra(SelectRoomActivity.CHATROOM_NAME);
             final TextView welcominguser = (TextView) findViewById(R.id.hello_user_2);
             if(ccolor.trim().equals("Black")){

                 welcominguser.setTextColor(Color.parseColor("#000000"));
             }
             else if(ccolor.trim().equals("Blue")){

                 welcominguser.setTextColor(Color.parseColor("#0000FF"));
             }
             else if(ccolor.trim().equals("Red")){

                 welcominguser.setTextColor(Color.parseColor("#FF0000"));
             }
             else if(ccolor.trim().equals("Orange")){

                 welcominguser.setTextColor(Color.parseColor("#FF8000"));
             }
             else if(ccolor.trim().equals("Green")){

                 welcominguser.setTextColor(Color.parseColor("#008000"));
             }
             else if(ccolor.trim().equals("Gray")){

                 welcominguser.setTextColor(Color.parseColor("#808080"));
             }
             else if(ccolor.trim().equals("Brown")){

                 welcominguser.setTextColor(Color.parseColor("#804000"));
             }
             else if(ccolor.trim().equals("Purple")){

                 welcominguser.setTextColor(Color.parseColor("#800080"));
             }
             else if(ccolor.trim().equals("Pink")){

                 welcominguser.setTextColor(Color.parseColor("#FF4080"));
             }
             else {

                 welcominguser.setTextColor(Color.parseColor("#000000"));
             }
             welcominguser.setText("Hello, " + username);



        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = ProgressDialog.show(SubmitRoomActivity.this, "", 
                        "Creating room..", true);
                 new Thread(new Runnable() {
                        public void run() {
                            login();                          
                        }
                      }).start();               
            }
        });
    }

    void login(){
        try{            
            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://10.0.2.2/mychat/createroom"); // make sure the url is correct.
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(3);
            // 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("username",username));  // $Edittext_value = $_POST['Edittext_value'];
            nameValuePairs.add(new BasicNameValuePair("ccolor",ccolor));  // $Edittext_value = $_POST['Edittext_value'];
            nameValuePairs.add(new BasicNameValuePair("roomname",crname)); 
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response2=httpclient.execute(httppost);
            // edited by James from coderzheaven.. from here....
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response2 = httpclient.execute(httppost, responseHandler);
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText(response2);
                    dialog.dismiss();
                }
            });



        }catch(Exception e){
            dialog.dismiss();
            tv.setText("Exception : " + e.getMessage());
        }
    }
}

这是xml代码:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" 
        android:background="#EED8FF">

        <LinearLayout 
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:padding="10dp"
            >
    <TextView
                android:id="@+id/hello_user_2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:textColor="#000000"/>
          <TextView
                android:layout_width="fill_parent"
                android:layout_height="56dp"
                android:text="@+string/room_inst_2"
                android:textSize="16sp"
                android:textColor="#000000"/>
            <Spinner
            android:id="@+id/second_colors"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:entries="@array/sec_color_names" />
            <Button 
                   android:id="@+id/subroom"
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_margin="4dp"
                   android:text="@string/cont_act"
                style="@style/DefaultButtonText"
                   android:background="@drawable/button_default_bg"
                    android:onClick="gotoRoom"
               />
              <TextView
                android:layout_width="fill_parent"
                android:layout_height="56dp"
                android:id="@+id/logerr2"
                android:textColor="#000000"/>
            </LinearLayout

    </RelativeLayout>

这是PHP脚本:

<?php
$hostname_localhost ="localhost";
$database_localhost ="chat_db";
$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);

$username = $_POST['username'];
$roomname = $_POST['roomname'];
$roomcolor = $_POST['ccolor'];
$query_insert = "INSERT INTO chatrooms VALUES('$username','$roomname','$roomcolor')";
$query_exec = mysql_query($query_insert) or die(mysql_error());

echo "Room created successfully"; 

?>

我该如何解决这个问题? 我的代码有什么问题?

尝试使用以下方法在php上获取内容:

$response = file_get_contents("http://10.0.2.2/mychat/createroom");

然后使用json_decode($ response)解码json值

您没有错误,因为您有:

   }catch(Exception e){
        dialog.dismiss();
        tv.setText("Exception : " + e.getMessage());
    }

您捕获了所有异常(因此您的应用程序不会崩溃),但是您没有记录异常,因此您不知道问题出在哪里。 另外,您从后台线程调用tv.setText() 很坏。

尝试在此处添加一些日志记录。

您正在两次调用post方法。 如果您为表设置了一些唯一约束,则可能会出现问题。

//Execute HTTP Post Request
response2=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response2 = httpclient.execute(httppost, responseHandler);

我认为,一个职位请求就足以满足您的需求。 具有两个名称相同但类型不同的变量也很令人困惑。 就像response2是HttpResponse一样,另一个是String。

如果使用的是第一个执行调用,则可以得到如下响应字符串:

String responseBody = EntityUtils.toString(response.getEntity());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM