Android http 响应不起作用


Android http response doesn't work

你好,我正在尝试创建一个活动,其中android将值发送到php脚本,该脚本将值插入mysql数据库,然后响应来自android文本视图。当我运行应用程序并单击按钮时,会出现对话框,上面写着"创建聊天室......",当该过程完成后,对话框消失,我在文本视图中没有得到任何响应,但我发现值已成功插入到数据库中。我的代码有什么问题?

注:I没有收到任何错误,应用程序不会崩溃,我在清单中添加了互联网权限。

这是 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 responseBody = EntityUtils.toString(response.getEntity());