本文介绍了NullPointerException异常发生在一个Android code段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的code其中涉及会员注册。

 公共类RegisterActivity延伸活动{
    私有静态最后字符串变量= RegisterActivity.class.getSimpleName();
    私人按钮btnRegister;
    私人按钮btnLinkToLogin;
    私人的EditText inputFullName;
    私人的EditText inputEmail;
    私人的EditText控件inputPassword;
    私人ProgressDialog pDialog;
    私人是SessionManager会议;
    私人SQLiteHandler分贝;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_register);

        inputFullName =(EditText上)findViewById(R.id.name);
        inputEmail =(EditText上)findViewById(R.id.email);
        控件inputPassword =(EditText上)findViewById(R.id.password);
        btnRegister =(按钮)findViewById(R.id.btnRegister);
        btnLinkToLogin =(按钮)findViewById(R.id.btnLinkToLoginScreen);

        //进度对话框
        pDialog =新ProgressDialog(本);
        pDialog.setCancelable(假);

        //会话管理器
        会议=新SessionManager(中间getApplicationContext());

        // SQLite数据库处理程序
        DB =新SQLiteHandler(getApplicationContext());

        //检查是否已经登录用户或不
        如果(session.isLoggedIn()){
            //已经登录的用户在乘坐他的主要活动
            意向意图=新的意图(RegisterActivity.this,
                MainActivity.class);
            startActivity(意向);
            完();
        }

        //注册按钮点击事件
        btnRegister.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图查看){
                字符串名称= inputFullName.getText()的toString()。
                。字符串email = inputEmail.getText()的toString();
                。字符串password = inputPassword.getText()的toString();

                如果(name.isEmpty()及!&安培;!email.isEmpty()&安培;&安培;!password.isEmpty()){
                    registerUser(姓名,电子邮件,密码);
                 } 其他 {
                    Toast.makeText(getApplicationContext(),
                            请输入您的详细信息!,Toast.LENGTH_LONG)
                        。显示();
                }
            }
        });

        //链接登录屏幕
        btnLinkToLogin.setOnClickListener(新View.OnClickListener(){

            公共无效的onClick(视图查看){
                意图I =新的意图(getApplicationContext()
                        LoginActivity.class);
                startActivity(ⅰ);
                完();
            }
        });

    }

    / **
     *在MySQL数据库函数来存储用户将post数据(标签,名称,
     *电子邮件,密码)注册网址
     * * /
    私人无效registerUser(最后的字符串名称,最后弦乐电子邮件,
                          最终的字符串密码){
        //标签用于取消该请求
        字符串tag_string_req =req_register;

        pDialog.setMessage(注册...);
        的ShowDialog();

        StringRequest strReq =新StringRequest(Method.POST,
                AppConfig.URL_REGISTER,新Response.Listener<字符串>(){

            @覆盖
            公共无效onResponse(字符串响应){
                Log.d(TAG,注册回应:+ response.toString());
                hideDialog();

                尝试 {
                    JSONObject的jObj =新的JSONObject(响应);
                    布尔错误= jObj.getBoolean(错误);
                    如果(!错误){
                        //用户成功存储在MySQL中
                        //现在存放在sqlite的用户
                        字符串的uid = jObj.getString(UID);

                        JSONObject的用户= jObj.getJSONObject(用户);
                        字符串名称= user.getString(姓名);
                        字符串email = user.getString(电子邮件);
                        字符串created_at =用户
                            .getString(created_at);

                        //插入在用户表行
                        db.addUser(姓名,电子邮件,UID,created_at);

                        //启动登录活动
                        意向意图=新的意图(
                            RegisterActivity.this,
                            LoginActivity.class);
                        startActivity(意向);
                        完();
                    } 其他 {

                        //发生登记错误。得到的错误
                        // 信息
                        串ERRORMSG = jObj.getString(ERROR_MSG);
                        Toast.makeText(getApplicationContext(),
                            ERRORMSG,Toast.LENGTH_LONG).show();
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
                }

            }
        },新Response.ErrorListener(){

            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                Log.e(TAG,注册错误:+ error.getMessage());
                Toast.makeText(getApplicationContext(),
                    error.getMessage(),Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }){

            @覆盖
            保护地图<字符串,字符串> getParams()方法{
                //发布PARAMS注册网址
                地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
                params.put(标签,注册);
                params.put(姓名,名);
                params.put(邮件,邮件);
                params.put(密码,密码);

                返回PARAMS;
            }

        };

        //添加请求,请求队列
        。AppController.getInstance()addToRequestQueue(strReq,tag_string_req);
    }

    私人无效的ShowDialog(){
        如果(!pDialog.isShowing())
            pDialog.show();
    }

    私人无效hideDialog(){
        如果(pDialog.isShowing())
            pDialog.dismiss();
    }
    }
 

当我运行code,它抛出一个 NullPointerException异常,呈现出以下日志。

据日志,似乎有问题的片段是:

这是 registerUser 方法的最后一行。

您如何看待这个问题?如果有任何信息,您应该进一步了解这个code,请让我知道。

AppController的类如下:

 公共类AppController的扩展应用{

    公共静态最终字符串变量= AppController.class.getSimpleName();

    私人请求队列mRequestQueue;

    私有静态AppController的mInstance;

    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        mInstance =这一点;
    }

    公共静态同步的AppController的getInstance(){
        返回mInstance;
    }

    公共请求队列getRequestQueue(){
        如果(mRequestQueue == NULL){
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        返回mRequestQueue;
    }

    公众< T>无效addToRequestQueue(请求< T> REQ,字符串变量){
        req.setTag(?TextUtils.isEmpty(标签)标签:标签);
        。getRequestQueue()加(REQ);
    }

    公众< T>无效addToRequestQueue(请求< T> REQ){
        req.setTag(TAG);
        。getRequestQueue()加(REQ);
    }

    公共无效cancelPendingRequests(对象标签){
        如果(mRequestQueue!= NULL){
            mRequestQueue.cancelAll(标签);
        }
    }
}
 

的Manifest.xml:

 <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>

<应用
    机器人:allowBackup =真
    机器人:图标=@纹理映射/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名称=。ui.LoginActivity
        机器人:标签=@字符串/ APP_NAME
        机器人:launchMode =singleTop
        机器人:windowSoftInputMode =adjustPan>
        <意向滤光器>
            <作用机器人:名称=android.intent.action.MAIN/>

            <类机器人:名称=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
    <活动
        机器人:名称=。ui.RegisterActivity
        机器人:标签=@字符串/ APP_NAME
        机器人:launchMode =singleTop
        机器人:windowSoftInputMode =adjustPan/>
    <活动
        机器人:名称=。ui.MainActivity
        机器人:标签=@字符串/ APP_NAME
        机器人:launchMode =singleTop/>
< /用途>
 

解决方案

问题是你没有申报您的应用程序的Andr​​oidManifest的子类。添加安卓名=path.to.AppController到应用程序标记,否则你的应用程序的子类不被实例和 mInstance 仍然未初始化(默认为空)。这解释了NPE

 <应用
    机器人:名称=path.to.AppController
    机器人:allowBackup =真
    机器人:图标=@纹理映射/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
 

Here's the code which deals with member registration.

public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputFullName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(RegisterActivity.this,
                MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();

                if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                    registerUser(name, email, password);
                 } else {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * Function to store user in MySQL database will post params(tag, name,
     * email, password) to register url
     * */
    private void registerUser(final String name, final String email,
                          final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                            .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch login activity
                        Intent intent = new Intent(
                            RegisterActivity.this,
                            LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "register");
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    }

When I run the code, it throws a NullPointerException, showing the following logs.

According to the log, the snippet that seems to have the problem is:

Which is the last line of the registerUser method.

What do you think the problem is? If there is any information that you should know further about this code, please let me know.

The AppController class is as follows.

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Manifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ui.LoginActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ui.RegisterActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" />
    <activity
        android:name=".ui.MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop" />
</application>
解决方案

the problem is you didn't declare your Subclass of Application to the AndroidManifest. Add android:name="path.to.AppController" to the Application tag, otherwise your subclass of Application is not instantiated and mInstance remains not initialized (null by default). And that explains the NPE

 <application
    android:name="path.to.AppController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

这篇关于NullPointerException异常发生在一个Android code段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:06