Android连接PHP和MySql强制关闭

时间:2012-11-14 14:39:36

标签: php android mysql

我正在编写一个需要登录和注册的应用程序,所以我在网上查找了一些教程。我还买了和在线托管服务器来存储我的数据库。但是,在运行应用程序时,我不断遇到运行时错误。我已经抓了一整天,仍然不知道这个问题。我很感激,如果有人能给我一些提示或线索,谢谢。

Log Cat错误

11-14 22:22:13.071: E/AndroidRuntime(12901): FATAL EXCEPTION: main
11-14 22:22:13.071: E/AndroidRuntime(12901): android.os.NetworkOnMainThreadException
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at com.example.trafficmaster.library.JSONParser.getJSONFromUrl(JSONParser.java:42)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at com.example.trafficmaster.library.UserFunctions.registerUser(UserFunctions.java:61)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at com.example.trafficmaster.RegisterActivity$1.onClick(RegisterActivity.java:55)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.view.View.performClick(View.java:4211)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.view.View$PerformClick.run(View.java:17267)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.os.Handler.handleCallback(Handler.java:615)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.os.Looper.loop(Looper.java:137)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at android.app.ActivityThread.main(ActivityThread.java:4898)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at java.lang.reflect.Method.invokeNative(Native Method)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at java.lang.reflect.Method.invoke(Method.java:511)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
11-14 22:22:13.071: E/AndroidRuntime(12901):    at dalvik.system.NativeStart.main(Native Method)
11-14 22:22:18.251: D/dalvikvm(12901): GC_CONCURRENT freed 357K, 11% free 12504K/13895K, paused 4ms+9ms, total 46ms
11-14 22:22:25.251: I/Process(12901): Sending signal. PID: 12901 SIG: 9

我的注册主类

public class RegisterActivity extends Activity {
    Button btnRegister;
    Button btnLinkToLogin;
    EditText inputFullName;
    EditText inputEmail;
    EditText inputPassword;
    TextView registerErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.registerName);
        inputEmail = (EditText) findViewById(R.id.registerEmail);
        inputPassword = (EditText) findViewById(R.id.registerPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                new MyInnerClass().execute();

                String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(name, email, password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully registred
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Registration Screen
                            finish();
                        }else{
                            // Error in registration
                            registerErrorMsg.setText("Error occured in registration");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

2 个答案:

答案 0 :(得分:3)

android.os.NetworkOnMainThreadException

从主线程访问网络时会发生此异常。使用AsyncTask来访问网络。

   private class MyInnerClass extends AsyncTask<String, Void, String> {
   @Override
   protected void onPreExecute() {
   super.onPreExecute();

   }

   @Override
   protected String doInBackground(String params) {

   return "Done";
   }

   @Override
   protected void onPostExecute(String result) {
   super.onPostExecute(result);
   }
   }

从您的主Activity调用new MyInnerClass().execute();,Android会自动调用onPreExecute()。此方法适用于您在网络访问之前所做的事情

网络相关内容在doInBackground()内完成,然后Android将调用onPostExecute(),结果将作为参数传递给此方法。

答案 1 :(得分:0)

您正在主线程上执行(可能很慢)网络操作。如果您的目标SDK是11(Honeycomb)或更高,这将在Honeycomb或更高版本上抛出NetworkOnMainThreadException,因为此行为可能会阻止UI并导致应用程序无响应。

您可以使用AsyncTask解决此问题,将数据加载到doInBackground(..)