我首先在片段内显示数据,然后在Create View的函数中使用了一些函数,一切都变得很完美,并成功获取并显示了数据,但是当我从另一个函数中调用adpter尝试重新执行一次操作时,显示和更新数据时发生错误, 具体来说,当我按下对话框中的按钮时会出现问题, 请帮助
//CustomerAdapter class
public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public final int TYPE_MOVIE = 0;
public final int TYPE_LOAD = 1;
static Context context;
List<Customer>customers;
OnLoadMoreListener loadMoreListener;
boolean isLoading = false, isMoreDataAvailable = true;
public CustomerAdapter(Context context, List<Customer> customers) {
this.context = context;
this.customers = customers;
}
public void refreshEvents(List<Customer> data) {
clear();
addAll(data);
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
if(viewType==TYPE_MOVIE){
return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
}else{
return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
isLoading = true;
loadMoreListener.onLoadMore();
}
if(getItemViewType(position)==TYPE_MOVIE){
((CustomerHolder)holder).bindData(customers.get(position));
if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// function call a volly function .. //..
// if(customers.get(position).user_id==2)((CustomerHolder)holder).imgLock.setVisibility(View.VISIBLE);
((CustomerHolder)holder).buttonViewOption.getRootView().toString();
// Toast.makeText(context,"Index Is "+customers.get(position).status+"usr_id"+customers.get(position).user_id, Toast.LENGTH_SHORT).show();
//Page_6Fragment.newInstance().sendNotfic(context ,customers.get(position).user_id);
// Call a fucntion to
Page_6Fragment.newInstance().showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
}
});
}
}
@Override
public int getItemViewType(int position) {
if(customers.get(position).type.equals("movie")){
return TYPE_MOVIE;
}else{
return TYPE_LOAD;
}
}
@Override
public int getItemCount(){
return customers.size();
}
/* VIEW HOLDERS */
static class CustomerHolder extends RecyclerView.ViewHolder{
TextView tvTitle;
TextView tvRating;
ImageView imgLock;
// int usrid;
Button buttonViewOption;
public CustomerHolder(View itemView){
super(itemView);
tvTitle=(TextView)itemView.findViewById(R.id.title);
tvRating=(TextView)itemView.findViewById(R.id.rating);
imgLock=(ImageView)itemView.findViewById(R.id.img_lock);
buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
}
void bindData(Customer cust){
tvTitle.setText(cust.name);
tvRating.setText(cust.title);
// if(cust.user_id==2)imgLock.setVisibility(View.GONE);
if(cust.status!=0)buttonViewOption.setBackground(context.getResources().getDrawable(R.drawable.lock));
// imgLock.setVisibility(View.VISIBLE);
}
}
static class LoadHolder extends RecyclerView.ViewHolder{
public LoadHolder(View itemView){
super(itemView);
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
/* notifyDataSetChanged is final method so we can't override it
call adapter.notifyDataChanged(); after update the list
*/
public void notifyDataChanged(){
notifyDataSetChanged();
isLoading = false;
}
public interface OnLoadMoreListener{
void onLoadMore();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
}
// Fragment class :
public class Page_6Fragment extends android.support.v4.app.Fragment implements AdapterView.OnItemSelectedListener {
TextView t1,t2,t3,t4;
Spinner spin,spin2,spin3,spin4;
Dialog dialog;
RecyclerView recyclerView;
List<Customer>customers;
CustomerAdapter adapter;
View rootView;
String TAG = "MainActivity - ";
Context context;
API api;
Activity a;
Boolean acceptOrNo = true;
Context c =null;
public static Page_6Fragment newInstance(){
Page_6Fragment fragment = new Page_6Fragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_customer, container, false);
//View rootView = inflater.inflate(R.xml.pref, container, false);
//Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
// startActivity(intent);
this.context = getActivity();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
customers = new ArrayList<>();
adapter = new CustomerAdapter(context,customers);
adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
@Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
@Override
public void run() {
int index = customers.size();
loadMore(index);
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(adapter);
api = ServiceGenerator.createService(API.class);
load(0);
return rootView;
}
// recyclerView.addItemDecoration(new VerticalLineDecorator(2));
private void load(int index){
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
@Override
public void onResponse(Call<List<Customer>> call, final Response<List<Customer>> response){
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
//Log.i("TRUE_TRUE_","Yes "+response.body().get(2).name);
if(response.isSuccessful()){
//Log.i("TRUE_TRUE3","Yes"+response.body().toString());
//movies.addAll(response.body());
//adapter.notifyDataChanged();
getActivity().runOnUiThread(new Runnable(){
public void run(){
// No.1 ..............
// ShowDataScreen();
// Toast.makeText( MainActivity.this, "ShowDataScreen",Toast.LENGTH_SHORT).show();
customers.addAll(response.body());
adapter.notifyDataChanged();
}});// end of No.1 UI new thread
getActivity().runOnUiThread(new Runnable(){
public void run() {//No.2
// Toast.makeText( MainActivity.this, "This is correct way",Toast.LENGTH_SHORT).show();
}});// end of No.2 UI new thread
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
}else{
Log.e(TAG," Response Error "+String.valueOf(response.code()));
}
}
@Override
public void onFailure(Call<List<Customer>> call, Throwable t) {
Log.e(TAG," Response Error "+t.getMessage());
}
});
}
public void showDialog(final Context context , final int getToken , final int id){
dialog = new Dialog(context);
dialog.setCancelable(true);
// dialog.setTitle("استقبال الطلب");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.layout);
dialog.show();
String[] bankNames = {
"O","B","H","N","j"
};
t1= (TextView)dialog.findViewById(R.id.tv_h);
t2= (TextView)dialog.findViewById(R.id.tv_m);
t3= (TextView)dialog.findViewById(R.id.tv_title);
t4= (TextView)dialog.findViewById(R.id.tv_pam);
spin =(Spinner)dialog.findViewById(R.id.spinner_minutes);
spin2 =(Spinner)dialog.findViewById(R.id.spinner_minutes2);
spin3 =(Spinner)dialog.findViewById(R.id.spinner_minutes3);
spin4 =(Spinner)dialog.findViewById(R.id.tex);
spin.setOnItemSelectedListener(this);
spin2.setOnItemSelectedListener(this);
spin3.setOnItemSelectedListener(this);
spin4.setOnItemSelectedListener(this);
RadioButton radioButton2 = (RadioButton)dialog.findViewById(R.id.second2);
RadioButton radioButton = (RadioButton)dialog.findViewById(R.id.second);
RadioGroup radioGroup = (RadioGroup)dialog.findViewById(R.id.radioSex);
ArrayAdapter<String> a = new ArrayAdapter<String>(context,R.layout.spinner_item,bankNames);
//ArrayAdapter b = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames2);
//a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//spin.setAdapter(a);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)dialog.findViewById(checkedId);
if (checkedId == R.id.second2) {
RadioYes();
acceptOrNo = false;
} else if (checkedId == R.id.second) {
acceptOrNo = true;
RadioNo();
}
}
});
Button btnOk = (Button)dialog.findViewById(R.id.button_cancel);
btnOk.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//TODO Auto-generated method stub
// Log.i("trace_u",""+acceptOrNo);
if(acceptOrNo)sendNotfic(context , id , getToken ,"1" , spin4.getSelectedItem().toString() , "الساعه"+spin.getSelectedItem().toString()+":"+spin2.getSelectedItem().toString()+" "+spin3.getSelectedItem().toString());
else
sendNotfic(context , id , getToken ,"2","--" ,"--");
dialog.dismiss();
/// Update Rview
// if(adapter != null) {
adapter.refreshEvents(customers);
//}
}
});
Button btnNo = (Button)dialog.findViewById(R.id.button_set);
btnNo.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
/*
adapter = new CustomerAdapter(context , customers);
Log.i("adapter_",""+adapter);
if(adapter != null) {
Log.i("adpter_33","yesysy");
adapter.refreshEvents();
}
*/
}
});
}
// Loge cat :
Process: com.example.android.wacher, PID: 2519
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.wacher.adapters.CustomerAdapter.refreshEvents(java.util.List)' on a null object reference
at com.example.android.wacher.fragments.Page_6Fragment$8.onClick(Page_6Fragment.java:312)
at android.view.View.performClick(View.java:5609)
at android.view.View$PerformClick.run(View.java:22259)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
答案 0 :(得分:1)
在您的onBindViewHolder
中,您有这行
Page_6Fragment.newInstance().showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
在此行中,您创建Page_6Fragment
的新实例,但尚未初始化适配器,尝试显示对话框,并在按钮侦听器中刷新空适配器
解决方案1: 将回调函数传递给适配器,该函数在片段中实现
解决方案2: 您可以将片段作为参数传递给适配器,然后直接调用该方法,而不用创建片段的新实例
将构造函数更改为
public CustomerAdapter(Page_6Fragment page_6Fragment, List<Customer> customers) {
// You can get context from page_6Fragment.getContext()
// And No need to make the context or the fragment static
}
在onBindViewHolder
中
以这种方式调用方法
page_6Fragment.showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
在初始化适配器时,在片段中
adapter = new CustomerAdapter(Page_6Fragment.this,customers);