Android:在数据库中获取数据时出现NullPointerException错误

时间:2014-08-20 03:30:15

标签: android android-sqlite android-contentprovider

这在系统中发生了什么。 1.管理员登录这是在其他活动,但我不会发布它因为它与此无关(没问题) 2.在系统中注册用户(使用数据库没问题) 3.单击添加用户按钮(现有用户所在的位置) register必须在ListView中显示其名称) 问题:当我点击adduser以查看系统是否注册了用户时,它会强行关闭。

CurrentUser.java

package com.example.istronggyminstructor;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.example.istronggyminstructor.registeredUserList.Users;

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

public class CurrentUsers extends Activity {
    private Button register;
    private Button adduser;
    EditText getusertext, getpass, getweight, textdisp;
    View popupview, popupview2;
    public static ArrayList<String> ArrayofName = new ArrayList<String>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_users);
        register = (Button) findViewById(R.id.regbut);
        adduser = (Button) findViewById(R.id.addbut);
        register.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                LayoutInflater inflator = (LayoutInflater) getBaseContext()
                        .getSystemService(LAYOUT_INFLATER_SERVICE);
                popupview = inflator.inflate(R.layout.popup, null);
                final PopupWindow popupWindow = new PopupWindow(popupview,
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                popupWindow.showAtLocation(popupview, Gravity.CENTER, 0, 0);
                popupWindow.setFocusable(true);
                popupWindow.update();
                Button dismissbtn = (Button) popupview.findViewById(R.id.close);
                dismissbtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        popupWindow.dismiss();
                    }
                });
                popupWindow.showAsDropDown(register, 50, -30);
            }
        });
        //Thread.setDefaultUncaughtExceptionHandler(new forceclose(this));
    }



    public void registerUser(View v) {
        EditText username = (EditText) popupview.findViewById(R.id.usertext);
        EditText password = (EditText) popupview
                .findViewById(R.id.passwordtext);
        EditText weight = (EditText) popupview.findViewById(R.id.weight);
        String getUsername = username.getText().toString();
        String getPassword = password.getText().toString();
        String getWeight = weight.getText().toString();

        dataHandler dbHandler = new dataHandler(this, null, null, 1);

        Users user = 
                  new Users(getUsername, getPassword, Integer.parseInt(getWeight));

        dbHandler.addUsers(user);

        Toast.makeText(getApplicationContext(), "Registering...",
                Toast.LENGTH_SHORT).show();
    }

    public void onClick_addUser(View v) {
        LayoutInflater inflator = (LayoutInflater) getBaseContext()
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        popupview2 = inflator.inflate(R.layout.popup2, null);
        final PopupWindow popupWindow = new PopupWindow(popupview2,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        popupWindow.showAtLocation(popupview2, Gravity.CENTER, 0, -10);
        popupWindow.setFocusable(true);
        popupWindow.update();
        Button dismissbtn = (Button) popupview2.findViewById(R.id.close2);
        dismissbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.showAsDropDown(register, 50, -30);


        dataHandler dbHandler = new dataHandler(this, null, null, 1);
        dbHandler.getAllUsers();
        ListView list = (ListView)findViewById(R.layout.popup2);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, ArrayofName);
    //LINE118   list.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.current_users, menu);
        return true;
    }

}

当前用户的XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.16" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick_addUser"
            android:paddingLeft="220dp"
            android:text="@string/title_activity_current_users"
            android:textSize="25sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="98dp"
            android:text="@string/name" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="200dp"
            android:paddingTop="98dp"
            android:text="@string/timein" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="400dp"
            android:paddingTop="98dp"
            android:text="@string/score" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="540dp"
            android:paddingTop="98dp"
            android:text="@string/done" />

        <Button
            android:id="@+id/regbut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/register" />

        <Button
            android:id="@+id/addbut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="505dp"
            android:onClick="onClick_addUser"
            android:text="@string/adduser" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="@string/cleardb" />

    </FrameLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textdisp"
                android:layout_width="match_parent"
                android:layout_height="738dp"
                android:layout_marginTop="30dp" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

registeredUserList.java

package com.example.istronggyminstructor;

public class registeredUserList {

public static class Users {
      private static int _id;
      private static String _users;
      private static String _password;
      private static int _weight;
      private static String[] _workoutlists;
      private static int _score;

      public Users() {

        }

      public Users(String username, String password, int weight) {
            _users = username;
            _password = password;
            _weight = weight;
        }
      public int getId() {
        return _id;
      }

      public static void setId(int id) {
        _id = id;
      }

      public String getUsers() {
        return _users;
      }

      public static void setUsers(String users) {
        _users = users;
      }

      public String getPassword(){
          return _password;
      }

      public void setPassword(String password){
          _password = password;
      }

      public int getWeight(){
          return _weight;
      }

      public static void setWeight(int weight){
          _weight = weight;
      }

      public String[] getWorkoutLists(){
          return _workoutlists;
      }

      public void setWorkoutLists(String[] workoutlists){
          _workoutlists = workoutlists;
      }

      public int score(){
          return _score;
      }

      public void score(int score){
          _score = score;
      }


    } 
}

