2017-04-16 73 views
0

我想從其中包含回收以另一個片段,它是bottombar的一部分片段傳遞值。如何將片段的RecyclerAdapter中的值傳遞給另一個片段?

我一直在使用接口來實現這一嘗試過,但我的應用程序崩潰,並顯示一個NullPointerException

我的第一片段包含與編輯文本顯示當前位置,價格和用作DatePicker圖像按鈕沿複選框。

當用戶選中該複選框,他可以輸入日期到從圖像按鈕EditText領域。 用戶可以在EditText字段中選擇三個日期。

我的問題是如何使這些條目(位置,價格和日期) 傳遞給第三個片段?

我參考了this來實現這個接口。

這裏是我的代碼

Textproperty1.java

import android.content.Intent; 
import android.support.annotation.IdRes; 
import android.support.annotation.Nullable; 
import android.support.v7.app.ActionBar; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.Toolbar; 
import android.widget.Toast; 

import com.example.sumitroy.pitchads.TextProperty1_Schedule_Classes.TextProperty1_Schedule; 
import com.example.sumitroy.pitchads.TimesofIndia.TOITextFragment; 
import com.roughike.bottombar.BottomBar; 
import com.roughike.bottombar.OnMenuTabClickListener; 

import java.util.ArrayList; 

public class TextProperty1 extends AppCompatActivity { 

    BottomBar bottomBar; 
    String test=null; 

    @Override 
    protected void onCreate(final Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_text_property1); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     ActionBar appbar = getSupportActionBar(); 
     appbar.setDisplayHomeAsUpEnabled(true); 
     appbar.setDisplayShowHomeEnabled(true); 
     bottomBar=BottomBar.attach(this,savedInstanceState); 
     bottomBar.noNavBarGoodness(); 
     bottomBar.noTabletGoodness(); 
     bottomBar.noResizeGoodness(); 
     bottomBar.hideShadow(); 
     bottomBar.setItemsFromMenu(R.menu.bottombar_textproperty, new OnMenuTabClickListener() { 
      @Override 
      public void onMenuTabSelected(@IdRes int menuItemId) { 

       if(menuItemId==R.id.textproperty_bottombaritem1) 
       { 
        TextProperty1_Schedule f=new TextProperty1_Schedule(); 
        Intent intent=new Intent(getApplicationContext(),TextProperty1_Schedule.class); 
        intent.putExtra(test,"check"); 
        getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit(); 
       } 
       else if(menuItemId==R.id.textproperty_bottombaritem2) 
       { 
        TextProperty1_EditText f=new TextProperty1_EditText(); 
        getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit(); 
       } 
       else 
       { 
        TextProperty1_ConfirmAd f=new TextProperty1_ConfirmAd(); 
        getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit(); 


       } 

      } 

      @Override 
      public void onMenuTabReSelected(@IdRes int menuItemId) { 

      } 
     }); 

    } 

    @Nullable 
    @Override 
    public Intent getSupportParentActivityIntent() { 
     String from=getIntent().getExtras().getString("from"); 
     Intent newintent=null; 
     if(from.equals("FAV")) 
     { 
      newintent=new Intent(this,TOITextFragment.class); 
     } 
     return newintent; 
    } 

} 

TextProperty1_Schedule.java

import android.content.Context; 
import android.content.pm.PackageManager; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentTransaction; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.example.sumitroy.pitchads.R; 
import com.example.sumitroy.pitchads.TextProperty1; 
import com.example.sumitroy.pitchads.TextProperty1_ConfirmAd; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.Locale; 
import java.util.jar.Manifest; 


/** 
* A simple {@link Fragment} subclass. 
*/ 
public class TextProperty1_Schedule extends Fragment { 
    TextView textView; 
    private static final int MY_PERMISSION_REQUEST_LOCATION=1; 
    private RecyclerView mRecyclerView; 
    private RecyclerView.Adapter mAdapter; 
    private RecyclerView.LayoutManager mLayoutManager; 
    private List<TextProperty1_Schedule_Location>scheduleLocationList; 
    int imageid[]={R.drawable.location_show}; 

