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);"
Related
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
i get some problem when i use the intent, he said "cannot resolve constructor Intent('....')" , i dont know what is wrong in my code but you can see what i m importing here
package com.example.noen.myintentapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn_move);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_move:
Intent intn = new Intent(MainActivity.this,target1.class);
break;
}
}
}
I made a fragment to connect via Facebook, the code of which is here :
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class LoginFragment extends Fragment
{
private TextView mTextDetails;
private CallbackManager fbCallbackManager;
private AccessTokenTracker tTracker;
private ProfileTracker pTracker;
private FacebookCallback<LoginResult> fbCallback = new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onCancel()
{
}
#Override
public void onError(FacebookException error)
{
}
};
public LoginFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
fbCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
tTracker.startTracking();
pTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setTextDetails(view);
setupFBLoginButton(view);
}
#Override
public void onResume()
{
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onStop()
{
super.onStop();
tTracker.stopTracking();
pTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
fbCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupFBLoginButton(View view)
{
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(fbCallbackManager, fbCallback);
}
private void setTextDetails(View view)
{
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker()
{
tTracker= new AccessTokenTracker()
{
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken)
{
//TODO
}
};
}
private void setupProfileTracker()
{
pTracker = new ProfileTracker()
{
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile)
{
//TODO
}
};
}
}
I am trying to "call" this fragment from my main activity using the following code :
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
{
private boolean logged = false;
private LoginFragment loginFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
LoginFragment loginFragment = new LoginFragment();
fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");
fTransaction.commit();
setContentView(R.layout.activity_main);
}
}
Yet, I have an error on the 2nd argument of this line fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");.
My IDE tells me it's expecting an android.app.Fragment object, and mine is a my.package.LoginFragment.
I don't get it, my LoginFragment extends Fragment...
I also tried to pass everything in android.support.v4.*, but then I can't do loginButton.setFragment(this);, and then I have no idea on how to set the Fragment to the loggin button.
Use getSupportFragmentManager() when working with support fragments instead of getFragmentManager().
Also, adding the fragment should happen after setContentView() so the fragment_container can be found.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginFragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, loginFragment, "fragment_container")
.commit();
}
After doing this you will have to fix a couple imports too. Make sure you use the following in MainActivity.
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.
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");
}