【问题标题】:Android PHP App Not Reading EditText InputAndroid PHP 应用程序不读取 EditText 输入
【发布时间】:2015-08-02 13:14:21
【问题描述】:

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

但是,当我向我的 PHP 页面发送 HTTPRequest,同时使用 JSONParser 翻译数据时,来自我的 Android 应用页面的输入 (EditText) 似乎没有继续。

这是 Android Java 代码:

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);} ?>

我错过了什么?

【问题讨论】:

    标签: java php android sql json


    【解决方案1】:

    你发送 $_POST 参数 etUsername

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

    在 AttemptLogin AsyncTask 和 PHP 脚本中测试 $_POST 参数用户名

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

    【讨论】:

    • 亲爱的上帝,我怎么会错过这个?!谢谢你多一双眼睛
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多