    public TextProperty1_Schedule() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View rootview; 
     rootview= inflater.inflate(R.layout.fragment_text_property1__schedule, container, false); 
     textView=(TextView)rootview.findViewById(R.id.yourCity); 
     if(ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED) 
     { 
      if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION)) 
      { 
       ActivityCompat.requestPermissions(getActivity(),new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSION_REQUEST_LOCATION); 
      } 
      else 
      { 
       ActivityCompat.requestPermissions(getActivity(),new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSION_REQUEST_LOCATION); 
      } 
     } 
     else 
     { 
      LocationManager locationManager=(LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE); 
      Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

      try 
      { 
       textView.setText(herelocation1(location.getLatitude(),location.getLongitude())); 

      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
       //Toast.makeText(getContext(),"Not Found!!",Toast.LENGTH_LONG).show(); 
      } 
     } 

     scheduleLocationList=new ArrayList<>(); 

     for(int i=1;i<=15;i++) 
     { 
      if(i==1) 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Bangalore", "1000", " "," "," ", false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
      else if(i==2) 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Jamshedpur", "250", " "," "," ",false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
      else if(i==3) 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Indore", "100", " "," "," ", false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
      else if(i==4) 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Mumbai", "450", " "," "," ", false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
      else if(i==5) 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Goa", "450", " "," "," ", false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
      else 
      { 
       TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Goa", "450", " "," "," ", false,imageid[0]); 
       scheduleLocationList.add(sl); 
      } 
     } 
     mRecyclerView = (RecyclerView)rootview.findViewById(R.id.my_recycler_view); 
     mRecyclerView.setHasFixedSize(true); 
     mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 
     mAdapter = new TextProperty1_CardViewScheduleAdapter(scheduleLocationList,communication); 
     mRecyclerView.setAdapter(mAdapter); 

     return rootview; 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) { 
     switch (requestCode) 
     { 
      case MY_PERMISSION_REQUEST_LOCATION:{ 
       if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) 
       { 
        if(ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED) 
        { 
         LocationManager locationManager=(LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE); 
         Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

         try 
         { 
          textView.setText(herelocation1(location.getLatitude(),location.getLongitude())); 

         } 
         catch (Exception e) 
         { 
          e.printStackTrace(); 
          Toast.makeText(getContext(),"Please Switch On Your Location!!",Toast.LENGTH_LONG).show(); 
         } 
        } 
       } 
       else 
       { 
        Toast.makeText(getContext(),"No Permission granted!",Toast.LENGTH_LONG).show(); 
       } 
      } 

     } 
    } 

    public String herelocation1(double lat,double lon) 
    { 
     String currcity=""; 
     Geocoder geocoder=new Geocoder(getActivity(), Locale.getDefault()); 
     List<Address> addressList; 
     try 
     { 
      addressList=geocoder.getFromLocation(lat,lon,1); 
      if(addressList.size() > 0) 
      { 
       currcity=addressList.get(0).getLocality(); 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return currcity; 
    } 

TextProperty1_CardViewScheduleAdapter.FragmentCommunication communication=new TextProperty1_CardViewScheduleAdapter.FragmentCommunication() { 
    @Override 
    public void respond(ArrayList<String> locattion_confirm, ArrayList<String> price_confirm, ArrayList<String> dates1_confirm, ArrayList<String> dates2_confirm, ArrayList<String> dates3_confirm) { 

     TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd(); 
     Bundle bundle=new Bundle(); 
     bundle.putString("Location", String.valueOf(locattion_confirm)); 
     bundle.putString("Price", String.valueOf(price_confirm)); 
     bundle.putString("Dates1", String.valueOf(dates1_confirm)); 
     bundle.putString("Dates2", String.valueOf(dates2_confirm)); 
     bundle.putString("Dates3", String.valueOf(dates3_confirm)); 
     fragmentB.setArguments(bundle); 
    } 
}; 

} 

TextProperty1_CardViewScheduleAdapter.java

import android.app.DatePickerDialog; 
import android.content.Context; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.CheckBox; 
import android.widget.DatePicker; 
import android.widget.EditText; 
import android.widget.ImageButton; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.example.sumitroy.pitchads.R; 
import com.example.sumitroy.pitchads.TextProperty1_ConfirmAd; 

import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.List; 

/** 
* Created by Sumit Roy on 06-Apr-17. 
*/ 
public class TextProperty1_CardViewScheduleAdapter extends 
     RecyclerView.Adapter<TextProperty1_CardViewScheduleAdapter.ViewHolder> { 
    public ArrayList<String> location=new ArrayList<String>(); 
    public ArrayList<String>price=new ArrayList<String>(); 
    public ArrayList<String>dates1=new ArrayList<String>(); 
    public ArrayList<String>dates2=new ArrayList<String>(); 
    public ArrayList<String>dates3=new ArrayList<String>(); 
    private FragmentCommunication mCommunicator; 

    public int day,month,year; 
    int imagebuttonclick=0; 

    private List<TextProperty1_Schedule_Location> stList; 


    public TextProperty1_CardViewScheduleAdapter(List<TextProperty1_Schedule_Location> schedule_locations,FragmentCommunication communication) { 
     this.stList = schedule_locations; 
     this.mCommunicator=communication; 

    } 

    // Create new views 
    @Override 
    public TextProperty1_CardViewScheduleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, 
                   int viewType) { 
     // create a new view 
     View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
       R.layout.textproperty1_list_schedule_card, null); 

     // create ViewHolder 

     ViewHolder viewHolder = new ViewHolder(itemLayoutView,mCommunicator); 

     return viewHolder; 
    } 

    @Override 
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) { 

     final int pos = position; 

     viewHolder.tvLocate.setText(stList.get(position).getLocation()); 

     viewHolder.tvPrice.setText(stList.get(position).getPrice()); 

     viewHolder.chkSelected.setChecked(stList.get(position).isSelected()); 

     viewHolder.chkSelected.setTag(stList.get(position)); 
     viewHolder.img.setImageResource(stList.get(position).getUrl()); 


     viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() { 
      public void onClick(final View v) { 

       //Click Event for check box 

       CheckBox cb = (CheckBox) v; 
       TextProperty1_Schedule_Location contact = (TextProperty1_Schedule_Location) cb.getTag(); 
       contact.setSelected(cb.isChecked()); 
       stList.get(pos).setSelected(cb.isChecked()); 
       imagebuttonclick=0; 
       /*Toast.makeText(
         v.getContext(), 
         "Clicked on Checkbox: " + cb.getText() + " is " 
           + cb.isChecked(), Toast.LENGTH_LONG).show(); */ 

       viewHolder.img.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
         //Click event for image button 
         imagebuttonclick+=1; 
         if(imagebuttonclick==1) 
         { 
          //Toast.makeText(view.getContext(),"Clicked once",Toast.LENGTH_SHORT).show(); 

          final Calendar calendar=Calendar.getInstance(); 
          day=calendar.get(Calendar.DAY_OF_MONTH); 
          month=calendar.get(Calendar.MONTH); 
          day=day+1; 
          year=calendar.get(Calendar.YEAR); 
          Context context=v.getContext(); 
          DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() { 

           @Override 
           public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { 
            String selected_date=" " + i2+ "/" + i1 + "/" + i; 
            //Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show(); 

            viewHolder.dates.setText(selected_date); 
            String getlocation,getprice,getdate1; 
            getlocation=viewHolder.tvLocate.getText().toString(); 
            getprice=viewHolder.tvPrice.getText().toString(); 
            getdate1=viewHolder.dates.getText().toString(); 
            if(getdate1.length()!=0) 
            { 
             location.add(getlocation); //Pass this value to a different fragment 
             price.add(getprice);//Pass this value to a different fragment 
             dates1.add(getdate1);//Pass this value to a different fragment 

            } 


           } 
          },year,month,day 
          ); 
          //Will set datepicker dialog from current date 
          datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000); 
          datePickerDialog.setTitle("Select Date"); 
          datePickerDialog.show(); 

         } 
         else if(imagebuttonclick==2) 
         { 
          //Toast.makeText(view.getContext(),"More Than once",Toast.LENGTH_SHORT).show(); 
          final Calendar calendar=Calendar.getInstance(); 
          day=calendar.get(Calendar.DAY_OF_MONTH); 
          day=day+2; 
          month=calendar.get(Calendar.MONTH); 
          year=calendar.get(Calendar.YEAR); 
          Context context=v.getContext(); 
          DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() { 

           @Override 
           public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { 
            String selected_date=" " + i2+ "/" + i1 + "/" + i; 
            //Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show(); 
            String getdate2; 

            viewHolder.dates2.setText(selected_date); 
            getdate2=viewHolder.dates2.getText().toString(); 
            if(getdate2.length()!=0) 
            { 
             dates2.add(getdate2); //Pass this value to a different fragment 
            } 


           } 
          },year,month,day 
          ); 
          //Will set datepicker dialog from current date 
          datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000); 
          datePickerDialog.setTitle("Select Date"); 
          calendar.add(Calendar.DAY_OF_MONTH,+1); 
          datePickerDialog.show(); 
         } 
         else if(imagebuttonclick==3) 
         { 
          //Toast.makeText(view.getContext(),"More Than once",Toast.LENGTH_SHORT).show(); 
          final Calendar calendar=Calendar.getInstance(); 
          day=calendar.get(Calendar.DAY_OF_MONTH); 
          day=day+3; 
          month=calendar.get(Calendar.MONTH); 
          year=calendar.get(Calendar.YEAR); 
          Context context=v.getContext(); 
          DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() { 

           @Override 
           public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { 
            String selected_date=" " + i2+ "/" + i1 + "/" + i; 
            //Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show(); 
            String getdate3; 

            viewHolder.dates3.setText(selected_date); 
            getdate3=viewHolder.dates3.getText().toString(); 
            if(getdate3.length()!=0) 
            { 
             dates3.add(getdate3); //Pass this value to a different fragment 
            } 

           } 
          },year,month,day 
          ); 
          //Will set datepicker dialog from current date 
          datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000); 
          datePickerDialog.setTitle("Select Date"); 
          datePickerDialog.show(); 

         } 
         else 
         { 
          Toast.makeText(view.getContext(),"Can Enter Ads only for three days",Toast.LENGTH_SHORT).show(); 
          imagebuttonclick=0; 
         } 


        } 
       }); 
       if(viewHolder.chkSelected.isChecked()==false) 
       { 
        viewHolder.dates.setText(" "); 
        viewHolder.dates2.setText(" "); 
        viewHolder.dates3.setText(" "); 
       } 
       TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd(); 
       Bundle bundle=new Bundle(); 
       bundle.putString("Location", String.valueOf(location)); 
       fragmentB.setArguments(bundle); 

      } 

     }); 
     mCommunicator.respond(location,price,dates1,dates2,dates3); 
     TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd(); 
     Bundle bundle=new Bundle(); 
     bundle.putString("Location", String.valueOf(location)); 
     bundle.putString("Price", String.valueOf(price)); 
     bundle.putString("Dates1", String.valueOf(dates1)); 
     bundle.putString("Dates2", String.valueOf(dates2)); 
     bundle.putString("Dates3", String.valueOf(dates3)); 
     fragmentB.setArguments(bundle); 

    } 

    // Return the size arraylist 
    @Override 
    public int getItemCount() { 
     return stList.size(); 
    } 

    public static class ViewHolder extends RecyclerView.ViewHolder { 

     public TextView tvLocate; 
     public TextView tvPrice; 
     public EditText dates; 
     public EditText dates2; 
     public EditText dates3; 
     public ImageButton img; 
     public CheckBox chkSelected; 
     FragmentCommunication mcommunication; 


     public TextProperty1_Schedule_Location singlestudent; 

     public ViewHolder(View itemLayoutView,FragmentCommunication communicator) { 
      super(itemLayoutView); 

      chkSelected = (CheckBox) itemLayoutView 
        .findViewById(R.id.checkbox1); 
      tvLocate = (TextView) itemLayoutView.findViewById(R.id.tvLocation); 
      tvPrice = (TextView) itemLayoutView.findViewById(R.id.tvPrice); 
      img=(ImageButton)itemLayoutView.findViewById(R.id.itemImage); 
      dates = (EditText) itemLayoutView.findViewById(R.id.tvDates); 
      dates2=(EditText)itemLayoutView.findViewById(R.id.tvDates2); 
      dates3=(EditText)itemLayoutView.findViewById(R.id.tvDates3); 
      mcommunication=communicator; 

     } 

    } 

    // method to access in activity after updating selection 
    public List<TextProperty1_Schedule_Location> getStudentist() { 
     return stList; 
    } 

    public interface FragmentCommunication { 
     void respond(ArrayList<String> locattion_confirm,ArrayList<String> price_confirm,ArrayList<String> dates1_confirm,ArrayList<String> dates2_confirm,ArrayList<String> dates3_confirm); 
    } 
} 

