我正在尝试将包含回收站视图的片段中的值传递给另一个片段,这些片段都是底栏的一部分。
我尝试使用界面实现此功能,但我的应用崩溃并显示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 :(得分:0)
对于来自片段的传输数据,您应该使用Bundle。在你的代码中,我看到你放入bundle String(方法public void respond),但是在onCrerate方法中你调用方法getStringArrayList()。您调用不同的方法,并获得NullPointerException。
答案 1 :(得分:0)
您可以使用greenrobot/EventBus。在需要事件的所有片段中注册EventBus。要获取事件 @Subscribe 具有所需模型的方法。并在 runOnUIThread()中执行操作。我认为你的目标将会实现。记住一件事,当片段/活动被破坏时,不要忘记取消注册EventBus。
请按照以下步骤进行操作 -
创建总线模型
public class BusModelAdapterItems {
private ArrayList<String> stringArrayList;
public BusModelAdapterItems(ArrayList<String> stringArrayList) {
this.stringArrayList = stringArrayList;
}
public ArrayList<String> getStringArrayList() {
return stringArrayList;
}
}
在你的片段中输入代码 -
@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));