简体   繁体   中英

Unable to populate data in listView from Database in Android

I am developing one android app in which I want to store my employee details. I am unable to load data in ListView from Database.

DatabaseHelper.java

\\import statement 
 public class DatabaseHelper extends SQLiteOpenHelper{

    public static final String EMPLOYEE_ID = "EmployeeId";
    public static final String EMPLOYEE_NAME = "Name";
    public static final String EMPLOYEE_USERNAME = "Username";
    public static final String EMPLOYEE_PASSWORD = "Password";
    public static final String EMPLOYEE_MANGER_ID = "ManagerId";

    public static final String CREATE_TABLE_EMPLOYEE = "CREATE TABLE "+TABLE_NAME_EMPLOYEE+" ("+EMPLOYEE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+EMPLOYEE_NAME+" varchar(30), "+EMPLOYEE_USERNAME+" varchar(8), "+EMPLOYEE_PASSWORD+" varchar(10), "+EMPLOYEE_MANGER_ID+" Int);";

    public static final String DROP_TABLE_EMPLOYEE = "DROP TABLE "+TABLE_NAME_EMPLOYEE+" IF EXISTS";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;         
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_TABLE_EMPLOYEE);
        } catch (SQLException e) {
            //toast message
        }
        //toast message
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        try {
            db.execSQL(DROP_TABLE_EMPLOYEE);
            onCreate(db);
        } catch (SQLException e) {
            //toast message 
        }
        //toast message
    }   
}

I have another class for handling only employeetable such as inserting, deleting, etc ie EmployeeDatabaseHelper derived from DatabaseHelper.

EmployeeDatabaseHelper.java

\\import statement
public class EmployeeDatabaseHelper extends DatabaseHelper{

public EmployeeDatabaseHelper(Context context) {
    super(context); 
}

public Cursor getAllEmployee(){

    ArrayList<Employee> employeeArrayList = new ArrayList<Employee>();
    String sql = "select * from tblEmployee";
    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.moveToFirst()) {
        do{
            Employee e  = new Employee();
            e.name = cursor.getString(cursor.getColumnIndex(EMPLOYEE_NAME));
            employeeArrayList.add(e);               
        } while (cursor.moveToNext());
    }       
    return cursor;  
}
}

EmployeeFragment in this section my code is wrong It is giving null pointer Exception. My application close when I open Employeefragment.

EmployeeFragment.java

public class EmployeeFragment extends Fragment {

EmployeeDatabaseHelper dbHelper;
ListView employeeList;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_employee, container, false);
    employeeList = (ListView) rootView.findViewById(R.id.employeeList);
    populateEmployeeList();
    return rootView;
}

public void populateEmployeeList(){

    Cursor cursor = dbHelper.getAllEmployee();
    String[] data = new String[] {dbHelper.EMPLOYEE_ID, dbHelper.EMPLOYEE_NAME};
    int[] id = new int[] {R.id.mainTextView, R.id.subTextView};
    SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(getActivity(), R.layout.row, cursor, data, id);
    employeeList.setAdapter(myAdapter);

}
}

And Employee.java is my another class

public class Employee {
 public String username;
 public String name;
 public String password;        
}

In row.xml I have nothing great only two textView. (ie mainTextView,subTextView) and In fragment_employee.xml I have one button to add new employee. and one list to view all employee. I stucked here. if I comment this populateEmployeeList() class then my program works. otherwise it get closed unexpectedly.

LOG cat

 FATAL EXCEPTION: main
  Process: com.threepin.deepakcorporation, PID: 9393
  java.lang.IllegalArgumentException: column '_id' does not exist
  at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
  at android.widget.CursorAdapter.init(CursorAdapter.java:172)
  at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
  at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:52)
  at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:78)
  at com.threepin.deepakcorporation.EmployeeFragment.populateEmployeeList(EmployeeFragment.java:61)
  at com.threepin.deepakcorporation.EmployeeFragment.onActivityCreated(EmployeeFragment.java:52)
  at android.app.Fragment.performActivityCreated(Fragment.java:1708)
  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:908)
  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
  at android.app.BackStackRecord.run(BackStackRecord.java:684)
  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
  at android.os.Handler.handleCallback(Handler.java:733)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:136)
  at android.app.ActivityThread.main(ActivityThread.java:5127)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
  at dalvik.system.NativeStart.main(Native Method)

Try to use populateEmployeeList() in onActivityCreated() method of fragment. Because as per your code, your view is not completed yet and you are trying to fill the listview by calling populateEmployeeList() .

Column _id does not exist, just read your error carefully. You have to take the _id field:

@Override
public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
    String sql="CREATE TABLE tableEQ (_ID INTEGER PRIMARY KEY," ...

}

if I comment this populateEmployeeList() class then my program works. otherwise it get closed unexpectedly

Because dbHelper is null when calling getAllEmployee method from EmployeeDatabaseHelper class.

To fix issue, create object of EmployeeDatabaseHelper class by passing Context in class constructor before using dbHelper object to access methods from class:

 dbHelper=new EmployeeDatabaseHelper(getActivity());
 Cursor cursor = dbHelper.getAllEmployee();

I have changed my code. Its running. I don't know it will help others or not but still.

No changes in DatabaseHelper.java

EmployeeDatabaseHelper.java

public class EmployeeDatabaseHelper {
DatabaseHelper dbhelper;

public EmployeeDatabaseHelper(Context applicationContext) {
    dbhelper= new DatabaseHelper(applicationContext);
}

public long insertEmployee(String name, String username, String password){
    SQLiteDatabase db = dbhelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(EMPLOYEE_NAME,name);
    cv.put(EMPLOYEE_USERNAME,username);
    cv.put(EMPLOYEE_PASSWORD,password);
    long id = db.insert(TABLE_NAME_EMPLOYEE, null, cv);
    db.close();
    return id;      
}

public ArrayList<Employee> getAllEmployee(){

    ArrayList<Employee> employeeArrayList = new ArrayList<Employee>();
    SQLiteDatabase db = dbhelper.getWritableDatabase();
    Cursor cursor = db.query(TABLE_NAME_EMPLOYEE, null,null,null,null,null,null);

        while (cursor.moveToNext()) {
            Employee e  = new Employee();
            e.name = cursor.getString(cursor.getColumnIndex(EMPLOYEE_NAME));
            e.username = cursor.getString(cursor.getColumnIndex(EMPLOYEE_USERNAME));
            employeeArrayList.add(e);
        } 

    db.close();
    return employeeArrayList;
}
}

EmployeeFragment.java

public class EmployeeFragment extends Fragment {

EmployeeDatabaseHelper dbHelper;
ListView employeeList;
public Cursor employees;
private ArrayList<Employee> arrlst;
private myadapter myadapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_employee, container, false);

    employeeList = (ListView) rootView.findViewById(R.id.employeeList);
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    populateEmployeeList();
}

public void populateEmployeeList(){

    dbHelper=new EmployeeDatabaseHelper(getActivity());
     arrlst = dbHelper.getAllEmployee();
    myadapter = new myadapter(getActivity());
    employeeList.setAdapter(myadapter);

}

class myadapter extends ArrayAdapter<Employee>{
Activity con;
private LayoutInflater Inflater;

public myadapter(Activity context) {
    super(context,R.layout.row);
    con=context;
     Inflater = (LayoutInflater)con.getSystemService(con.LAYOUT_INFLATER_SERVICE);
}

class ViewHolder{
    TextView tvid;
    TextView tvname;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View vi = convertView;
     ViewHolder vh;
    if(vi==null){
        vh = new ViewHolder();
        vi= Inflater.inflate(R.layout.row, null);
        vh.tvid=(TextView)vi.findViewById(R.id.mainTextView);

        vh.tvname=(TextView)vi.findViewById(R.id.subTextView);
        vi.setTag(vh);

    }else{
        vh=(ViewHolder)vi.getTag();
    }
    Employee e =arrlst.get(position);
    vh.tvid.setText(e.name);
    vh.tvname.setText(e.username);
    return vi;
}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return arrlst.size();
}
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM