单击应用程序时按钮在android片段中出现崩溃

时间:2013-05-27 07:22:09

标签: android android-fragments

我有使用按钮的片段类,按钮必须登录用户(如果存在)或必须显示文本用户无效。我使用sqlite数据库。但问题是,当我点击登录按钮时,我的应用程序崩溃了。 这是Frag

的附加代码
public class FirstFragment extends Fragment {

LoginDataBaseAdapter loginDataBaseAdapter;
String userName;
EditText testUser;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.firstfragment,container,false);

    // create a instance of SQLite Database
    loginDataBaseAdapter = new LoginDataBaseAdapter(getActivity());
    loginDataBaseAdapter = loginDataBaseAdapter.open();


    //get the reference of the design


   final  testUser = (EditText) view.findViewById(R.id.editTextUserNameToLogin);
    final EditText testPassword = (EditText) view.findViewById(R.id.editTextPasswordToLogin);
    final Button btnLogin = (Button) view.findViewById(R.id.buttonSignIn);
    final Button btnCreate=(Button)view.findViewById(R.id.buttonCreateAccount);

    //set OnClick Listener on login button

    btnLogin.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

             userName=testUser.getText().toString();

              EditText testPassword = (EditText) getActivity().findViewById(R.id.editTextPasswordToLogin);
              String password = testPassword.getText().toString();


            //fetch the password from the database for respective user name

            String storedPassword = loginDataBaseAdapter.getSinlgeEntry(userName);
            Toast.makeText(getActivity(),storedPassword,1).show();

            // check if the Stored password matches with  Password entered by user
            if (password.equals(storedPassword)) {
                Toast.makeText(getActivity(), "Congrats:Login Sucessfull", Toast.LENGTH_LONG).show();

           } else {
             Toast.makeText(getActivity(), "User Name or Password does not match", Toast.LENGTH_LONG).show();
          }




        }
    });
return view;
}

我的Db类“LoginDataBaseAdapter”我有一个函数可以检查我们传递用户名的密码。这是代码

 public String getSinlgeEntry(String userName) {
    Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
    if (cursor.getCount() < 1) // UserName Not Exist
    {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
    return password;
}

现在我无法弄清楚我失踪的地方。当我点击登录按钮时,我的应用程序崩溃了。 提前谢谢。

我的logcat:

   java.lang.NullPointerException
        at com.example.betatestregister.LoginDataBaseAdapter.getSinlgeEntry(LoginDataBaseAdapter.java:68)
        at com.example.betatestregister.FirstFragment$1.onClick(FirstFragment.java:52)
        at android.view.View.performClick(View.java:4204)
        at android.view.View$PerformClick.run(View.java:17355)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

我的LoginDataBaseAdapter类代码:

package com.example.betatestregister;

/ **  *由Rohan于2013年5月24日创建。  * /

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import android.widget.Toast;




public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table " + "LOGIN" +
        "( " + "ID" + " integer primary key autoincrement," + "USERNAME  text,PASSWORD 
text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;

public LoginDataBaseAdapter(Context _context) {
    context = _context;
    dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public LoginDataBaseAdapter open() throws SQLException {

//        db = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    db.close();
}

public SQLiteDatabase getDatabaseInstance() {
    return db;
}

public void insertEntry(String userName, String password) {
    ContentValues newValues = new ContentValues();
    // Assign values for each row.
    newValues.put("USERNAME", userName);
    newValues.put("PASSWORD", password);

    // Insert the row into your table
    db.insert("LOGIN", null, newValues);
    ///Toast.makeText(context, "Reminder Is Successfully Saved", 
Toast.LENGTH_LONG).show();
}

public int deleteEntry(String UserName) {
    //String id=String.valueOf(ID);
    String where = "USERNAME=?";
    int numberOFEntriesDeleted = db.delete("LOGIN", where, new String[]{UserName});
    // Toast.makeText(context, "Number fo Entry Deleted Successfully : 
"+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
    return numberOFEntriesDeleted;
}

public String getSinlgeEntry(String userName) {
    Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, 
null, null, null);
    if (cursor.getCount() < 1) // UserName Not Exist
    {
        cursor.close();
      //  Toast.makeText(context, "Number fo Entry Deleted Successfully : 
"+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
    return password;
}

public void updateEntry(String userName, String password) {
    // Define the updated row content.
    ContentValues updatedValues = new ContentValues();
    // Assign values for each row.
    updatedValues.put("USERNAME", userName);
    updatedValues.put("PASSWORD", password);

    String where = "USERNAME = ?";
    db.update("LOGIN", updatedValues, where, new String[]{userName});
}

}

3 个答案:

答案 0 :(得分:1)

loginDataBaseAdapter = loginDataBaseAdapter.open(); 

删除上述代码。
仅限使用

loginDataBaseAdapter.open();  

在创建实例后,您正在修改登录Data BaseAdapter。

答案 1 :(得分:1)

public LoginDataBaseAdapter open() throws SQLException {

//        db = dbHelper.getWritableDatabase();
    return this;
}

取消注释此行

//        db = dbHelper.getWritableDatabase();

此方法现在什么都不做,但应该得到一个可写的数据库实例。 它没有这样做,因此db为null,你得到了NPE。

答案 2 :(得分:1)

在你的情况下你得到一些null的光标。首先你必须检查它为空的原因。但是为了防止当光标为空时崩溃应用程序,你可能会做这样的事情:

    String storedPassword="";
    String checkPassowrd = loginDataBaseAdapter.getSinlgeEntry(userName);

    if(checkPassword!=null){

     storedPassword = checkPassword;

    }

我建议你像这样设置你的getSingleEntry方法:

    public String getSinlgeEntry(String userName) {
     Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
     if (cursor.getCount() < 1) // UserName Not Exist
          {
            cursor.close();
              return "NOT EXIST";
        }else{
       cursor.moveToFirst();
      String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
       cursor.close();
       return password;
      }
   }

令我恼火的是,你真的想让你的光标放在第一个条目上吗?没有cursor.MoveToNext()?