Android Connecting with PHP and MySql Force Close

2019-10-21 01:44发布

I was writing an application that required login and registration, so I look up some tutorials on the net. I also bought and online hosting server to store my database. However I keep getting run time error while running the applications. I've been scratching for one whole day and still dont know the problem. I'd appreciate if anyone can give me some hint or clue, thank you.

Log Cat Error

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

My Register Main Class

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条回答
Fickle 薄情
2楼-- · 2019-10-21 02:19
android.os.NetworkOnMainThreadException

This exception occurs when you access network from your main thread. Use AsyncTask to access network as such.

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

Call new MyInnerClass().execute(); from you main Activity and Android will automatically call onPreExecute(). This method is for the stuff you wana do before network access

Network related stuff is done inside doInBackground() and then Android will call onPostExecute() and the result will be passed as params to this method.

查看更多
淡お忘
3楼-- · 2019-10-21 02:24

You're performing a (potentially slow) network operation on the main thread. If your target SDK is 11 (Honeycomb) or higher this will throw a NetworkOnMainThreadException on Honeycomb or above, because this behaviour can block the UI and lead to an unresponsive app.

You could use an AsyncTask to get around this, loading the data in its doInBackground(..).

查看更多
登录 后发表回答