更新数据库时没有错误或响应

问题描述 投票:0回答:1

我正在尝试从我的应用程序连接到Mysql上的数据库。但我看不到任何来自应用程序的Toast响应或结果。以及我的数据库没有更新,谢谢

这是mainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    public void userReg(View view){

        startActivity(new Intent(this,Register.class));

    }

}

background.Java

public class Background extends AsyncTask<String,Void,String> {
    Context ctx;
    Background(Context ctx){
        this.ctx = ctx;

    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://10.0.2.2/AndroidDB/register.php";
        String log_url = "http://10.0.2.2/AndroidDB/login.php";
        String method = params[0];
        if(method.equals("register")) {

            String name = params[1];
            String username = params[2];
            String password = params[3];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
                String data = URLEncoder.encode("name","UTF-8") +"="+URLEncoder.encode(name,"UTF-8")+"&"+
                            URLEncoder.encode("username","UTF-8") +"="+URLEncoder.encode(username,"UTF-8")+"&"+
                             URLEncoder.encode("password","UTF-8") +"="+URLEncoder.encode(password,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpURLConnection.getInputStream();
                IS.close();
                return  "Registration Success....";


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

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

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();

    }
}

这是Register.java

public class Register extends AppCompatActivity {
    EditText et_Name, et_UserName, et_Userpass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        et_Name =(EditText)findViewById(R.id.name);
        et_UserName =(EditText)findViewById(R.id.userName);
        et_Userpass =(EditText)findViewById(R.id.userPass);


    }


    public void userReg (View view) {
        String name = et_Name.getText().toString();
        String username = et_UserName.getText().toString();
        String password = et_Userpass.getText().toString();
        String method = "register";
        Background background= new Background(this);
        background.execute(method,name,username,password);
        finish();

    }
}

我没有看到错误,但我没有看到结果请求帮助。

android mysql database toast
1个回答
0
投票

复制这个类:

public class HttpClient {

private static JSONObject response = null;

public static JSONObject SendHttpGET(String url) {
     response = null;
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Content-type", "application/json");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer sb = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            sb.append(inputLine);
        }
        in.close();
        response = new JSONObject(sb.toString());
    } catch (Exception e) {
        e.printStackTrace();
       // Crashlytics.logException(e);
    }
    return response;
}

public static JSONObject SendHttpPost(String URL, List<NameValuePair> param) {
    System.out.println("!!-- req=>" +URL + " - " + param.toString());
    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 15000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        DefaultHttpClient httpclient = new DefaultHttpClient(params);

        HttpPost httpPostRequest = new HttpPost(URL);
        httpPostRequest.setEntity(new UrlEncodedFormEntity(param));
       /* StringEntity se;
        se = new StringEntity(param.toString());
        httpPostRequest.setEntity(se);*/
        //httpPostRequest.setHeader("Accept", "application/json");
        //httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip");

        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(0, resultString.length() - 1);
            System.out.println("!!-- res11=>" + resultString.toString());
            JSONObject jsonObjRecv = new JSONObject(resultString);
            System.out.println("!!-- res=>" + jsonObjRecv.toString());
            return jsonObjRecv;
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
    return null;
}

private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");

        }
    } catch (IOException e) {
       e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

然后在Activity(Inner class)中添加下面的Asynctask类

public class RegisterAsynctask extends AsyncTask<String,Void,JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            baseActivity.showProgressDialog();
             name = et_Name.getText().toString();
             username = et_UserName.getText().toString();
             password = et_Userpass.getText().toString();
             method = "register";
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            try {

                List<NameValuePair> req_params = new ArrayList<NameValuePair>();
                req_params.add(new BasicNameValuePair("name", name));
                req_params.add(new BasicNameValuePair("username", username));
                req_params.add(new BasicNameValuePair("password", ""+password));
                req_params.add(new BasicNameValuePair("method", method));
                JSONObject response = HttpClient.SendHttpPost(your_url, req_params);
                if (response != null) {

                    return response;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject res) {
            super.onPostExecute(res);
            baseActivity.dismissProgressDialog();
            Toast.makeText(getApplicationContext(), res.toString(), Toast.LENGTH_LONG).show();
        }
    }

现在从userReg()方法调用它:

new RegisterAsynctask().execute();
© www.soinside.com 2019 - 2024. All rights reserved.