dataHandler.java

package com.example.istronggyminstructor;


import java.util.ArrayList;
import java.util.List;

import com.example.istronggyminstructor.registeredUserList.Users;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class dataHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "userInfo.db";
    public static final String TABLE_USERINFO = "user";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_WEIGHT = "weight";

    public dataHandler(Context context, String name, CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USER_TABLE = "CREATE TABLE " +
                 TABLE_USERINFO + " ("
                 + COLUMN_ID + " INTEGER PRIMARY KEY, " + COLUMN_USERNAME 
                 + " TEXT," + COLUMN_PASSWORD + " TEXT, " + COLUMN_WEIGHT + " INTEGER " + ");";
          db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERINFO);
          onCreate(db);
    }

    public void addUsers(Users user) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, user.getUsers());
        values.put(COLUMN_PASSWORD, user.getPassword());
        values.put(COLUMN_WEIGHT, user.getWeight());

        SQLiteDatabase db = this.getWritableDatabase();

        db.insert(TABLE_USERINFO, null, values);
        db.close();
}
    public Users findUsers(String username) {
        String query = "Select * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USERNAME
                + " =  \"" + username + "\"";

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(query, null);

        Users user = new Users();

        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            Users.setUsers(cursor.getString(1));
            //Users.setWeight(Integer.parseInt(cursor.getString(3))); not yet needed
            cursor.close();
        } else {
            user = null;
        }
            db.close();
        return user;
    }

    public List<Users> getAllUsers(){
        List<Users> user = new ArrayList();
        String selectQuery = "SELECT * FROM " + TABLE_USERINFO;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                Users users = new Users();
                users.setUsers(cursor.getString(1));

                String name = cursor.getString(1);
                CurrentUsers.ArrayofName.add(name);
                // Adding contact to list
                user.add(users);
            } while (cursor.moveToNext());
        }

        // return user list
        return user;

    }


    public boolean deleteUsers(String username) {

        boolean result = false;

        String query = "Select * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USERNAME + " =  \"" 
        + username + "\"";

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(query, null);

        Users user = new Users();

        if (cursor.moveToFirst()) {
            Users.setId(Integer.parseInt(cursor.getString(0)));
            db.delete(TABLE_USERINFO, COLUMN_ID + " = ?",
                    new String[] { String.valueOf(user.getId()) });
            cursor.close();
            result = true;
        }
            db.close();
        return result;
    }
}

logcat的

08-20 03:23:23.293: E/AndroidRuntime(16363): FATAL EXCEPTION: main
08-20 03:23:23.293: E/AndroidRuntime(16363): java.lang.IllegalStateException: Could not execute method of the activity
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.view.View$1.onClick(View.java:3599)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.view.View.performClick(View.java:4204)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.view.View$PerformClick.run(View.java:17355)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.os.Handler.handleCallback(Handler.java:725)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.os.Looper.loop(Looper.java:137)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.app.ActivityThread.main(ActivityThread.java:5041)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at java.lang.reflect.Method.invokeNative(Native Method)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at java.lang.reflect.Method.invoke(Method.java:511)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at dalvik.system.NativeStart.main(Native Method)
08-20 03:23:23.293: E/AndroidRuntime(16363): Caused by: java.lang.reflect.InvocationTargetException
08-20 03:23:23.293: E/AndroidRuntime(16363):    at java.lang.reflect.Method.invokeNative(Native Method)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at java.lang.reflect.Method.invoke(Method.java:511)
08-20 03:23:23.293: E/AndroidRuntime(16363):    at android.view.View$1.onClick(View.java:3594)
08-20 03:23:23.293: E/AndroidRuntime(16363):    ... 11 more
08-20 03:23:23.293: E/AndroidRuntime(16363): Caused by: java.lang.NullPointerException
08-20 03:23:23.293: E/AndroidRuntime(16363):    at com.example.istronggyminstructor.CurrentUsers.onClick_addUser(CurrentUsers.java:118)
08-20 03:23:23.293: E/AndroidRuntime(16363):    ... 14 more

4 个答案:

答案 0 :(得分:1)

你在xml文件中没有任何listView所以调用

ListView list = (ListView)findViewById(R.layout.popup2);

创建空列表兄弟; - )

你必须创建一个并致电:(R。 id .popup2)

ListView list = (ListView)findViewById(R.id.popup2);

答案 1 :(得分:1)

如果您的身份ListView的{​​{1}}位于popup2文件中,则需要更改此

popup2.xml

ListView list = (ListView)findViewById(R.id.popup2);

答案 2 :(得分:0)

最后一行logcat输出指向您的问题:

at com.example.istronggyminstructor.CurrentUsers.onClick_addUser(CurrentUsers.java:118)

答案 3 :(得分:0)

你的函数getAllUsers()应该是这样的

       public List<String> getAllUsers(){

    List<String> user = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT * FROM " + TABLE_USERINFO;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            user.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return user;
}

并且,在您的onclick功能

   dataHandler db = new dataHandler(getApplicationContext()); // 


    List<String> user = db.getAllUsers();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, user);
    setListAdapter(adapter);