Get correct date string from Android PagerDatePicker Library - android

I'm using PagerDatePicker library in Android to pick a date and do some work on corresponding date's fragment. But the problem I'm getting is that when I click on a date, I get correct date on corresponding date's textview but not on Toast or Logcat.
When I swipe on the screen (since, it is a viewpager, I can just swipe to move to the next date as shown here),or click on any date, I get correct date on the textView but on Logcat or Toast, it shows the date of a day after or a day before the selected date.
How is it possible that it is showing correct text on textView and incorrect string on Toast/Logcat.
There are 3 Java files - MainActivity.java -
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_main_container, DatePickerDefaultFragment.newInstance())
.commit();
}
}
DatePickerDefaultFragment.java -
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import pl.rspective.pagerdatepicker.PagerDatePickerDateFormat;
import pl.rspective.pagerdatepicker.adapter.DatePagerFragmentAdapter;
import pl.rspective.pagerdatepicker.adapter.DefaultDateAdapter;
import pl.rspective.pagerdatepicker.model.DateItem;
import pl.rspective.pagerdatepicker.view.DateRecyclerView;
import pl.rspective.pagerdatepicker.view.RecyclerViewInsetDecoration;
public class DatePickerDefaultFragment extends Fragment {
private DateRecyclerView dateList;
private ViewPager pager;
LocalDate localDate;
DateTime dateTime;
public static DatePickerDefaultFragment newInstance() {
return new DatePickerDefaultFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_picker_default, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pager = (ViewPager) view.findViewById(R.id.pager);
dateList = (DateRecyclerView) view.findViewById(R.id.date_list);
// [Setting today's date in the DatePicker.]
localDate = new LocalDate();
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
Log.i(getClass().getName(), localDate.toString(fmt));
String DATE_START = localDate.toString(fmt);
String DATE_END = localDate.plusYears(5).toString(fmt);
Log.i(getClass().getName(), DATE_END);
// [END]
dateList.addItemDecoration(new RecyclerViewInsetDecoration(getActivity(), R.dimen.date_card_insets));
Date start = null;
Date end = null;
Date defaultDate = null;
try {
start = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_START);
end = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_END);
defaultDate = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_START );
} catch (ParseException e) {
e.printStackTrace();
}
dateList.setAdapter(new DefaultDateAdapter(start, end, defaultDate));
DatePagerFragmentAdapter fragmentAdapter = new DatePagerFragmentAdapter(getFragmentManager(), dateList.getDateAdapter()) {
#Override
protected Fragment getFragment(int position, long date) {
return SimplePageFragment.newInstance(position, date);
}
};
pager.setAdapter(fragmentAdapter);
dateList.setPager(pager);
dateList.setDatePickerListener(new DateRecyclerView.DatePickerListener() {
#Override
public void onDatePickerItemClick(DateItem dateItem, int position) {
// Toast.makeText(getActivity(), "Clicked: " + position, Toast.LENGTH_SHORT).show();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Toast.makeText(getActivity(), "Date - " + simpleDateFormat.format(dateItem.getDate()), Toast.LENGTH_SHORT).show();
}
#Override
public void onDatePickerPageSelected(int position) {
}
#Override
public void onDatePickerPageStateChanged(int state) {
}
#Override
public void onDatePickerPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
});
}
}
and SimplePageFragment.java -
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
public class SimplePageFragment extends Fragment {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
private static final String DATE_PICKER_DATE_KEY = "date_picker_date_key";
private static final String DATE_PICKER_POSITION_KEY = "date_picker_position_key";
private final String TAG = getClass().getSimpleName();
private TextView tvDate;
private TextView tvPosition;
private int position;
private long date;
private DateTime dateTime;
public static SimplePageFragment newInstance(int position, long date) {
Bundle bundle = new Bundle();
bundle.putInt(DATE_PICKER_POSITION_KEY, position);
bundle.putLong(DATE_PICKER_DATE_KEY, date);
SimplePageFragment simplePageFragment = new SimplePageFragment();
simplePageFragment.setArguments(bundle);
return simplePageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(DATE_PICKER_POSITION_KEY, -1);
date = getArguments().getLong(DATE_PICKER_DATE_KEY, -1);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page_simple, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvDate = (TextView) view.findViewById(R.id.tv_date_label);
tvPosition = (TextView) view.findViewById(R.id.tv_position_label);
dateTime = new DateTime(date);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
Log.i(TAG, dateTime.toString(formatter));
// tvDate.setText("fun");
String ss = dateTime.toString(formatter);
tvDate.setText(ss);
// Log.e("DATE", "" + dateTime.toString(formatter));
Log.e("DATE2", ss);
// Toast.makeText(getActivity(), SIMPLE_DATE_FORMAT.format(date), Toast.LENGTH_SHORT).show();
// tvPosition.setText(String.valueOf(position));
}
}
and there's this fragment_page_simple.xml layout used in SimplePageFragment -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff343434"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_date_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="20sp"
android:textColor="#0f0"/>
<TextView
android:id="#+id/tv_position_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:textSize="16sp"
android:textColor="#ffff3f49"/>
</LinearLayout>

