Pass data from Activity to SupportMapFragment - java

I have two fragments and one activity.
DataFragment passes info succesfuly to MainActivity and that's why there is no point providing you the code of it. My issue is , that bundle isn't effective on MyMapFragment which extends SupportMapFragment when I am trying to pass data from MainActivity. Of course I've searched a lot for many days but the only solutions given are for a fragment and not for SupportMapFragment which I think it's different.
MainActivity
package com.manuelpap.mapapp;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.SupportMapFragment;
import com.parse.Parse;
public class MainActivity extends AppCompatActivity {
public String mapLocation="EMPTY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
Intent intent = getIntent();
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
MyMapFragment fragobj=new MyMapFragment();
fragobj.setArguments(bundle);
Log.d("MAPLOCATION", "----MainActivity---- " + mapLocation);
finish(); //I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
}
}
public class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
return new MyMapFragment();
}
}
#Override
public int getCount(){
return 2; //posa scrolls dexia (pages) theloume
}
#Override
public CharSequence getPageTitle(int position) {
if(position==0){
return "DATA";
}
else {
return "MAP";
}
}
}
}
MyMapFragment
package com.manuelpap.mapapp;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Handler handler=new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (getArguments() == null)
location = "------NOTHING RECIEVED------";
else
location =getArguments().getString("message");
Log.d("MAPFRAGMENTLOCATION", location);
handler.postDelayed(this, 200); // set time here to refresh textView
}
});
GoogleMap googleMap = getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(40.416775, -3.70379));
googleMap.addMarker(markerOptions);
}
}

It looks like you are finishing your main activity
//I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
Your DataFragment is in the viewpager so it is supposed to start along with your map fragment. You are not starting multiple instances of main activity that I can see here.
When you call finish() on your main activity that means that the map and pager and everything goes away. Not sure what exactly your looking for but I assume you are trying to pass the location string to the map so I have tailored my answer to fit that use case.
The problem is that you are using new MyMapFragment() without the bundle in the view pager. The other logic that you have in MainActivity pertaining to the Map fragment is not going anything to the one that is displayed with the view pager. Essentially you are just creating another instance of the map fragment that is not displayed anywhere. The view pager is the class that needs the data passed to it.
I thought this link might be helpful here to explain the newInstance Method.
Creating a Fragment: constructor vs newInstance()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
}
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), mapLocation));
}
public class MyAdapter extends FragmentPagerAdapter{
private String mMapLocation;
public MyAdapter(FragmentManager fm, String mapLocation) {
super(fm);
mMapLoaction = mapLocation;
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
Bundle bndl = new Bundle();
if(!TextUtils.isEmpty(mapLocation))
bndl.putString("message", mapLocation);
return new MyMapFragment.newInstance(bndl);
}
}
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
public static MyMapFragment newInstance(Bundle bundle) {
MyMapFragment myMapFragment= new MyMapFragment ();
if (bundle != null) {
myMapFragment.setArguments(bundle);
}
return myMapFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(getArguments()!=null)
location =getArguments().getString("message");
}

Related

Pass the data from activity to Page Adapter

I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
Main Activity Code
package com.example.tablay;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import com.google.android.material.tabs.TabLayout;
import java.util.List;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
}
Page Adapter Code :
package com.example.tablay;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.Date;
import java.util.List;
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
public TabFragmentPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}
Fragment Code:
package com.example.tablay;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class tab1Fragment extends Fragment {
public tab1Fragment() {
// 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_tab1, container, false);
TextView tes=(TextView) view.findViewById(R.id.testtab1);
String strtext = getArguments().getString("edttext");
tes.setText(strtext);
return view;
}
}
I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
You can pass data from activity to the adapter by constructor like this :
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager(),ActivityStringData));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
to
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
String data=null;
public TabFragmentPagerAdapter(#NonNull FragmentManager fm,String activityData) {
super(fm);
this.data=activityData
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}

"null object reference error" when trying to use TTS

