Я создаю CategoryFragment, который будет отображать все данные, добавленные из моей деятельности. Код работает нормально, данные добавляются в базу данных, я проверил данные в проводнике файлов устройств, и данные, которые я добавил, есть, но они не отображаются в моем списке. Вот коды:
РубрикиFragment.java
package com.example.devcash.Fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import com.example.devcash.ADD_UI.AddCategoryActivity;
import com.example.devcash.CustomAdapters.CategoryAdapter;
import com.example.devcash.Database.DatabaseHelper;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment implements SearchView.OnQueryTextListener {
DatabaseHelper db;
ListView lv;
CategoryAdapter categoryAdapter;
public CategoriesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addcategory = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addcategory);
}
});
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//handles listview
ListView lvcategories = (ListView) view.findViewById(R.id.categorylist_listview);
db = new DatabaseHelper(getActivity());
ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
lvcategories.setAdapter(categoryAdapter);
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
categoryListArrayList = db.getAllCategory();
getActivity().setTitle("Categories");
}
//handles the search menu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.searchmenu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("Search..");
super.onCreateOptionsMenu(menu, inflater);
}
}
фрагменткатегории.xml
<?xml version = "1.0" encoding = "utf-8"?>
<FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".Fragments.CategoriesFragment"
android:padding = "@dimen/text_padding">
<ListView
android:id = "@+id/categorylist_listview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:dividerHeight = "1dp"/>
<android.support.design.widget.FloatingActionButton
android:id = "@+id/addcategories_fab"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "bottom|end"
android:layout_margin = "@dimen/fab_margin"
android:src = "@drawable/ic_add"
android:tint = "@color/whiteBG"
android:backgroundTint = "@color/colorPrimary"/>
</FrameLayout>
КатегорияAdapter.java
package com.example.devcash.CustomAdapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;
import java.util.ArrayList;
public class CategoryAdapter extends BaseAdapter {
private Context context;
private ArrayList<CategoryList> categoryListArrayList;
public CategoryAdapter(Context context, ArrayList<CategoryList> categoryListArrayList) {
this.context = context;
this.categoryListArrayList = categoryListArrayList;
}
@Override
public int getCount() {
return categoryListArrayList.size();
}
@Override
public Object getItem(int position) {
return categoryListArrayList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, null, true);
holder.textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
//display the data into the CategoryFragment
holder.textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());
return convertView;
}
private class ViewHolder{
protected TextView textCategoryName;
}
}
проблема в том, что вы устанавливаете адаптер с пустым списком, и перед его созданием в первый раз проверьте, не пуст ли ваш список, а затем позвоните notifyDataSetChanged()
ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);
categoryListArrayList = db.getAllCategory();
categoryAdapter.notifyDataSetChanged();
редактировать
Во-первых, вы должны передать контекст, а не действие в конструкторе вашего адаптера.
categoryAdapter = new CategoryAdapter(getActivity().getApplicationContext(), categoryListArrayList);
затем в вашем адаптере попробуйте изменить getview()
на это
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, parent, true);
TextView textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);
textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());
return convertView;
}
Ваш список хорошо заполнен данными?
@ismael alaoui, данные не отображаются в моем списке. Я снова проверил базу данных и обнаружил, что добавленные данные есть.
Извините, я имел в виду, что ваш список категорий хорошо заполнен данными?
Да, он хорошо заполнен данными
Отлично, пожалуйста, добавьте свой код адаптера, я должен проверить его.
просто попробуйте передать контекст, getActivity().getApplicationContext()
пожалуйста, добавьте точку останова в notifydatastchanged и сообщите мне, достигает ли ваш код этой точки?
Прежде всего, вам нужно изменить этот код
ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
lvcategories.setAdapter(categoryAdapter);
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
categoryListArrayList = db.getAllCategory();
К
ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryListArrayList = db.getAllCategory();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);
И в коде адаптера для раздувания представления вам нужно передать родительское значение, а не нулевое.
Использовать этот
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, parent, false); // You just pass null instead of parent
вместо
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, null, true);
Надеюсь, это поможет.
Исправлена проблема. Спасибо!
Добро пожаловать. Рад помочь вам.
называется
notifyDataSetChanged()
, но, тем не менее, его данные не отображаются в списке