This is just a quick shoot but did you try to use standard java Date classes. The library is based on them, you are using JodaTime library. This shouldn't do any difference but who knows. It's really weird that you have correct value in textView and wrong in logcat.
I checked the demo app, and I am getting correct values in logcat/toast - I used standard Java date class.

final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
dateList = (DateRecyclerView) view.findViewById(R.id.date_list);
dateList.setDatePickerListener(new DateRecyclerView.DatePickerListener() {
#Override
public void onDatePickerItemClick(DateItem dateItem, int position) {
Toast.makeText(context, "date = " + SIMPLE_DATE_FORMAT.format(dateItem.getDate()), Toast.LENGTH_LONG).show();
someTextView.setText(SIMPLE_DATE_FORMAT.format(dateItem.getDate()));
}
#Override
public void onDatePickerPageSelected(int position) {
}
#Override
public void onDatePickerPageStateChanged(int state) {
}
#Override
public void onDatePickerPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
});

Related

How to pass values from a RecyclerAdapter of an fragment to another Fragment?

I am trying to pass values from a fragment which contains a recycler view to another fragment which are all part of the bottombar.
I have tried using interface to achieve this, but my app crashes and shows a NullPointerException.
My first fragment contains a checkbox along with a Edit Text showing current Location, price and an image button which serves as a DatePicker.
When the user checks the checkbox he can enter the date into the EditText field from the image button.
The user can pick three dates into the EditText Fields.
My question is how to make these entries (location,price and date)
pass to the third fragment?
I have taken reference from this to implement the interface.
Here is my code
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;
}
}
For transfer data from fragments you should using Bundle. In your code I see that you put in bundle String (method public void respond), but in method onCrerate you call method getStringArrayList(). You call different methods and you get NullPointerException.
You can use greenrobot/EventBus. Register EventBus in all those fragment where you need an event. To get event #Subscribe a method with a required model. And perform your action within runOnUIThread(). I think your objective will be achieved. And remember one thing, don't forget to unregister EventBus when Fragment/Activity is destroyed.
Follow these steps-
Create a Bus Model
public class BusModelAdapterItems {
private ArrayList<String> stringArrayList;
public BusModelAdapterItems(ArrayList<String> stringArrayList) {
this.stringArrayList = stringArrayList;
}
public ArrayList<String> getStringArrayList() {
return stringArrayList;
}
}
In your fragment put the 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();
}
});
}
From your Adapter please put this code-
// the array list that adapter holds and you want to pass to the fragments
EventBus.getDefault().post(new BusModelAdapterItems(arrayList));

TextToSpeech not working on fragment

