Android PHP应用程序不读取EditText输入


Android PHP App Not Reading EditText Input

我有一个android应用程序,通过PHP页面调用我的云SQL服务器。

然而,当我发送一个HTTPRequest到我的PHP页面,而使用JSONParser来翻译数据,输入(EditText)从我的Android应用程序页面似乎没有延续。

Android Java Code:

public class login extends Activity implements View.OnClickListener {
private AnimatedGifImageView animatedGifImageView;
public EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();


//testing on Emulator:
private static final String LOGIN_URL = "(my php page)";

//JSON element ids from response of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    user = (EditText)findViewById(R.id.etUsername);
    pass = (EditText)findViewById(R.id.etPassword);

    animatedGifImageView = ((AnimatedGifImageView) findViewById(R.id.animatedGifImageView));
    animatedGifImageView.setAnimatedGif(R.raw.animated_gif_big, TYPE.AS_IS);

    //setup input fields
    //setup buttons
    mSubmit = (Button) findViewById(R.id.btnLogin);
    //register listeners
    mSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.btnLogin:
            new AttemptLogin().execute();
            break;
        case R.id.btnSignUp:
            Intent i = new Intent(this, register.class);
            startActivity(i);
            break;
        default:
            break;
    }
}
class AttemptLogin extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(login.this);
        pDialog.setMessage("Checking Credentials...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("etUsername", username));
            params.add(new BasicNameValuePair("etPassword", password));
            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);
            // check your log for json response
            Log.d("Login attempt", json.toString());
            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(login.this, LoginLoading.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(login.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}

}

这是我的JSONParser代码:

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}

public JSONObject getJSONFromUrl(final String url) {
    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;
        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "'n");
        }
        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // Return the JSON Object.
    return jObj;
}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {
    // Making HTTP request
    try {
        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "'n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}

这是我的php页面上结束的部分:

<?php if (empty ($_POST['username'])) {$response['success'] = 0; die(json_encode($response)); exit (0);} ?>

我错过了什么?

您发送$_POST参数etUsername

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("etUsername", username));
        params.add(new BasicNameValuePair("etPassword", password));

在你的AttemptLogin AsyncTask和在你的PHP脚本测试$_POST参数username

        if (empty ($_POST['username']))