簡體   English   中英

單擊注冊btn時我的android應用程序崩潰

[英]MY android application is crashing when I click on the register btn

運行我的應用程序時,我單擊了注冊按鈕,該應用程序崩潰了。 請在下面找到Log-cat(如果有人可以解釋使用log-cat的最佳方法,那將會很棒),我還包括了Java寄存器。 如果還有更多信息,您需要評論,我將更新此消息。

04-23 21:52:07.835: D/libEGL(28588): loaded /system/lib/egl/libEGL_mali.so 
04-23 21:52:07.875: D/libEGL(28588): loaded /system/lib/egl/libGLESv1_CM_mali.so 
04-23 21:52:07.885: D/libEGL(28588): loaded /system/lib/egl/libGLESv2_mali.so 
04-23 21:52:07.895: E/(28588): Device driver API match 
04-23 21:52:07.895: E/(28588): Device driver API version: 23 
04-23 21:52:07.895: E/(28588): User space API version: 23 
04-23 21:52:07.895: E/(28588):  mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct  9 21:05:57 KST 2013 
04-23 21:52:08.000: D/OpenGLRenderer(28588): Enabling debug mode 0 
04-23 21:52:24.925: D/AndroidRuntime(28588): Shutting down VM 
04-23 21:52:24.925: W/dalvikvm(28588): threadid=1: thread exiting with uncaught exception (group=0x41ba8700) 
04-23 21:52:24.930: E/AndroidRuntime(28588): FATAL EXCEPTION: main 
04-23 21:52:24.930: E/AndroidRuntime(28588): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loggedin/com.loggedin.Register}: java.lang.NullPointerException 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.access$700(ActivityThread.java:159) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Handler.dispatchMessage(Handler.java:99) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Looper.loop(Looper.java:176) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.main(ActivityThread.java:5419) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invokeNative(Native Method) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invoke(Method.java:525) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at dalvik.system.NativeStart.main(Native Method) 
04-23 21:52:24.930: E/AndroidRuntime(28588): Caused by: java.lang.NullPointerException   
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.loggedin.Register.onCreate(Register.java:83) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Activity.performCreate(Activity.java:5372) 
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)

以下代碼是“注冊”頁面

包com.loggedin;

 import android.app.Activity;
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;
 import com.loggedin.internal.DatabaseHandler;
 import com.loggedin.internal.UserFunctions;
 import org.json.JSONException;
 import org.json.JSONObject;
 import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;

public class Register extends Activity {
/**
 *  JSON Response node names.
 **/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "id";
private static String KEY_FIRSTNAME = "FirstName";
private static String KEY_LASTNAME = "LastName";
private static String KEY_USERNAME = "Username";
private static String KEY_EMAIL = "email";
private static String KEY_DOB = "DOB";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
 * Defining layout items.
 **/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputDOB;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_register);
