首页 > 解决方案 > Connecting MySQL to Android

问题描述

I tried to connect Android to MySQL through php. There's no error in my code but I guess, there is something wrong. I tried to run the app but the title of the Dialog box only displays. I think the result might be the problem?

public class BackgroundWorker extends AsyncTask<String,Void,String> {

    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
    }

    @Override
    protected String doInBackground(String[] voids) {
        String type = "login";

        String login_url = "http://192.168.254.109/ITSP/login.php";
        if(type.equals("login")){
            try {
                String username = voids[1];
                String password =voids[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter =  new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
                        +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader =  new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result = "";
                String line;
                while((line = bufferedReader.readLine()) != null){
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

And by getting the value from here:

public void OnLogin(View view){
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);
}

I have just used simple code for PHP connection. (conn.php)

When I press the Log In button, only the alertDialog = "Login Status" are displayed.

标签: phpandroidmysql

解决方案


我建议您使用Ion库而不是使用AsyncTask. 它将减少代码行数,同时比AsyncTask

https://github.com/koush/ion

这是该库的 github 链接。

您在代码中尝试执行的操作可以像这样实现

    Ion.with(getContext())
    .load("POST","http://192.168.254.109/ITSP/login.php")
    .setBodyParameter("username", username)
    .setBodyParameter("password", password)
    .asJsonObject()  //change it to .asString() if u expect the response from the server in a string format
    .setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
       //if you change the return to .asString() u need to change the callback method to <String> instead of<JsonObject>
});

推荐阅读