I am trying to use Text-To-Speech but get the following error:
2020-07-26 22:58:51.876 15964-15964/ch.yourclick.kitt
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ch.yourclick.kitt, PID: 15964
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int,
java.util.HashMap)' on a null object reference
at ch.yourclick.kitt.MainActivity.speak(MainActivity.java:61)
at ch.yourclick.kitt.fragments.GeneralFragment$1.onClick(GeneralFragment.java:59)
MainActivity.java
package ch.yourclick.kitt;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import java.util.Locale;
import ch.yourclick.kitt.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
public TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
// Text to speech
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) { // <-- I never get into that if statement
int result = tts.setLanguage(Locale.getDefault());
// Language is not supported
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
}
else {
Log.e("TTS", "" + status); // Returns -1
Log.e("TTS", "" + TextToSpeech.SUCCESS); // Returns 0
}
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
/**
* Speak
*/
public void speak() {
String text = "Hello";
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
/**
* Turn off
*/
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
GeneralFragment.java
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import ch.yourclick.kitt.MainActivity;
import ch.yourclick.kitt.R;
/**
* A simple {#link Fragment} subclass.
* Use the {#link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_general, container, false);
Button hello = view.findViewById(R.id.hello);
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity mainActivity = new MainActivity();
mainActivity.speak();
}
});
return view;
}
}
It seems like tts returns null but why?
Consider the following two snippets from your post:
// Code found in onCreate(...) in MainActivity.java
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
// A bunch of code here
}
and
// Code found in an OnClickListener in GeneralFragment.java
MainActivity mainActivity = new MainActivity();
mainActivity.speak();
You're probably getting a NullPointerException due to the fact that tts is null when you call through to mainActivity.speak().
While your intentions were good, the reason for this not working as planned is that you're actually creating a new instance of MainActivity that hasn't gone through the appropriate lifecycle steps, meaning that onCreate(...) was never called and thus tts was never assigned... in that specific activity instance. Worth mentioning is that the "real" activity instance your fragment is running in however should have it set-up correctly.
So, what's the fastest way to get it working? Well, I'd say get the current activity, cast it to MainActivity if possible and try to call speak() on that instance instead:
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Activity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).speak();
}
}
});

FragmentViewPagerAdapter not calling getItem after screen rotation

I have a custom viewPagerAdapter in this activity, when the first launch of the activity (When the main activity starts it with the intent) the pager displays the fragments correctly, but when I rotate the device, the recipe is got from the savedInstantState, and the adapter is started, but the fragments are not displayed and the getItem method doesn't get callled!
Here's the code for the Activity:
package com.ameer.bake.activities;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.ameer.bake.Constants;
import com.ameer.bake.fragments.IngredientsFragment;
import com.ameer.bake.fragments.StepDetailsFragment;
import com.ameer.bake.fragments.StepsFragment;
import com.ameer.bake.R;
import com.ameer.bake.models.Recipe;
import com.ameer.bake.models.Step;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class DetailsActivity extends AppCompatActivity implements StepsFragment.StepCallback{
private Recipe recipe;
private IngredientsFragment ingredientsFragment;
private StepsFragment stepsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState != null){
recipe = new Gson().fromJson(savedInstanceState.getString(Constants.RECIPE), Recipe.class);
setupViewPager();
} else if (getIntent().hasExtra(Constants.CURRENT_RECIPE_KEY) ) {
Gson gson = new Gson();
recipe = gson.fromJson(getIntent().getStringExtra(Constants.CURRENT_RECIPE_KEY), Recipe.class);
setTitle(recipe.getName());
setupViewPager();
}
}
#Override
public void onStepClicked(Step step) {
Intent intent = new Intent(DetailsActivity.this, StepActivity.class);
intent.putExtra(Constants.STEP_KEY, new Gson().toJson(step));
startActivity(intent);
}
private class RecipePagerAdapter extends FragmentPagerAdapter {
private static final int NUM_ITEMS = 2;
private final String[] titles = new String[]{
getString(R.string.ingredients), getString(R.string.steps)};
private RecipePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
if (ingredientsFragment == null && stepsFragment == null) {
ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setIngredients(recipe.getIngredients());
stepsFragment = new StepsFragment();
stepsFragment.setSteps(recipe.getSteps());
stepsFragment.setCallback(DetailsActivity.this);
}
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ingredientsFragment;
case 1:
return stepsFragment;
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(Constants.RECIPE, new Gson().toJson(recipe));
super.onSaveInstanceState(savedInstanceState);
}
private void setupViewPager(){
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
FragmentPagerAdapter pagerAdapter = new RecipePagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(pagerAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpager_tab);
viewPagerTab.setViewPager(vpPager);
}
}
Switch to a FragmentStatePagerAdapter rather than using FragmentPagerAdapter. Also use getChildFragmentManager() instead of getSupportFragmentManager()
The solution was as Pedro Varela mentioned in the comments:
"Hope this works. Add setRetainInstance(true); in onCreate of your internal fragments of the view pager "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated""
Thanks

Error on getApplicationContext()

I have an Error on Public View onCreateView on getApplicationContext seems it wont work at my HomeFragment, but when I try this at my MainAcitivity it work. does anyone encounter this?
Thanks in Advance!
Here`s my Code:
package com.thesis.artificialintelligence;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
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.Locale;
public class HomeFragment extends Fragment {
private TextView resultTEXT;
private TextView resultTEXT2;
TextToSpeech t1;
private String package_calculator = "com.android.calculator2";
private String class_calculator ="com.android.calculator2.Calculator";
private String package_camera = "com.android.camera";
private String class_camera ="com.android.camera.Camera";
private String package_contacts = "com.android.contacts";
private String class_contacts = "com.android.contacts.Contacts";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
rootView.findViewById(R.id.TVresult);
rootView.findViewById(R.id.TVresult2);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() // There`s an Error here at getApplicationContext()
{
#Override
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
t1.setLanguage(Locale.UK);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach()
{
super.onDetach();
}
}
Fragments do not have a getApplicationContext() method.
TextToSpeech only needs a context so you can replace it with getActivity().
If you really want the application context do getActivity().getApplicationContext()
Dear you can get Context using
getActivity().getApplicationContext();
If you are using fragment than replace getApplicationContext() to getActivity() and getContext().

Can not cast android.app.fragment

I've seen other posts, and they all suggest that the host activity java file is not extending android.support.v4.app.Fragment. However, I don't know how to make the hosting java file extend android.support.v4.app.Fragment.
I've tried adding the dependency to the gradle file but that doesn't work either.
Here's the hosting activity snippet:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import course.examples.fragmentstaticlayout.TitlesFragment.ListSelectionListener;
public class QuoteViewerActivity extends Activity implements ListSelectionListener{
public static String[] mTitleArray;
public static String[] mQuoteArray;
private QuotesFragment mDetailsFragment;
private static final String TAG = "QuoteViewerActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTitleArray = getResources().getStringArray(R.array.Titles);
mQuoteArray = getResources().getStringArray(R.array.Quotes);
setContentView(R.layout.main);
mDetailsFragment = (QuotesFragment) getFragmentManager().findFragmentById(R.id.details);
}
The line in question is the last line of the snippet. And here is my QuotesFragment.
import android.content.Context;
import android.os.Bundle;
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;
public class QuotesFragment extends Fragment {
private TextView mQuoteView = null;
private int mCurrIdx = -1;
private int mQuoteArrayLen;
private static final String TAG = "QuotesFragment";
public int getShownIndex() {
return mCurrIdx;
}
public void showQuoteAtIndex(int newIndex) {
if (newIndex < 0 || newIndex >= mQuoteArrayLen)
return;
mCurrIdx = newIndex;
mQuoteView.setText(QuoteViewerActivity.mQuoteArray[mCurrIdx]);
}
#Override
public void onAttach(Context context){
Log.i(TAG, getClass().getSimpleName() + ":entered onAttach()");
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, getClass().getSimpleName() + ":entered onCreate()");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.quote_fragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mQuoteView = (TextView) getActivity().findViewById(R.id.quoteView);
mQuoteArrayLen = QuoteViewerActivity.mQuoteArray.length;
}
Assuming that I'm right about the host activity not extending the support.v4, how would I do this?
This is because you are trying to cast Fragment to SupportFragment.
Your QuotesFragment is extending SupportFragment, and while casting you are trying to use FragmentManager and fragment which returns Fragment, not supportFragment.
Try using geSupportFragmentManager instead getFragmentManager.
Also you should extend AppCompatActivity or FragmentActivity instead of Activity for your QuoteViewerActivity
Here is similar question
Try changing your getFragmentManager() to getSupportFragmentManager() and extending FragmentActivity instead of Activity in your QuoteViewerActivity.

Categories