I am quite new to Android programming! I have managed to have TTS work but not for fragments. I am trying to swipe some images, and speak something each time I do that. I am not getting any error, however, the text is not spoken. Here's the code:
package com.example.nightrain.sliderTTS1;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.Locale;
public class Wild extends FragmentActivity{
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
public static final String[] IMAGE_NAME = {
"1", "2", "3"};
static final int NUM_ITEMS = IMAGE_NAME.length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return fragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment implements TextToSpeech.OnInitListener {
private static TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.nightrain.sliderTTS1");
imageView.setImageResource(imgResId);
tts = new TextToSpeech( getActivity(), SwipeFragment.this );
speak("help");
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
public void onInit(int status) {
Log.d("Speech", "OnInit - Status ["+status+"]");
if (status == TextToSpeech.SUCCESS) {
Log.d("Speech", "Success!");
tts.setLanguage(Locale.US);
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void speak( String text){
tts.speak( text, TextToSpeech.QUEUE_FLUSH, null, "1" );
}
}
}
Figured it out. I was trying to use speak() before onInit(). It is interesting that I could use speak outside onInit() with no issues in activity, however, for fragment I needed to mode the speak() method and all necessary code inside onInit(). Since it is system called, I could found no way to force it to work outside it.

how to replace fragments tabs inside mainfragment by using button click

hey guys i'm sufferening to problem how to call tab fragments inside fragment.i am always click on button show unfortunately app closed and in logcat show nullpointer exception.i implemented but gettting errror null object reference
Lead_Fragment Main fragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.admin.bdayevent.R;
public class Lead_Fragment extends Fragment implements TabLayout.OnTabSelectedListener,Frgmentchangelistener {
private TabLayout tabLayout;
private ViewPager viewPager;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_lead_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.leadtabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Step1"));
tabLayout.addTab(tabLayout.newTab().setText("Step2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager)view.findViewById(R.id.leadmain_container);
//Creating our pager adapter
Lead_Pager adapter = new Lead_Pager(getFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(this);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
}
});
Lead_step1 fragment1 = new Lead_step1();
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.leadmain_container, fragment1);
// fragmentTransaction.hide(Step1.this);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return view;
}
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
// Toast.makeText(getApplicationContext(),"tab selected "+tab.getPosition(),Toast.LENGTH_SHORT).show();
}
// public void replaceFragment(Fragment fragment, boolean addToBackStack) {
// FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// if (addToBackStack)
// {
// transaction.addToBackStack(null);
// }
// transaction.replace(R.id.fragment_container, fragment);
// transaction.commit();
// getChildFragmentManager().executePendingTransactions();
// }
public void onTabUnselected(TabLayout.Tab tab)
{
// Toast.makeText(getApplicationContext(),"tab unselected",Toast.LENGTH_SHORT).show();
}
public void onTabReselected(TabLayout.Tab tab)
{
}
void switchFragment1(int target)
{
viewPager.setCurrentItem(target);
}
#Override
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.leadmain_container, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Lead_tab1 this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer) this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer)
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.admin.bdayevent.R;
import com.example.admin.bdayevent.Registration;
/**
* Created by admin on 4/28/2016.
*/
public class Lead_step1 extends Fragment implements View.OnClickListener{
EditText customername,customermobile,referncename;
Button nextbtn;
String MobilePattern = "[0-9]{10}";
SharedPreferences lead_pref = null;
Lead_Fragment lead_fragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view= inflater.inflate(R.layout.lead_step1, container, false);
customername = (EditText) view.findViewById(R.id.lead_customername);
customermobile = (EditText) view.findViewById(R.id.lead_mobileno);
referncename = (EditText) view.findViewById(R.id.lead_referencename);
nextbtn=(Button)view.findViewById(R.id.leadnext);
nextbtn.setOnClickListener(this);
return view;
}
public void onClick(View v)
{
if (customername.getText().toString().trim().equals("")) {
customername.setError("please enter name");
}
else if (customermobile.getText().toString().trim().equals("")) {
customermobile.setError("please enter 10 digit mobileno");
}
else if (referncename.getText().toString().trim().equals("")) {
referncename.setError("please enter refernce name");
}
else if(customermobile.getText().toString().matches(MobilePattern) == false)
{
customermobile.setError("plz enter 10 digit mobile number");
}
else
{
((Lead_Fragment) getParentFragment()).switchFragment1(2);
String Lead_name=customername.getText().toString().trim();
String Lead_Mobile=customermobile.getText().toString().trim();
String Lead_Reference=referncename.getText().toString();
System.out.println("value of leads"+Lead_name+":"+Lead_Mobile+":"+Lead_Reference);
lead_pref = getActivity().getSharedPreferences("lead_pref",getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = lead_pref.edit();
editor.putString("key_Lead_name", Lead_name);
editor.putString("key_Lead_Mobile", Lead_Mobile);
editor.putString("key_Lead_Reference", Lead_Reference);
editor.commit();
}
}
}
Lead_tab2, this is the second fragment which contain the form like registration page similar to first fragement which in define 3 editetext.
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import com.example.admin.bdayevent.Database;
import com.example.admin.bdayevent.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Lead_step2 extends Fragment implements View.OnClickListener {
EditText eventname, eventlocation, eventdate, eventtime;
Button submit_btn;
private int mYear, mMonth, mDay, mHour, mMinute;
DatePickerDialog datePickerDialog;
private static final String TIME24HOURS_PATTERN =
" (([0-1]?[0-9])|(2[0-3])):[0-5][0-9] ";
private Pattern pattern;
private Matcher matcher;
SharedPreferences Lead2;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.lead_step2, container, false);
eventname = (EditText) view.findViewById(R.id.lead_eventname);
eventlocation = (EditText) view.findViewById(R.id.lead_location);
eventdate = (EditText) view.findViewById(R.id.lead_date);
eventtime = (EditText) view.findViewById(R.id.lead_time);
submit_btn = (Button) view.findViewById(R.id.lead_submitbtn);
eventdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
eventdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
} else {
//datePickerDialog.
}
}
});
eventtime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute)
{
boolean isPM = (hourOfDay >= 12);
eventtime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
}
}, mHour, mMinute, false);
timePickerDialog.show();
} else {
// Hide your calender here
}
}
});
submit_btn.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v)
{
if (eventname.getText().toString().trim().equals("")) {
eventname.setError("please enter eventname");
} else if (eventlocation.getText().toString().trim().equals("")) {
eventname.setError("please enter eventlocation");
} else if (eventdate.getText().toString().trim().equals("")) {
eventdate.setError("please enter evendate");
} else if (eventtime.getText().toString().trim().equals("")) {
eventtime.setError("please enter Eventtime");
}
else if (validateTime(String.valueOf(eventdate.getText())))
{
eventdate.setError("please enter Valid Date");
}
else if(validateDate(String.valueOf(eventtime.getText())))
{
eventtime.setError("please enter Valid Date");
}
else
{
Toast.makeText(getContext(), "Welcome to leadgenration", Toast.LENGTH_SHORT);
// ((Lead_Fragment) getParentFragment()).switchFragment1(2);
new Lead_generation().execute();
}
}
class Lead_generation extends AsyncTask<Void,Void,Boolean>
{
protected void onPreExecute()
{
//System.out.println("value of user is preexecute:" + User_mobile + "" + User_password);
progressDialog = new ProgressDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenting....plz wait");
progressDialog.show();
}
protected Boolean doInBackground(Void... params)
{
if(Send_Lead())
{
}
return false;
}
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
if(result==true)
{
Toast.makeText(getActivity(),"Lead Added Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"not add Lead",Toast.LENGTH_SHORT).show();
}
}
}
public boolean Send_Lead()
{
Lead2=getActivity().getSharedPreferences("lead_pref", getContext().MODE_PRIVATE);
String Lead_Cutom_name = Lead2.getString("key_firstname","");
String Lead_Custom_contact = Lead2.getString("key_lastname","");
String Lead_Custom_reference = Lead2.getString("key_user_org","");
String Lead_Eventname=eventname.getText().toString().trim();
String Lead_Eventlocation=eventlocation.getText().toString().trim();
String Lead_EventDate=eventdate.getText().toString().trim();
String Lead_EventTime=eventtime.getText().toString().trim();
System.out.println("value of all leads"+Lead_Cutom_name+" "+Lead_Custom_contact+" "
+Lead_Custom_reference+" "+Lead_Eventname+" "+Lead_Eventlocation+" "+Lead_EventDate+" "+Lead_EventTime);
if(Database.ADD_Lead(getActivity(),Lead_Cutom_name,Lead_Custom_contact,Lead_Custom_reference,Lead_Eventname,Lead_Eventlocation,
Lead_EventDate,Lead_EventTime))
{
return true;
}
else
{
return false;
}
}
public boolean validateTime(final String time)
{
matcher = pattern.matcher(time);
return matcher.matches();
}
public boolean validateDate(String date)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
sdf.parse(date);
return true;
} catch (ParseException ex) {
return false;
}
}
}
LOCATFILE
this is the logcat file show background processing also show the any type of error occur in your project
05-11 06:16:53.858 13059-13059/com.example.admin.bdayevent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.bdayevent, PID: 13059
java.lang.ClassCastException: com.example.dashboard.New_dashboard cannot be cast to com.example.admin.bdayevent.Registration
at com.example.dashboard.Lead_step1.onClick(Lead_step1.java:67)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try like this
put one container or use the existing container and make a fragment transaction there when you click the button. like this
NEWFragment new_fragment = new NEWFragment();
FragmentTransaction transaction = (context).getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, new_fragment, new_fragment.toString());
transaction.addToBackStack(new_fragment.toString());
new_fragment.setArguments(bundle);
transaction.commitAllowingStateLoss();