TextProperty1_ConfirmAd

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

import java.util.ArrayList; 


/** 
* A simple {@link Fragment} subclass. 
*/ 
public class TextProperty1_ConfirmAd extends Fragment { 
    TextView textView1,textView2,textView3,textView4,textView5; 
    ArrayList<String>get_location; 
    ArrayList<String>get_price; 
    ArrayList<String>get_dates1; 
    ArrayList<String>get_dates2; 
    ArrayList<String>get_dates3; 


    public TextProperty1_ConfirmAd() { 
     // Required empty public constructor 
    } 


    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     get_location=getArguments().getStringArrayList("Location"); 
     get_price=getArguments().getStringArrayList("Price"); 
     get_dates1=getArguments().getStringArrayList("Dates1"); 
     get_dates2=getArguments().getStringArrayList("Dates2"); 
     get_dates3=getArguments().getStringArrayList("Dates3"); 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view; 
     view=inflater.inflate(R.layout.fragment_text_property1__confirm_ad, container, false); 
     textView1=(TextView)view.findViewById(R.id.textView1); 
     textView2=(TextView)view.findViewById(R.id.textView2); 
     textView3=(TextView)view.findViewById(R.id.textView3); 
     textView4=(TextView)view.findViewById(R.id.textView4); 
     textView5=(TextView)view.findViewById(R.id.textView5); 

