2016-01-22 5 views
1

Я пытаюсь показать Listview, чтобы показать мои данныеПросмотр списка не отображается

Это main_fragment.java

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); 
    final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>(); 
    ListView contactListView; 

    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); 
    contactListView = (ListView) view.findViewById(R.id.listView); 
    dbHandler = new DatabaseHandler(getActivity().getApplicationContext()); 

    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(); 
      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()); 
     } 
    } 
} 

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; 
    } 
} 

Это import_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"> 

<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="91dp"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Contact Name" 
     android:id="@+id/contactName" 
     android:layout_gravity="left|center_vertical"/> 

    <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"/> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="My Contacts" 
     android:id="@+id/textView" 
     android:layout_gravity="center" 
     android:layout_marginTop="10dp"/> 

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

Мои listview в import_fragment.xml, когда я открываю import_fragment.xml в приложении появляется только контактное имя и телефон, а также адрес электронной почты и адрес, который добавлен в import_fragment.xml, а не новые контактные данные, которые в базе данных добавлены пользователем.

+0

Почему высота родительского LinearLayout устанавливается в 91dp? С этим я не думаю, что ListView будет видно со многими TextView над ним. –

+0

Я тоже изменил его на fill_parent и все еще мои объекты, которые в моей базе данных не отображаются @ReyPham –

ответ

0

Изменение и высоты вашего LinearLayout к

android:layout_height="fill_parent" 

Ваш ListView на самом деле «там», это просто, что контейнер (макет) из ListView не является достаточно большим, чтобы соответствовать его.

EDIT:

Вы определяете два разных списка контактов там! Оба класса активности и адаптера относятся к двум различным контактам. Удалите элемент внутри функции onCreateView.

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

Я изменил оба на fill_parent тоже, и все же мои объекты, которые есть в моей базе данных, не отображаются @Jiyeh –

+0

@MaystroJeKa Проверьте обновленный ответ. – Jiyeh

0

Вы должны setAdapter в onCreateView. В настоящее время вы заполняете список в onCreateContextMenu. Кроме того, после установки адаптера, вы должны вызвать notifyDataSetChanged(), а

+0

Я добавил его в 'onCreateView', но у меня возникла ошибка при добавлении NullPointerException, пожалуйста, скажите мне, как добавить его правильно? @Mustansar Saeed –

0

Попробуйте этот путь, я попытался это в моей машине, и показать мне listview правильно, я сделал с weightSum так будет применяться для всех устройств, просто изменить файл XML с менее одного

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

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:weightSum="4"> 

    <ImageView 
     android:id="@+id/ivContactImage" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="1" /> 

    <LinearLayout 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="3" 
     android:orientation="vertical"> 

     <TextView 
      android:id="@+id/contactName" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="left|center_vertical" 
      android:text="Contact Name" 
      android:textAppearance="?android:attr/textAppearanceMedium" /> 

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

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

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

     <TextView 
      android:id="@+id/textView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="left|center_vertical" 
      android:text="My Contacts" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 

    </LinearLayout> 
</LinearLayout> 

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

+0

Ваша проблема решена? @Maystro JeKa –

+0

Нет, ваш ответ мне не помог .. Мне нужно знать, как установить адаптер в onCreateView @Amit Vaghela –

+0

@MaystroJeKa разве ваша проблема не решена? –

Смежные вопросы