/**
 * Defining all layout items
 **/
    inputFirstName = (EditText) findViewById(R.id.FirstName);
    inputLastName = (EditText) findViewById(R.id.LastName);
    inputUsername = (EditText) findViewById(R.id.Username);
    inputEmail = (EditText) findViewById(R.id.email);
    inputDOB = (EditText) findViewById(R.id.DOB);
    inputPassword = (EditText) findViewById(R.id.Password);
    btnRegister = (Button) findViewById(R.id.registerbtn1);
    registerErrorMsg = (TextView) findViewById(R.id.register_error);
   /**
 * Button which Switches back to the login screen on clicked
 **/
    Button login = (Button) findViewById(R.id.bktologinbtn);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Login.class);
            startActivityForResult(myIntent, 0);
            finish();
        }
    });
    /**
     * Register Button click event.
     * A Toast is set to alert when the fields are empty.
     * Another toast is set to alert Username must be 5 characters.
     **/
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
       if (  ( !inputUsername.getText().toString().equals("")) && (      !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals(""))  && ( !inputDOB.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
            {
                if ( inputUsername.getText().toString().length() > 4 ){
                InternetAsync(view);
                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(getApplicationContext(),
                        "One or more fields are empty", Toast.LENGTH_SHORT).show();
            }
        }
    });
   }
 /**
 * Async Task to check whether internet connection is working
 **/
  private class InternetCheck extends AsyncTask<String, Boolean, Boolean>   {
    private ProgressDialog nDialog;
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        nDialog = new ProgressDialog(Register.this);
        nDialog.setMessage("Loading..");
        nDialog.setTitle("Checking Network");
        nDialog.setIndeterminate(false);
        nDialog.setCancelable(true);
        nDialog.show();
    }
    @Override
    protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
        ConnectivityManager cm = (ConnectivityManager)   getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }
    @Override
    protected void onPostExecute(Boolean th){
        if(th == true){
            nDialog.dismiss();
            new ProcessRegister().execute();
        }
        else{
            nDialog.dismiss();
            registerErrorMsg.setText("Error in Network Connection");
        }
    }
}
  private class ProcessRegister extends AsyncTask <String, String, JSONObject>{
  /**
 * Defining Process dialog
 **/
    private ProgressDialog pDialog;
    String email,Password,FirstName,LastName,DOB,Username;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.Username);
        inputPassword = (EditText) findViewById(R.id.Password);
           FirstName = inputFirstName.getText().toString();
           LastName = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            DOB = inputDOB.getText().toString();
            Username= inputUsername.getText().toString();
            Password = inputPassword.getText().toString();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Registering ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected JSONObject doInBackground(String... args) {
    UserFunctions userFunction = new UserFunctions();
    JSONObject json = userFunction.registerUser(FirstName, LastName, DOB, email, Username, Password);
        return json;
    }
   @Override
    protected void onPostExecute(JSONObject json) {
   /**
    * Checks for success message.
    **/
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);
                    String red = json.getString(KEY_ERROR);
                    if(Integer.parseInt(res) == 1){
                        pDialog.setTitle("Getting Data");
                        pDialog.setMessage("Loading Info");
                        registerErrorMsg.setText("Successfully Registered");
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");
                        /**
                         * Removes all the previous data in the SQlite database
                         **/
                        UserFunctions logout = new UserFunctions();
                        logout.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
                        /**
                         * Stores registered data in SQlite Database
                         * Launch Registered screen
                         **/
             Intent registered = new Intent(getApplicationContext(),Registered.class);
                        /**
                         * Close all views before launching Registered screen
                        **/
                        registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        pDialog.dismiss();
                        startActivity(registered);
                          finish();
                    }
                    else if (Integer.parseInt(red) ==2){
                        pDialog.dismiss();
                        registerErrorMsg.setText("User already exists");
                    }
                    else if (Integer.parseInt(red) ==3){
                        pDialog.dismiss();
                        registerErrorMsg.setText("Invalid Email id");
                    }
                }
                    else{
                    pDialog.dismiss();
                        registerErrorMsg.setText("Error occured in registration");
                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
     }
     public void InternetAsync(View view){
         new InternetCheck().execute();
    }
    }

使用logcat時的一些建議...

E / AndroidRuntime(28588): 由以下原因引起:java.lang.NullPointerException
E / AndroidRuntime(28588):位於com.loggedin.Register.onCreate( Register.java:83

您始終可以進行快速的文本搜索以查找出由何原因造成的:您可以找出錯誤的出處.Logcat還會顯示在案例行#83中也拋出了錯誤。

我建議也研究如何正確使用調試器,這非常重要:

正如Mike所說,調試器可以真正幫助您發現問題。 在這種情況下,該行是:

 btnRegister.setOnClickListener(new View.OnClickListener() {

問題是當您使用findViewById時:

public View findViewById (int id)
Added in API level 1
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns
The view if found or null otherwise.

這意味着findViewById返回一個空指針:),因此,請在XML布局中檢查您的ID。

錯誤很明顯,關於使用調試器和logcat,ppl正確表示。

無論如何,以下是我的觀點:1.請交叉檢查您的xml文件activity_register.xml,它具有您在此處使用的ID。

  1. 由於錯誤發生在按鈕的onclick上,然后嘗試使用try-catch捕獲onlick內的所有內容,因此也使整個按鈕在try-catch內單擊均獲得了支持。 添加兩個具有不同味精的Toast,以標識引發異常的位置。

  2. 您也可以簡單地在獲得ID后在創建時在其中添加Log msg,例如Log.e(“ IS_REGISTER_BUTTON_NULL”,“ Value:” + btnRegister),如果ID不為null,則會寫入其他字符,然后返回null。 還刪除onlick內的所有內容,並查看每個字符串值,例如

字符串uName = inputUsername.getText()。toString(); 字符串pWd = inputPassword.getText()。toString();

Log.e(“ CHECKING_IF_STRING_ARE_NULL”,uName +“” + pWd +“” + eMail + .....);

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM