数据库值未在Android中更新

时间:2017-03-25 18:14:27

标签: android

我正在尝试更新服务器上的数据库,但代码似乎有些问题。代码转到catch块,并显示带有null消息的Toast。

public class Test extends AppCompatActivity {

    static String inputLine, data = "";
    HttpURLConnection conn = null;

    String q = "update data set room='ANKUSH' where id='5'";

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

        try {
            URL url = new URL("http://takeyourtime.16mb.com/postdb.php");
            String agent = "Applet";
            String q2 = "insert into user(name,username,password,email) values('AHA','xxxAA','xxxA','xSDxx')";
            String query = "query=" + q2;
            String type = "application/x-www-form-urlencoded";
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", agent);
            conn.setRequestProperty("Content-Type", type);
            conn.setRequestProperty("Content-Length", "" + query.length());

            OutputStream out = conn.getOutputStream();
            out.write(query.getBytes());
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                data = data + inputLine + "\n";
            }
            //data = StringParser.StringPars(data);
            in.close();
            int rc = conn.getResponseCode();
            System.out.print("Response Code = " + rc + "\n");
            String rm = conn.getResponseMessage();
            System.out.print("Response Message = " + rm + "\n");
            Toast.makeText(this, "Response Code = " + rc + "\n", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_SHORT).show();
        } finally {
            conn.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

1)将<uses-permission android:name="android.permission.INTERNET" />添加到您的清单

2)Android阻止主线程的网络连接。