Data exchange via Intent between Fragments works on pre-5.0 but not on Android 5.0

As a part of The Big Nerd Ranch's Android Guide example Criminal Intent,
I am updating a button with date/time entered in the
Date/TimePicker. Button and Date/TimePicker reside in different
fragments. I am transferring data between them using an Intent. It
works fine on Pre-Lollipop devices but doesn't seem to update button
text on Android 5.0 or Lollipop devices. What am I missing?
Full code can be seen at Github.
CrimeFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
private static final String TAG = "CriminalFragment";
public static final String EXTRA_CRIME_ID = "com.sudhirkhanger.android.criminalintent.crime_id";
private static final String DIALOG_DATE = "date";
private static final String DIALOG_TIME = "time";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
private void updateDateAndTime() {
Date d = mCrime.getDate();
CharSequence c = DateFormat.format("EEEE, MMM dd, yyyy", d);
CharSequence t = DateFormat.format("h:mm a", d);
mDateButton.setText(c);
mTimeButton.setText(t);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before,
int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count,
int after) {
// This space intentionally left blank
}
public void afterTextChanged(Editable c) {
// This one too
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTimeButton = (Button) v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = TimePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(fm, DIALOG_TIME);
}
});
updateDateAndTime();
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDateAndTime();
} else if (requestCode == REQUEST_TIME) {
Date date = (Date) data
.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(date);
updateDateAndTime();
}
}
}
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The problem isn't with the communication between the Fragments, it's that for some reason the default CalendarView DatePicker in Lollipop never calls the OnDateChanged() method, so mDate in DatePickerFragment.java never gets changed; DatePickerFragment sends back to CrimeFragment the same value it received from CrimeFragment, so it only looks like the communication between the two Fragments isn't working.
The Lollipop DatePicker does call OnDateChanged() when it's in SpinnerView mode, so CrimeFragment's date will then get properly updated. Unfortunately, Lollipop ignores the android:calendarViewShown="false" directive in the DatePicker's tag in the dialog_date.xml file. The only way to force the DatePicker to display as spinners is to include a android:datePickerMode="spinner" directive in the DatePicker's xml tag. You will get a warning that this directive is supported in API 21 only, but it will be ignored by devices running pre-5.0 Android.You have to keep the calendarViewShown="false" directive for pre-5.0 devices.
DatePickerDialog appears to have been fixed in Android 5.0, so you could also use that resource in DatePickerFragment to make things work.

