我的自定义类有一些麻烦来获取数据。我已经创建了一个用于从我的Web服务获取数据的自定义类,当我尝试使用我的单例类时出现问题,如果我使用DataReader.getInstance(getContext(), this)
我的列表视图仅在应用程序启动时第一次填充。但是如果我在任何时候使用我的DataReader的新实例都可以正常工作..
这是我的DataReader类:
public class DataReader {
private static DataReader singleton;
private Context context;
private Data_Listener data_listener;
public DataReader(Context context, Data_Listener data_listener) {
this.context = context;
this.data_listener = data_listener;
}
public static synchronized DataReader getInstance(Context context, Data_Listener data_listener) {
if (singleton == null) {
singleton = new DataReader(context, data_listener);
}
return singleton;
}
public void Categorias_fill(){
final ArrayList<Object> objects = new ArrayList<>();
API.getInstance(context).unAuthenticateArrayRequest(Request.Method.GET, context.getString(R.string.endpoint_categorias), null, new API_Listener() {
@Override
public void OnSuccess(JSONObject response) {
}
@Override
public void OnSuccess(JSONArray response) throws JSONException {
Gson gson = new Gson();
Categoria categoria;
for(int i = 0;i < response.length(); i++) {
categoria = gson.fromJson(response.getJSONObject(i).toString(), Categoria.class);
objects.add(categoria);
}
data_listener.onBindData(objects);
}
@Override
public void OnError(String error) {
data_listener.onBindData(objects);
}
});
}
以及我如何使用DataReader:
public class CategoriasFragment extends Fragment implements Data_Listener{
private Categorias_Adapter adapter;
private ArrayList<Categoria> list = new ArrayList<>();
private ExpandableListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_categorias, container, false);
listView = (ExpandableListView) view.findViewById(R.id.exp_list);
listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {
if(list.size()>0){
if(list.get(groupPosition).getSubCategorias().size()>0){
SubCategoria subCategoria = list.get(groupPosition).getSubCategorias().get(childPosition);
Log.d(General.appname, subCategoria.getNombre());
}
}
return true;
}
});
//This work only the first time
//DataReader.getInstance(getContext(), this).Categorias_fill();
//This work everytime
DataReader dataReader = new DataReader(getContext(), this);
dataReader.Categorias_fill();
return view;
}
@Override
public void onBindData(ArrayList<Object> objects) {
list = (ArrayList) objects;
adapter = new Categorias_Adapter(getContext(), list);
listView.setAdapter(adapter);
}
答案 0 :(得分:1)
在后续调用getInstance()
时,您的上下文和Data_Listener未设置。他们仍会指出他们在第一次通话中指出的任何内容。
我建议尝试这样做:在getInstance()方法中显式设置DataReader.context和DataReader.data_listener。