Android http响应无效

时间:2014-12-29 16:19:06

标签: java php android xml httpresponse

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

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

这是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"; 

?>

如何解决此问题?我的代码出了什么问题?

3 个答案:

答案 0 :(得分:0)

尝试使用以下内容获取php上的内容:

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

然后使用json_decode($ response)

解码json值

答案 1 :(得分:0)

你没有错误,因为你有这个:

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

您捕获所有异常(因此您的应用程序不会崩溃),但您不记录异常,因此您不知道您的问题是什么。此外,您从后台线程调用tv.setText()。非常糟糕。

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

答案 2 :(得分:0)

您正在调用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());