I am new to Android development.
I want to create a customized date and time picker in my Application.
I downloaded this library from github to achieve this.
When I try to use it in my application, it crashes and I got the following error:
java.lang.IllegalStateException: Activity has been destroyed
Can anybody look at my code to see what I am missing?
import jp.seesaa.android.datetimepicker.date.DatePickerDialog;
import jp.seesaa.android.datetimepicker.time.RadialPickerLayout;
import jp.seesaa.android.datetimepicker.time.TimePickerDialog;
/**
* Created by MAC12 on 20-Apr-15.
*/
public class HomeFragment extends Fragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
public HomeFragment(){
}
String tg="HomeFragment ";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// cls.findViewById(R.layout.fragment_home).setOnClickListener();
return rootView;
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
Button button = (Button) view.findViewById(R.id.date_picker_day);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCls cls=new ActivityCls();
cls.Start();
}
});
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("fragment_home");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public class ActivityCls extends FragmentActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// findViewById(R.layout.date_picker_day).setOnClickListener();
DatePickerDialog.newInstance(HomeFragment.this, 2006, 1, 2)
.show(getSupportFragmentManager(), "datepicker");
}
public void Start()
{
DatePickerDialog.newInstance(HomeFragment.this, 2006, 1, 2)
.show(getSupportFragmentManager(), "datepicker");
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
// Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
// Log.w(TAG, "App destoryed");
super.onDestroy();
}
#Override
public void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) {
}
#Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
}
}
http://developer.android.com/guide/topics/ui/controls/pickers.html here you can see the format of the date is moth day and year, you are pasing year before then you have that exception.
Related
Couldn't find a solution from the existing posts. I'm trying to build a step counter using Android's built in TYPE_STEP_COUNTER sensor but the onSensorChange() method doesn't get called! In the below code, for example, "Outside stepcount" is never printed to the Logcat.
public class StepFragment extends Fragment implements SensorEventListener {
private int step_count = 0;
TextView stepCountText;
private Sensor mStepSensor;
private SensorManager mSensorManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.stepfragment, container, false);
stepCountText = (TextView)view.findViewById(R.id.stepcounttext);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mSensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
System.out.println("Outside" + step_count);
if (event.values[0] == 1.0f) {
step_count++;
System.out.println(step_count);
}
stepCountText.setText(Integer.toString(step_count));
}
#Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepSensor, SensorManager.SENSOR_DELAY_NORMAL);
if(mStepSensor != null)
{
System.out.println("Sensor step counter present");
}
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
System.out.println("Fragment Paused");
}
}
I do get "Sensor step counter present" in my Logcat which proves that my device indeed has the step_counter sensor. I'd be very grateful for some help!
I'm implementing the autocomplete suggestion code in Google map place api.
We are using OnMapReadyCallback as an implement.
The MapView.getMapAsync(this) function was originally used in onCreateView. But now I'm going to use it in setupAutoCompleteFragment. However, in MapView.getMapAsync(this), it is not compiled due to this. What can be used?
public class googlemaptab extends Fragment implements OnMapReadyCallback {
MapView mapview;
Button kakaobutton;
public static googlemaptab newInstance(){
return new googlemaptab();
}
public googlemaptab() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_googlemaptab, container, false);
kakaobutton = (Button)view.findViewById(R.id.kakaobutton);
mapview = (MapView)view.findViewById(R.id.google_map_view);
setupAutoCompleteFragment();
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
kakaobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//클릭하면 카카오maptab으로 이동하겠다.
((MainActivity)getActivity()).replaceFragment(kakaomaptab.newInstance());
}
});
}
#Override
public void onStart() {
super.onStart();
mapview.onStart();
}
#Override
public void onResume() {
super.onResume();
mapview.onResume();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(mapview != null)
{
mapview.onCreate(savedInstanceState);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng SEOUL = new LatLng(37.56, 126.97);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(SEOUL);
markerOptions.title("서울");
markerOptions.snippet("수도");
googleMap.addMarker(markerOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
private void setupAutoCompleteFragment() {
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getActivity().
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mapview.getMapAsync(this);
}
#Override
public void onError(Status status) {
Log.e("Error", status.getStatusMessage());
}
});
}
}
You could do it better this way
private void setupAutoCompleteFragment(OnMapReadyCallback instance) {
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getActivity().
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mapview.getMapAsync(instance);
}
#Override
public void onError(Status status) {
Log.e("Error", status.getStatusMessage());
}
});
}
And don't forget to update your onCreateView with the new function signature as the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_googlemaptab, container, false);
kakaobutton = (Button)view.findViewById(R.id.kakaobutton);
mapview = (MapView)view.findViewById(R.id.google_map_view);
setupAutoCompleteFragment(this);
return view;
}
You can use Classname.this in this case.
For example: if your fragment name is HomeFragment then,
HomeFragment.this
If this still doesn't work then you can override onViewCreated() function and call mapView.getMapAsync(this) inside onViewCreated()
If needed check this link
have you tried with mapview.getMapAsync(getActivity()); instead of mapview.getMapAsync(this);
I created my test project where i code to communicate between two fragments but actully I want to access activity from fragment.
Here is code to connect fragment to fragment, its working absolutely right without any error but now i want to change this code to connect activity from fragment instead of fragment to fragment communication.
So Please change this code to access activities from fragment. I stuck on this issue for than a week.So Guys please resolve this.
here is my mainaactivity:
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void onInputASent(CharSequence input) {
fragmentB.updateEditText(input);
}
#Override
public void onInputBSent(CharSequence input) {
fragmentA.updateEditText(input);
}
Here is my FragmentA.java:
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void onInputASent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputASent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my FragmentB.java:
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
void onInputBSent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputBSent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my Fertilizers.java file which i want to access from FragmentA.:
public class Fertilizers extends AppCompatActivity {
RecyclerView mRecyclerView;
List<FertilizerData> myFertilizersList;
FertilizerData mFertilizersData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager;
gridLayoutManager = new GridLayoutManager(Fertilizers.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myFertilizersList = new ArrayList<>();
mFertilizersData = new FertilizerData("Urea Fertilizer","Urea is a concent","Rs.1900",R.drawable.urea);
myFertilizersList.add(mFertilizersData);
myFertilizersList.add(mFertilizersData); }
}
please write here a block of code to call Fertilzers Activity from FragmentA, I,ll be very thankful to you.
Calling getActivity() in your fragment gives you the calling activity so if MainActivity started your fragment then you would do
(MainActivity(getActivity())).something_from_your_main_activity
Solution found by itself regarding this issue.
FragmentHome.java class should look like this:
public class FragmentHome extends Fragment {
private Button button;
public FragmentHome(){
}
public interface OnMessageReadListener
{
public void onMessageRead(String message);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
button = (Button)v.findViewById(R.id.bn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Fertilizers.class);
intent.putExtra("some"," some data");
startActivity(intent);
}
});
return v;
}
}
FertilizersActivity.java should look like this:
public class Fertilizers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
if(bundle.getStringArrayList("some") !=null){
Toast.makeText(getApplicationContext(),"data:" + bundle.getStringArrayList("some"),Toast.LENGTH_LONG).show();
}
}
}
}
Could guys hep me integrate Startapp network in this activity, this is my code it has not the oncreate method i tried to integrate it but i failed. Please help me. You can find below the code and it does not contain the oncreate method.Im new to coding and i tried lot of time to solve this problem it's easy for me if the oncreate method is there i can integrate the ad network easy. Pleas guys any idea to deal with will help me. Thank you
public class MainFragment extends Fragment {
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
Replace your code with the following
public class MainFragment extends Fragment {
// Add these lines of code which is the onCreate method of your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// put your integration code here
Log.i("MainFragment", "onCreate()");
}
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
Below is a code where data will come at scrolling time but there is an error i.e
ClassCastException. Please help me to solve this error. Now I have added my whole fragment class Similar_Matchs_Tab where we fetching the from server.
java.lang.ClassCastException: com.devbhoomimedia.maangal.ProfilesActivity cannot be cast to android.widget.AbsListView$OnScrollListener
public class Similar_Matchs_Tab extends Fragment {
private ListView listView;
public Similar_Matchs_Tab() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JSON_URL = "https://www.maangal.com/maangal_mobile/similar_matches.php?matri_id="+email;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Inflate the layout for this fragment
View view= inflater.inflate(R.layout.matches_tab, container, false);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnScrollListener((AbsListView.OnScrollListener) getActivity());
sendRequest();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
return view;
}
sendRequest function to fetch the data
private void sendRequest(){
final ProgressDialog loading = ProgressDialog.show(getActivity(),"Loading Data", "Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST,JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
Log.e("Similar MAtches******",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
});
int MY_SOCKET_TIMEOUT_MS = 30000;
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
protected void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
Profile_Match_custom_List cl = new Profile_Match_custom_List(getActivity(), ParseJSON.ids,ParseJSON.ages, ParseJSON.heights, ParseJSON.communities,ParseJSON.castes,ParseJSON.educations,ParseJSON.occupations,ParseJSON.incomes,ParseJSON.pics,ParseJSON.locations,ParseJSON.shortlist,ParseJSON.expressinterest);
listView.setAdapter(cl);
}
}
B'coz you're casting Activity into AbsListView.OnScrollListener interface that's why you're getting classCastException.
just remove listView.setOnScrollListener((AbsListView.OnScrollListener) getActivity());
and replace
listView.setOnScrollListener((ProfileActivity) getActivity());
The reason why you're getting this error is because you're trying to cast activity to a scroll listener which is not possible. So to fix the problem just set the appropriate interface and it should work. Replace listView.setOnScrollListener((AbsListView.OnScrollListener) getActivity()); with this:
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
change it
listView.setOnScrollListener((AbsListView.OnScrollListener) getActivity());
to
listView.setOnScrollListener((ProfileActivity)getActivity());
and ProfileActivity must implements AbsListView.OnScrollListener.
Your activity does not implement AbsListView.OnScrollListener interface.