     textView1.setText((CharSequence) get_location); 
     textView2.setText((CharSequence) get_price); 
     textView3.setText((CharSequence) get_dates1); 
     textView4.setText((CharSequence) get_dates2); 
     textView5.setText((CharSequence) get_dates3); 
     return view; 

    } 

} 
+0

嗨,歡迎來到所以。您的問題包含很多可能不需要的代碼來說明問題。請考慮儘量減少[MCVE]的代碼量(http://stackoverflow.com/help/mcve)。 –

回答

0

對於來自你應該使用捆綁片段傳送數據。在你的代碼中,我看到你在捆綁String(方法public void respond),但在方法onCrerate中調用方法getStringArrayList()。你調用不同的方法,你會得到NullPointerException。

+0

我按照您的建議使用了Bundle,但它在編輯文本字段中不顯示任何值。這裏是我使用的代碼。Bundle bundle = this.getArguments();如果(bundle!= null) get_location = bundle.getStringArrayList(「Location」); get_price = bundle.getStringArrayList(「Price」); get_dates1 = bundle.getStringArrayList(「Dates1」); get_dates2 = bundle.getStringArrayList(「Dates2」); get_dates3 = bundle.getStringArrayList(「Dates3」); } –

+0

束的值來爲空 –

+0

嘗試更換getStringArrayList到的getString或在方法響應替換bundle.putString()來bundle.putputStringArrayList() – Oleg