app ends while clicking datepicker button

My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.
FirstActivity.java
package example.showevent1;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.os.Bundle;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class FirstActivity extends FragmentActivity implements OnItemSelectedListener, OnDateSetListener {
/** Called when the activity is first created. */
private static final String DATE_FORMAT = "yyyy-MM-dd";
classdbOpenHelper eventsData;
TextView userSelection;
Button okButton;
Button date1;
public EditText date;
private Calendar mCalendar;
private static final String[] items = { "Yalahanka", "Rajai nagar", "Sivaji Nagar", "Koramangala", "RT Nagar", "Banashankari", "Yashwanthpura", "Hebbal" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
okButton = (Button) findViewById(R.id.button2);
date1 = (Button) findViewById(R.id.button1);
userSelection = (TextView) findViewById(R.id.textView1);
Spinner my_spin = (Spinner) findViewById(R.id.spinner1);// data1
my_spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
my_spin.setAdapter(aa);
okButton.setOnClickListener(new clicker());
eventsData = new classdbOpenHelper(this);
date1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePicker();
}
});
}
static final String YEAR = "year";
static final String MONTH = "month";
static final String DAY = "day";
static final String HOUR = "hour";
static final String MINS = "mins";
static final String CALENDAR = "calendar";
private void showDatePicker() {
Object ft = getFragmentManager().beginTransaction();
DatePickerDialogFragment newFragment = new DatePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(YEAR, mCalendar.get(Calendar.YEAR));
args.putInt(MONTH, mCalendar.get(Calendar.MONTH));
args.putInt(DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
newFragment.setArguments(args);
newFragment.show((FragmentManager) ft, "datePicker");
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
userSelection.setText(items[pos]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
userSelection.setText("");
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String datevalue = date1.getText().toString();
String Userselectvalue = userSelection.getText().toString();
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(classdbOpenHelper.KEY_COUNTED,
// metersave.getText().toString());
cv.put(classdbOpenHelper.KEY_DESC, Userselectvalue);
cv.put(classdbOpenHelper.KEY_DATE, datevalue);
db.insert(classdbOpenHelper.DATABASE_TABLE, null, cv);
}
public void onDestroy() {
eventsData.close();
}
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateButtons();
}
private void updateButtons() {
// Set the date button text
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
date1.setText(dateForButton);
}
}
DatePickerDialogFragment.java
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.*;
public class DatePickerDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
Fragment editFragment = getFragmentManager().findFragmentByTag(FirstActivity.ACCESSIBILITY_SERVICE);
OnDateSetListener listener = (OnDateSetListener) editFragment;
return new DatePickerDialog(getActivity(), listener,
args.getInt(FirstActivity.YEAR),
args.getInt(FirstActivity.MONTH),
args.getInt(FirstActivity.DAY));
}
}
You are getting a Nullpointer because you never actually initialize the Calendar object:
mCalendar

Categories

Resources