Can not cast android.app.fragment - java

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.

Related

Default constructor is deprecated, I can't find the fragment problem in Adroid Studio

When I write the Code like this, the ControlFragment works fine, but when I use the exact same Code in my other Fragment named "AndresFragment" (second code), it's not working. It says "Default constructor in android.app.Fragment is deprecated". I really don't get it... Can someone please help me, I'm new in
package com.example.fragm;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class ControlFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
}
View myView = inflater.inflate(R.layout.controlfragment,
container, false);
return myView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Code for "AndresFragment":
package com.example.fragm;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AndresFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
// restore internal values if necessary
}
View myView1 = inflater.inflate(R.layout.andresfragment,
container, false);
return myView1;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
That's my Mainactivity.java with the ControlFragment it works:
package com.example.fragm;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
ControlFragment myFragment = new ControlFragment();
getSupportFragmentManager().beginTransaction().add(R.id.my_fragment_container, myFragment).commit();
}
}
But I can't use "AndresFragment"
package com.example.fragm;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
AndresFragment myFragment = new AndresFragment();
getSupportFragmentManager().beginTransaction().add(R.id.my_fragment_container, myFragment).commit();
}
}
When I try to compile it, the error is: "error: no suitable method found for add(int,AndresFragment)
getSupportFragmentManager().beginTransaction().add(R.id.my_fragment_container, myFragment).commit();"
You have wrong import in your AndresFragment.
Instead of:
import android.app.Fragment;
You should use:
import androidx.fragment.app.Fragment;
In your first file you have proper import and that is why you don't have error there, android.app.Fragment is old and deprecated so that is why you receive error message since you should be using new one.
If you are getting this:
just invalidate caches and restart

agment.onCreatePreferences at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:228)

I tried to create a settings activity for my android app but when I click the button that it's supposed to open the settings activity I get the following errors and my app goes back to my main activity.
Errors:
agment.onCreatePreferences(SettingsFragment.java:10)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:228)
Files mentioned by the errors:
PreferenceFragmentCompat.java
... // Fallback to default theme.
theme = R.style.PreferenceThemeOverlay;
}
mStyledContext = new ContextThemeWrapper(getActivity(), theme);
mPreferenceManager = new PreferenceManager(mStyledContext);
mPreferenceManager.setOnNavigateToScreenListener(this);
final Bundle args = getArguments();
final String rootKey;
if (args != null) {
rootKey = getArguments().getString(ARG_PREFERENCE_ROOT);
} else {
rootKey = null;
}
onCreatePreferences(savedInstanceState, rootKey); <---line 228
} ...
SettingsFragment
package com.example.padmw;
import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
And also my Settings activity
package com.example.padmw;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import java.util.Objects;
public class SettingsActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Objects.requireNonNull(getSupportActionBar()).setTitle("Settings");
if(findViewById(R.id.fragment_container)!= null)
{
if(savedInstanceState !=null)
return;
getSupportFragmentManager()
.beginTransaction().add(R.id.fragment_container,new SettingsFragment()).commit();
}
}
}
I also get an "Cannot resolve symbol 'R'" in on in the PreferenceFragmentCompat.java in "R.style.PreferenceThemeOverlay;"
So what is the problem and what should I do?
If you need more info, please let me know.
I add that those errors appeared after I replaced getFragmentManager with getSupportFragmentManager
in here :
package com.example.padmw;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import java.util.Objects;
public class SettingsActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Objects.requireNonNull(getSupportActionBar()).setTitle("Settings");
if(findViewById(R.id.fragment_container)!= null)
{
if(savedInstanceState !=null)
return;
getSupportFragmentManager()
.beginTransaction().add(R.id.fragment_container,new SettingsFragment()).commit();
}
}
}
Errors disappeared after I deleted the line "super.onCreate(savedInstanceState);"

How to convert an activity to a fragment in Android Studio?

I have this activity
package com.padilla.jorge.proyecto_aplicaciones_moviles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
public class VerPerfil extends AppCompatActivity {
private String[] arraySpinner;
Intent i;
TextView Nombre_TextView;
TextView Email_TextView;
TextView Password_TextView;
TextView Puntos_TextView;
TextView getNombre;
TextView getEmail;
TextView getPassword;
TextView getPuntos;
ArrayList<TextView> textViewsVal;
ArrayList<TextView> textViewsName;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference;
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_perfil);
Nombre_TextView=(TextView)findViewById(R.id.Nombre_textView);
Email_TextView=(TextView)findViewById(R.id.Email_TextView);
Password_TextView=(TextView)findViewById(R.id.Password_TextView);
Puntos_TextView=(TextView)findViewById(R.id.Puntos_TextView);
getNombre=(TextView)findViewById(R.id.Nombre_valor);
getEmail=(TextView)findViewById(R.id.Email_valor);
getPassword=(TextView)findViewById(R.id.Password_valor);
getPuntos=(TextView)findViewById(R.id.Puntos_valor);
textViewsName = new ArrayList<TextView>();
textViewsName.add(Nombre_TextView);
textViewsName.add(Email_TextView);
textViewsName.add(Password_TextView);
textViewsName.add(Puntos_TextView);
textViewsVal = new ArrayList<TextView>();
textViewsVal.add(getNombre);
textViewsVal.add(getEmail);
textViewsVal.add(getPassword);
textViewsVal.add(getPuntos);
Intent name_intent=this.getIntent();
final String name=name_intent.getExtras().getString("name");
reference = database.getReference(name).child("Perfil");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//rutina.setText(dataSnapshot.getKey());
int i = 0;
Log.d("number of childs",""+dataSnapshot.getChildrenCount());
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (i < 10) {
textViewsName.get(i).setText(child.getKey());
textViewsVal.get(i).setText(child.getValue().toString());
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
and i was wondering if there's a simple way to convert it to a fragment? Any help would be appreciated.
The reason i want to do this is because i want to implement a navigation drawer menu and i've seen that you have to use fragments (i know there's a way to do it with classes but it's way more complicated) and i already have this class so i would like to reuse it instead of creating a new fragment from scratch.
Let's try this:
Extend fragment and refactor MyActivityClass to MyFragmentClass
original: public class MyActivityClass extends AppCompatActivity
converted: public class MyFragmentClass extends Fragment
Create factory method and add all the values that you get from getIntent().getExtra() as parameters for the method
original: String name=getIntent.getExtras().getString("name");
converted:
This
public static MyFragmentClass newInstance(String name){
MyFragmentClass fragment = new MyActivity();
Bundle args = new Bundle();
args.putString(KEY_NAME, name);
fragment.setArguments(args);
return fragment;
}
and this,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
name = getArguments().getString(KEY_NAME);
}
}
override method onCreateView() and inflate your layout
original: setContentView(R.layout.activity_layout);
converted:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_layout, container, false);
return view;
}
place all the findViewById(...); statement in onCreateView() and rename to view.findViewById(...) and other code which does not need the activity to run.
override onActivityCreated() and place all the code that needs Activty in here.
remove code already converted to fragment
It's not the perfect answer but should help.
Try this:
Create fragment
Move that code and layout to fragment instead
Now you have a reusable fragment
Add the fragment in your activity or navigation drawer or wherever you like

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().

Pass data from Activity to SupportMapFragment

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");
}

Categories