如何解决NameValuePair不能是Android中的String

时间:2015-04-05 15:55:44

标签: java android basicnamevaluepair

我正在学习如何构建Android应用程序,我正在尝试使用Java和PHP将值插入到我的数据库中。但NameValuePair给了我多个错误。

我已经导入了必要的文件。我做错了什么?

我的PHP文件:

$connect = mysqli_connect("localhost","root","","users");

if(mysqli_connect_errno($connect))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "success";
}

$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
$result = mysql_query(" insert into users(username,password)   values('$username','$password')"  );
if($result == 1)
{
    // successfully inserted
    $response["success"] = 1;
    $response["message"] = "User created.";

    // echoing JSON response
    echo json_encode($response);
}
else
{
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);

}

Java 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="com.example.registro.MainActivity" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="70dp"
        android:ems="10"
        android:text="Password"
         >

    </EditText>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:text="Username" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="40dp"
        android:text="Button"
        android:onClick="create"
         />

</RelativeLayout>

主要活动文件

package com.example.registro;


import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList; 
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

    private EditText usernameField,passwordField;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          usernameField = (EditText)findViewById(R.id.editText1);
          passwordField = (EditText)findViewById(R.id.editText2);
    }

       public void create(){
              String username = usernameField.getText().toString();
              String password = passwordField.getText().toString();

              // TODO Auto-generated method stub
                HttpClient client = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://localhost/example/insert.php");

                try
                {
                    nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("username", username));
                    nameValuePairs.add(new BasicNameValuePair("password", password));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    response = httpclient.execute(httppost);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    }

1 个答案:

答案 0 :(得分:0)

尝试更改

public void create(){
          String username = usernameField.getText().toString();
          String password = passwordField.getText().toString();

          // TODO Auto-generated method stub
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost("http://localhost/example/insert.php");

            try
            {
                List<NameValuePair>  postparam = new ArrayList<NameValuePair>();
                postparam.add(new BasicNameValuePair("username", username));
                postparam.add(new BasicNameValuePair("password", password));

                httppost.setEntity(new UrlEncodedFormEntity(postparam));
                HttpResponse response = client.execute(request);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }