使用数据库弹出列表视图

时间:2016-01-27 05:39:34

标签: android database listview

我尝试让我的列表视图显示在数据库中保存的数据

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    ImageView contactImage;
    final EditText nametxt, emailTxt, phoneTxt, addressTxt;
    nametxt = (EditText) view.findViewById(R.id.txtName);
    emailTxt = (EditText) view.findViewById(R.id.txtEmail);
    phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
    addressTxt = (EditText) view.findViewById(R.id.txtAddress);
    dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
    contactListView=(ListView)view.findViewById(R.id.listView);
    contactListView.setAdapter(contactAdapter);

    final Button addBtn = (Button) view.findViewById(R.id.btnadd);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
            import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
            if (!contactExists(contact)) {
                dbHandler.createContact(contact);
                Contacts.add(contact);
                if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
                Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
                resetAddContactPanel();
                return;
            }
            Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
        }
    });



    final Button addContact = (Button) view.findViewById(R.id.btnadd);

    nametxt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));


        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });


    return view;


}

ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;



public void onActivityResult(int reqCode, int resCode, Intent data) {
    Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
    ImageView contactImageImgView;
    contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);

    if (resCode == Activity.RESULT_OK) {
        if (reqCode == 1) {
            imageUri = data.getData();
            contactImageImgView.setImageURI(data.getData());
        }
    }
}


private void resetAddContactPanel() {
    final EditText nametxt, emailTxt, phoneTxt, addressTxt;
    nametxt = (EditText) getActivity().findViewById(R.id.txtName);
    emailTxt = (EditText) getActivity().findViewById(R.id.txtEmail);
    phoneTxt = (EditText) getActivity().findViewById(R.id.txtPhone);
    addressTxt = (EditText) getActivity().findViewById(R.id.txtAddress);
    nametxt.setText("");
    phoneTxt.setText("");
    emailTxt.setText("");
    addressTxt.setText("");
}

public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);

    {
        ImageView contactImageImgView;

        contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);

        contactImageImgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
            }

        });


        if (dbHandler.getContactsCount() != 0)
            Contacts.addAll(dbHandler.getAllContacts());

        populateList();
    }


    menu.setHeaderIcon(R.drawable.pencil_icon);
    menu.setHeaderTitle("Contact Options");
    menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
    menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}


public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case EDIT:
            // TODO: Implement editing a contact
            break;
        case DELETE:
            dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
            Contacts.remove(longClickedItemIndex);
            contactAdapter.notifyDataSetChanged();
            break;
    }

    return super.onContextItemSelected(item);
}



private boolean contactExists(import_fragment.Contact contact) {

    String name = contact.getName();
    int contactCount = Contacts.size();

    for (int i = 0; i < contactCount; i++) {
        if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
            return true;
    }
    return false;
}


private void populateList() {
    contactAdapter = new ContactListAdapter(getActivity());
    contactListView.setAdapter(contactAdapter);
}


final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();

private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
    public ContactListAdapter(Context cntx) {
        super(cntx, R.layout.fragment_import, Contacts);
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null)
            view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);

        import_fragment.Contact currentContact = Contacts.get(position);

        TextView name = (TextView) view.findViewById(R.id.contactName);
        name.setText(currentContact.getName());
        TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
        phone.setText(currentContact.getPhone());
        TextView email = (TextView) view.findViewById(R.id.emailAddress);
        email.setText(currentContact.getEmail());
        TextView address = (TextView) view.findViewById(R.id.cAddress);
        address.setText(currentContact.getAddress());


        return view;
    }
}

我在此行contactListView.setAdapter(contactAdapter);收到空错误 这是DatabaseHelper

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "contactManager",
        TABLE_CONTACTS = "contacts",
        KEY_ID = "id",
        KEY_NAME = "name",
        KEY_PHONE = "phone",
        KEY_EMAIL = "email",
        KEY_ADDRESS = "address",
        KEY_IMAGEURI = "imageUri";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_IMAGEURI + " TEXT)");
}

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

    onCreate(db);
}

public void createContact(import_fragment.Contact contact) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PHONE, contact.getPhone());
    values.put(KEY_EMAIL, contact.getEmail());
    values.put(KEY_ADDRESS, contact.getAddress());
    values.put(KEY_IMAGEURI, contact.getImageURI().toString());

    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}


public import_fragment.Contact getContact(int id) {
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );

    if (cursor != null)
        cursor.moveToFirst();

    import_fragment.Contact contact = new import_fragment.Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
    db.close();
    cursor.close();
    return contact;
}

public void deleteContact(import_fragment.Contact contact) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[]{String.valueOf(contact.getId())});
    db.close();
}

public int getContactsCount() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public int updateContact(import_fragment.Contact contact) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PHONE, contact.getPhone());
    values.put(KEY_EMAIL, contact.getEmail());
    values.put(KEY_ADDRESS, contact.getAddress());
    values.put(KEY_IMAGEURI, contact.getImageURI().toString());

    int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
    db.close();

    return rowsAffected;
}

public List<import_fragment.Contact> getAllContacts() {
    List<import_fragment.Contact> contacts = new ArrayList<import_fragment.Contact>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

    if (cursor.moveToFirst()) {
        do {
            contacts.add(new import_fragment.Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return contacts;
}

这是logcat

01-27 07:45:45.795 3034-3034/com.al3almya.users.al3almya E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.al3almya.users.al3almya, PID: 3034
                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.al3almya.users.al3almya/com.al3almya.users.al3almya.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                           at com.al3almya.users.al3almya.main_fragment.onCreateView(main_fragment.java:65)
                                                                           at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                           at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                           at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                           at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
                                                                           at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
                                                                           at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
                                                                           at android.app.Activity.performStart(Activity.java:6253)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                           at android.os.Looper.loop(Looper.java:148) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                           at java.lang.reflect.Method.invoke(Native Method) 
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

这里的import_fragment.xml [list view here]不在main_fragment.xml

<ImageView
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:id="@+id/ivContactImage" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Contact Name"
        android:id="@+id/contactName"
        android:textSize="10dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone"
        android:id="@+id/phoneNumber"
        android:layout_gravity="left|center_vertical"
        android:layout_marginTop="5dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email"
        android:id="@+id/emailAddress"
        android:layout_gravity="left|center_vertical"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Address"
        android:id="@+id/cAddress"
        android:layout_gravity="left|center_vertical"/>

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView"
        android:layout_gravity="center"/>

</LinearLayout>

我添加了所有的东西,但我现在想知道如何在列表视图中显示我的数据请给我代码不告诉我setAdapter因为当我设置它我得到错误, 提前谢谢

2 个答案:

答案 0 :(得分:0)

您正在listview中搜索main_fragmentmain_fragment list view中的 ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 不可用,这就是为什么它会给出空指针异常。

答案 1 :(得分:0)

你的main_fragment第65行上有任何对象,其引用为空at com.al3almya.users.al3almya.main_fragment.onCreateView(main_fragment.java:65)