当我点击寄存器btn时,我的android应用程序崩溃了

时间:2014-04-23 21:28:02

标签: java android

在运行我的应用程序时,我点击注册按钮,应用程序崩溃了。请在下面找到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)

以下代码是注册页面

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

3 个答案:

答案 0 :(得分:3)

使用logcat时的一些建议...

E / AndroidRuntime(28588):引起:java.lang.NullPointerException
E / AndroidRuntime(28588):at com.loggedin.Register.onCreate( Register.java:83

你总是可以快速进行文本搜索,检查所造成的:你可以找出你出错的地方.Logcat还会在你的案例行#83中显示错误被抛出的位置。

我建议也要考虑如何正确使用调试器,这非常重要:

答案 1 :(得分:2)

正如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。

答案 2 :(得分:0)

错误是显而易见的,ppl正确地说使用了调试器和logcat ..

无论如何以下是我的意见: - 1. plz交叉检查你的xml文件activity_register.xml,它有你在这里使用的id。

  1. 因为错误发生在按钮的onclick上,然后尝试捕获异常中的所有内容,使用try-catch也可以在try-catch中单击整个按钮。添加两个具有不同消息的Toast,以识别引发异常的位置。

  2. 你也可以在获取id之后简单地添加Log msg这样的Log.e(“IS_REGISTER_BUTTON_NULL”,“Value:”+ btnRegister),如果它不为null,它将写入除null之外的其他字符。同时删除onlick中的所有内容,并查看每个字符串值,如

  3. String uName = inputUsername.getText()。toString(); String pWd = inputPassword.getText()。toString(); 。 。

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

    THX