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;
Related
My main class:
package edu.temple.webbrowser;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
public class BrowserActivity extends AppCompatActivity implements PageControlFragment.SendURLInterface, PageControlFragment.goBackInterface, PageControlFragment.goNextInterface, PageViewerFragment.SetURLInterface, PageViewerFragment.resetUrlInterface {
PageControlFragment PCFrag = new PageControlFragment();
PageViewerFragment PVFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Browser Activity");
if(getSupportFragmentManager().findFragmentById(R.id.page_viewer) == null && getSupportFragmentManager().findFragmentById(R.id.page_control) == null){
PVFrag = new PageViewerFragment();
FragmentManager FM = getSupportFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.page_viewer, PVFrag);
FT.add(R.id.page_control, PCFrag);
FT.commit();
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
public void SendURL(String URL){
String reqStr = "https://";
if(!URL.substring(0,reqStr.length()).equals(reqStr)){
URL = reqStr.concat(URL);
}
PVFrag.setURL(URL);
PCFrag.setText(PVFrag.getURL());
}
#Override
public void SetURL() {
PCFrag.setText(PVFrag.getURL());
}
#Override
public void goBack() {
PVFrag.goBack();
}
public void goNext() {
PVFrag.goNext();
}
public void resetUrl(){
String reset = PCFrag.getText();
PVFrag.setURL(reset);
}
}
The Fragment:
public class PageViewerFragment extends Fragment {
WebView browser;
String reqStr = "https://";
private Bundle webViewBundle;
String url_ = "https://google.com";
public PageViewerFragment() {
// Required empty public constructor
}
public static PageViewerFragment newInstance() {
PageViewerFragment fragment = new PageViewerFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
browser.saveState(outState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState == null) {
browser.loadUrl("https://www.google.com");
} else {
browser.restoreState(savedInstanceState.getBundle("web"));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_page_viewer, container, false);
browser = v.findViewById(R.id.browser);
browser.setWebViewClient(new WebViewClient());
browser.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
((PageViewerFragment.SetURLInterface) getActivity()).SetURL();
}
});
return v;
}
public String boolString(boolean b){
if(b) return "true";
return "false";
}
public void goBack(){
if(browser.canGoBack()){
browser.goBack();
}
}
public void goNext(){
if(browser.canGoForward()){
browser.goForward();
}
}
public void setURL(String url) {
browser.loadUrl(url);
}
public String getURL(){
return browser.getUrl();
}
interface SetURLInterface {
void SetURL();
}
interface resetUrlInterface{
void resetUrl();
}
I have everything working except when I rotate the screen the webview fragment becomes null. I've spent a lot of time looking through posts for a solution to this. The Page control fragment works fine, when I click the go button to send the url to the page viewer then the program crashes.
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);"
im making a simple app with youtube views and stuff but whenever i run the app i get no errors but the app doesn't open and on my simulator it says "CFBC (the name of my app) Has stopped running" here is my code i have 6 activities i know its a lot but if anyone can tell me why its crashing with 0 errors would help a ton
package org.cfbcla.cfbc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kwia on 8/4/17.
*/
public class Display extends AppCompatActivity {
YouTubePlayerView mYouTubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
btnPlay = (Button) findViewById(R.id.btnPlay);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlay);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
List<String> videoList = new ArrayList<>();
videoList.add("QOwE0XQei_M");
videoList.add("5sTXWESDBB0");
youTubePlayer.loadVideos(videoList);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mYouTubePlayerView.initialize(YTConfig.getApiKey(), mOnInitializedListener);
}
});
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button3) {
Intent i4 = new Intent(Display.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by kwia on 8/4/17.
*/
public class Display2 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display2);
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button) {
Intent i4 = new Intent(Display2.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by kwia on 8/4/17.
*/
public class Display3 extends AppCompatActivity{
YouTubePlayerView mYouTubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display3);
btnPlay = (Button) findViewById(R.id.btnPlay);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlay);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("sFXQ1vAaKXA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mYouTubePlayerView.initialize(YTConfig.getApiKey(), mOnInitializedListener);
}
});
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button) {
Intent i4 = new Intent(Display3.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by kwia on 8/4/17.
*/
public class Display4 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display4);
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button4) {
Intent i4 = new Intent(Display4.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v) {
if (v.getId() == R.id.A) {
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
}
public void onButtonClick2(View v2) {
if (v2.getId() == R.id.C) {
Intent i2 = new Intent(MainActivity.this, Display2.class);
startActivity(i2);
}
}
public void onbuttonClick3(View v3) {
if (v3.getId() == R.id.S) {
Intent i3 = new Intent(MainActivity.this, Display3.class);
startActivity(i3);
}
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.M) {
Intent i4 = new Intent(MainActivity.this, Display4.class);
startActivity(i4);
}
}
}
I want to call WebView Activity from MainActivity using Intent and I stored 5 urls in a string-array.xml
What I want: On Clicking List item in MainActivity it should open WebView activity and using [position] it should open exact url associated with list-item.
Code Description:
string-array.xml:
<string-array name="bookmark_urls">
<item>http://www.google.com</item>
<item>http://www.android.com/</item>
<item>http://www.toi.com/</item>
<item>http://www.facebook.com/</item>
<item>http://www.makemytrip.com/</item>
<item>http://www.yatra.com/</item>
</string-array>
In MainActivity.java I called Intent:
String[] urls = getResources().getStringArray(R.array.bookmark_urls);
Intent i = new Intent(MainActivity.this, Web_view.class);
i.putExtra("urls", urls[position]);
startActivity(i);
So, How I can properly call my String urls to next Webview ?
I want something like this:
mainWebView.loadUrl("http://www.google.com");
In you webActivity do this
Intent i = getIntent();
String url = i.getStringExtra("urls");
WebView mywebview = (WebView) findViewById(R.id.webView1);
mywebview.loadUrl(url);
WebView ww = (WebView)findViewById(R.id.ww);
WebSettings webSettings = ww.getSettings();
webSettings.setJavaScriptEnabled(true);
String WebURL=getIntent().getStringExtra("urls")
ww.loadUrl(WebURL);
Obtain and load the url in the onCreate of the activity Web_view :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the webView here
// load the url
final Intent intent = getIntent();
final String url = intent.getStringExtra("urls");
webView.loadUrl(url);
}
Please try to use my trick it will definately work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mainWebView = (WebView) findViewById(R.id.mainWebView);// pass here your webview id
WebSettings settings = mainWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
String urlStr = getIntent().getStringExtra("urls");
mainWebView.loadUrl(urlStr);
}
## Fragment with base Fragment ##
Create pass URL in Constructor of Fragment like this
mFragment = new Fragment1().newInstance(""+position,"url");
- Fragment1.class
package com.mydemo.fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ProgressBar;
import com.myadhaar.R;
import com.mydemo.Utils.Constants;
import com.mydemo.interfaces.OnFragmentInteractionListener;
public class Fragment1 extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String Fragmentposition;
private String param2,URL;
View rootView;
private ProgressBar probressbar;
WebView mWebView;
private OnFragmentInteractionListener mListener;
public Fragment1()
{
}
public static Fragment1 newInstance(String Fragmentposition, String param2)
{
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, Fragmentposition);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
Fragmentposition = getArguments().getString(ARG_PARAM1);
param2 = getArguments().getString(ARG_PARAM2);
URL = param2;// Constants.Url[Integer.parseInt(Fragmentposition)];
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_adrno, container, false);
initViews();
setToViews();
clickToViews();
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setwebView(mWebView,probressbar,URL);
}
#Override
public void initViews() {
super.initViews();
mWebView = (WebView) rootView.findViewById(R.id.webview);
probressbar = (ProgressBar) rootView.findViewById(R.id.progressBar);
}
#Override
public void setToViews() {
super.setToViews();
}
#Override
public void clickToViews() {
super.clickToViews();
}
#Override
public void setwebView(WebView webView,ProgressBar probressbar, String URL) {
super.setwebView(webView,probressbar, URL);
}
public void onButtonPressed(Uri uri)
{
if (mListener != null)
{
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener)
{
mListener = (OnFragmentInteractionListener) context;
} else
{
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
}
1. BaseFragment.class
package com.mydemo.fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewFragment;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.myadhaar.R;
import com.mydemo.interfaces.FragmentViews;
public class BaseFragment extends Fragment implements FragmentViews{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
FrameLayout frame_container;
public BaseFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_base, container, false);
frame_container = (FrameLayout) mRelativeLayout.findViewById(R.id.frame_container);
super.onCreateView(inflater, mRelativeLayout, savedInstanceState);
return mRelativeLayout;
}*/
public void onButtonPressed(Uri uri)
{
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Override
public void onDetach()
{
super.onDetach();
}
#Override
public void initViews() {
}
#Override
public void setToViews() {
}
#Override
public void clickToViews() {
}
#Override
public void setwebView(WebView mWebView, final ProgressBar probressbar, String URL) {
probressbar.setProgress(0);
probressbar.setMax(100);
WebSettings mWebSettings = mWebView.getSettings();
mWebView.setWebViewClient(new WebViewClient());
mWebSettings.setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
mWebSettings.setBuiltInZoomControls(true);
mWebSettings.setLoadWithOverviewMode(true);
mWebSettings.setUseWideViewPort(true);
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setSaveFormData(true);
mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mWebSettings.setLoadWithOverviewMode(true);
mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
mWebSettings.setBuiltInZoomControls(true);
mWebSettings.setAppCachePath( getActivity().getApplicationContext().getCacheDir().getAbsolutePath() );
mWebSettings.setAllowFileAccess( true );
mWebSettings.setAppCacheEnabled( true );
mWebSettings.setJavaScriptEnabled( true );
mWebSettings.setCacheMode( WebSettings.LOAD_DEFAULT );
mWebView.loadUrl(/*URL*/"");
mWebView.setWebViewClient(new MyWebViewClient()
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
probressbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
probressbar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
webView.loadUrl(url);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
handler.cancel();
}
});
if (Build.VERSION.SDK_INT > 11)
{
mWebView.getSettings().setDisplayZoomControls(false);
}
}
}
3. Inteface that should implent on BaseFragment.class
public interface FragmentViews {
public abstract void initViews();
public abstract void setToViews();
public abstract void clickToViews();
public abstract void setwebView(WebView webView, ProgressBar probressbar,String URL);
}
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");
}