0

您可以使用greenrobot/EventBus。在所有需要事件的片段中註冊EventBus。要獲得事件@訂閱一個具有所需模型的方法。和runOnUIThread()內執行你的行動。我認爲你的目標將會實現。並且記住一件事,當片段/活動被破壞時,不要忘記取消註冊EventBus。

按照以下步驟 -

創建一個巴士模型

public class BusModelAdapterItems { 
    private ArrayList<String> stringArrayList; 

    public BusModelAdapterItems(ArrayList<String> stringArrayList) { 
     this.stringArrayList = stringArrayList; 
    } 

    public ArrayList<String> getStringArrayList() { 
     return stringArrayList; 
    } 
} 

在你的片段放在codes-

@Override 
public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    if (!EventBus.getDefault().isRegistered(this)) { 
     EventBus.getDefault().register(this); 
    } 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    if (EventBus.getDefault().isRegistered(this)) { 
     EventBus.getDefault().unregister(this); 
    } 
} 

@org.greenrobot.eventbus.Subscribe 
public void onAdapterUpdate(final BusModelAdapterItems items) { 
    getActivity().runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      // do what you want 
      // items.getStringArrayList(); 
     } 
    }); 
} 

從您的適配器,請把這個代碼 -

// the array list that adapter holds and you want to pass to the fragments 
EventBus.getDefault().post(new BusModelAdapterItems(arrayList)); 
+0

我實現了greenbot/EventBus,但無法將數據傳遞給其他片段。在片段A的回收器適配器中,我使用了EventBus.getDefault .postSticky(Arraylist )方法,並在片段C中使用了訂閱者方法,並嘗試使用我的事件類的對象接收值。我在某個地方犯了錯嗎? –

+0

@SumitRoy請通過模型而不是ArrayList 。將ArrayList 設置爲模型的字段。它應該工作。 – MMBarno

+0

你可以給我一個提示如何通過一個模型?不介意我是android開發新手。 –

相關問題