YoutubePlayer API endless loading issue - java

I am starting a new intent whenever a new geofence transition happens.
In GeofenceTransitionService.java:
Intent intent = new Intent(GeofenceTransitionService.this, VideoActivity.class);
intent.putExtra("videoID", videoURLS[i]);
startActivity(intent);
And I am initializing the fragment like this,
in VideoActivity.java:
public class VideoActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private String videoID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoID = getIntent().getStringExtra("videoID");
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtubePlayerFragment);
youTubePlayerFragment.initialize("APIKEY", this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION |
YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
if(!wasRestored) {
youTubePlayer.cueVideo(videoID);
}
youTubePlayer.setFullscreenControlFlags(0);
youTubePlayer.setFullscreen(true);
youTubePlayer.setShowFullscreenButton(false);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
final int REQUEST_CODE = 1;
if(error.isUserRecoverableError()) {
error.getErrorDialog(this,REQUEST_CODE).show();
} else {
String errorMessage = String.format("There was an error initializing the YoutubePlayer (%1$s)", error.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
}
activity_video.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".VideoActivity">
<fragment
android:id="#+id/youtubePlayerFragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.appcompat.widget.LinearLayoutCompat>
But the video will never load. It works fine on other activities though. I have checked the manifest but couldn't find anything that differentiates this activity from the other one that works. I use the same code for the other activity to initialize the other fragment.

I forgot to split the video url to get the videoID.
intent.putExtra("videoID", videoURLS[i].split("=")[1]);

Related

Android Studio - Chat not displaying

Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:id="#+id/activity_main"
tools:context="com.example.syafiq.mychatapp.MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send"
android:id="#+id/fab"
android:tint="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
app:fabSize="mini"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
>
<EditText
android:id="#+id/messageinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fab"
android:layout_centerHorizontal="true"
android:hint="Message..." />
</android.support.design.widget.TextInputLayout>
<ListView
android:id="#+id/list_of_message"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/fab"
android:dividerHeight="16dp"
android:divider="#android:color/transparent"
android:layout_marginBottom="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Maincode
private static int SIGN_IN_REQUEST_CODE =1;
//private List<ChatMessage> list = new ArrayList<ChatMessage>();
FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout activity_main;
FloatingActionButton fab;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference myRef = db.getReference("message");
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.menu_signout)
{
AuthUI
.getInstance()
.signOut(this)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
Snackbar
.make(
activity_main,
"You have been signed out.",
Snackbar.LENGTH_SHORT
).show()
;
finish();
}
}
)
;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==SIGN_IN_REQUEST_CODE)
{
if (resultCode==RESULT_OK)
{
Snackbar
.make(
activity_main,
"Successfully signed in!",
Snackbar.LENGTH_SHORT
).show()
;
displayChatMessage();
}
else
{
Snackbar
.make(
activity_main,
"We couldn't sign you in. Please try again lter!",
Snackbar.LENGTH_SHORT
).show()
;
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main = (RelativeLayout) findViewById(R.id.activity_main);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab
.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText input = (EditText) findViewById(R.id.messageinput);
FirebaseDatabase
.getInstance()
.getReference()
.push()
.setValue(
new ChatMessage(
input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()
)
)
;
input.setText("");
displayChatMessage();
}
}
)
;
if (FirebaseAuth.getInstance().getCurrentUser()== null)
{
startActivityForResult(
AuthUI
.getInstance()
.createSignInIntentBuilder()
.build(),
SIGN_IN_REQUEST_CODE
);
}
else
{
Snackbar
.make(
activity_main,
"Welcome " + FirebaseAuth
.getInstance()
.getCurrentUser()
.getEmail(),
Snackbar.LENGTH_SHORT
).show()
;
//displayChatMessage();
}
}
DisplaychatMessage() function to display my chat message
private void displayChatMessage() {
Query query = FirebaseDatabase.getInstance().getReference().child("Chats");
ListView listofmsgs = (ListView) findViewById(R.id.list_of_message);
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions
.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.list_item)
.build()
;
//adapter.startListening();
Log.d("ErrorCheck", "1");
adapter = new FirebaseListAdapter<ChatMessage>(options) {
#Override protected void populateView(View v, ChatMessage model, int position) {
//ChatMessage cm = (ChatMessage) model;
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById(R.id.messageinput);
messageUser = (TextView) v.findViewById(R.id.message_user);
messageTime = (TextView) v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText().toString());
messageUser.setText(model.getMessageUser());
messageTime
.setText(
android.text.format.DateFormat.format(
"dd-mm-yyyy (HH:mm:ss)",
model.getMessageTime()
)
)
;
Log.d("ErrorCheck", "2");
}
};
listofmsgs.setAdapter(adapter);
adapter.startListening();
}
Hi guys, i did this but it doesn't seem like anything appear on my APP. But the then, when i press send, in my database, my chat appears there but again it doesn't appear on my Chat app. I did a debug log. Errorcheck 1, and 2 to see where the code ends. When i checked, looks like the debug log only display up till ErrorCheck 1 and does not display display 2. How do i solve this?
You've put ErrorCheck 2 in something called an anonymous class. That's why calling your displayChatMessage() will only log ErrorCheck 1. The code in the anonymous FirebaseListAdapter class you defined will only run when it's populateView() method is called. You don't call that method. You call adapter.startListening(); Something, somewhere, needs to call adapter.populateView() before you'll see ErrorCheck 2 logged.
You likely don't want to call it here. You can call it here just for a test but you should track down what is supposed to be calling it.
According to the docs about FirebaseListAdapter
This class is a generic way of backing an Android ListView with a Firebase location. It handles all of the child events at the given Firebase location. It marshals received data into the given class type. Extend this class and provide an implementation of populateView, which will be given an instance of your list item mLayout and an instance your class that holds your data. Simply populate the view however you like and this class will handle updating the list as the data changes.
So trying changing the data and see if that makes you log ErrorCheck 2

How to pass string url from Main Activity to next Activity and load url in webView [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
I have two Activity, One is Mainactivity and another is Secondactivity. Secondactivity contains Webview that loads local HTML pages from assets folder.
Mainactivity contains buttons labeled as Button A and Button B when pressed would start Secondactivity. I would like to pass the string as URL from Mainactivity to Secondactivity which loads the A.html and B.html when Button A and Button B is pressed.
For now, I have following code in Mainactivity Class
Fragment firstFragment1 = new browser();
Bundle args1 = new Bundle();
args1.putString("url1", "file:///android_asset/diploma.html");
firstFragment1.setArguments(args1);
moveToFragment(firstFragment1);
break;
and on SecondActivity Class, I have following code
String url1 = getArguments().getString("url1");
myWebView=(WebView)rootView.findViewById(R.id.webview);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setLoadsImagesAutomatically(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.setInitialScale(1);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
WebSettings webSettings = myWebView.getSettings();
myWebView.loadUrl(url1);
return rootView;
}
Which work for Fragment flawlessly, but how do I make it work for Activity to activity??
In first activity you should put extra argument to intent like this:
// I assume Web.class is your second activity
Intent intent = new Intent(this, Web.class);
intent.putExtra("url", your_url);
startActivity(intent);
Then in second activity you retrive argument like this:
String url = getIntent().getExtras().getString("url");
webView.load(url);
Make one single common activity which load web url
for example:
public class WebviewActivity extends AppCompatActivity {
Activity mActivity;
WebView webview_;
String title ="";
String url ="";
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_webview_activity);
mActivity = this;
findviews();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
url = bundle.getString("Url");
setAction();
}
else {
webview_.setVisibility(View.GONE);
}
}
private void setAction() {
try {
//check internet connection first
if (CommonUtils.isConnectingToInternet(WebviewActivity.this)) {
webview_.setVisibility(View.VISIBLE);
WebSettings webSettings = webview_.getSettings();
webview_.setWebViewClient(new MyWebViewClient());
webSettings.setJavaScriptEnabled(true);
webview_.getSettings().setSupportZoom(true);
webview_.getSettings().setBuiltInZoomControls(true);
webview_.getSettings().setDisplayZoomControls(true);
webview_.loadUrl(url);
}
else {
//alert - no internet connection
}
} catch (Exception e) {
//print exp
e.printStackTrace();
}
}
private void findviews() {
webview_ = (WebView) findViewById(R.id.wbview);
}
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(dialog == null){
dialog = ProgressDialog.show(WebviewActivity.this, null, "Loading...");
dialog.setCancelable(true);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(dialog.isShowing())
dialog.dismiss();
}
}
}
Xml code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_login_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="ltr"
tools:context=".activity.WebviewActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:supportsRtl="false"
app:popupTheme="#style/AppTheme.PopupOverlay">
<include layout="#layout/header_settinglayout" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/wbview"
>
</WebView>
</RelativeLayout>
Now you can load any url or html from whole app
From Activity :
if (CommonUtils.isConnectingToInternet(HelpActivity.this)) {
Intent i = new Intent(HelpActivity.this,WebviewActivity.class);
i.putExtra("title",getResources().getString(R.string.faqs));
i.putExtra("Url", "https://stackoverflow.com/questions/48594734/how-to-pass-string-url-from-main-activity-to-next-activity-and-load-url-in-webvi");
startActivity(i);
}
else {
//alert - no internet
}
From Fragment :
if (CommonUtils.isConnectingToInternet(getActivity())) {
Intent i = new Intent(getActivity(),WebviewActivity.class);
i.putExtra("title",getResources().getString(R.string.faqs));
i.putExtra("Url", "https://stackoverflow.com/questions/48594734/how-to-pass-string-url-from-main-activity-to-next-activity-and-load-url-in-webvi");
getActivity().startActivity(i);
}
else {
//alert - no internet
}
Webview load url
i.putExtra("Url", "https://stackoverflow.com/questions/48594734/how-to-pass-string-url-from-main-activity-to-next-activity-and-load-url-in-webvi");
Webview load html from assets directory
i.putExtra("Url", "file:///android_asset/diploma.html");
If you're using activities, pass the url as a string and get it in the next activity.Like below code
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("url","somepage.com");
startActivity(intent);
In the webView,get it like this
String url = getIntent().getStringExtras("url");
webView.load("url");

How to create Settings with toolbar in android

I have a Settings Preference screen.It has a ListPreference and a CheckBoxPreference. I want to change my app's date format when I choose an item of ListPreference. Also, by the CheckBoxPreference I want to show/hide notification on the status bar. Can anyone tell what I have to do to achieve that.
Also, how can I add a toolbar to the preference screen? I am stuck here. Please help. Thanks in advance.
I am stuck here. Please help.
Thanks in advance.
MainActivity.java
public void setCurrentDateOnView() {
String dateFormat = "dd - MM - yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
tv_Current_weekday.setText(short_weekday);
til_Current_Date.setError(null);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent_settings = new Intent(this, SettingsActivity.class);
startActivity(intent_settings);
Toast.makeText(this, "You have clicked on settings action menu.", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
NotificationManager mNotifyManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = sharedPreferences.getBoolean("pref_cb_notification", true);
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notifyEnabled) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean isChecked = sharedPreferences.getBoolean("pref_cb_notification", false);
if (isChecked) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
//Method to show notification
public void showNotification() {
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(SettingsActivity.this)
.setSmallIcon(R.drawable.ic_notifications_white_24dp)
.setContentTitle("My Application")
.setSubText("Tap to start");
Intent resultIntent = new Intent(SettingsActivity.this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(SettingsActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//System.currentTimeMillis();
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotifyManager.notify(1, notification);
}
//Method to hide notification
public void hideNotification() {
mNotifyManager.cancel(1);
}
}
Settings image
for adding toolbar you just need to use the coordinator layout in the layout file of your activity. Preference activity has simple layout like others and you just inflate preference fragments inside a container.
add appcompact design support library to your build.gradle
compile 'com.android.support:appcompat-v7:21.0.3'
Add toolbar.xml to your layout folder
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:elevation="4dp"
>
</android.support.v7.widget.Toolbar>
Then include toolbar in your activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<TextView
android:layout_below="#+id/tool_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/TextDimTop"
android:text="#string/hello_world" />
</RelativeLayout>
then you need to set up it in your activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
and then by using onCreateOptionsMenu you can add settings menu on it.

Can PlaceAutocompleteFragment (overlay mode) be called from inside the Fragment class

I'm working on my project to create an activity(extends AppCompatActivity) with navigation drawer for switching between multiple Fragments and one of them is a MapFragment(extends Fragment) with a MapView implementation. I would like to call the AutoComplete Widget, provided by Google, inside MapFragment class.
Here is my code inside class MapFragment
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build();
autocompleteFragment.setFilter(typeFilter);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
String placeDetailsStr = place.getName() + "\n"
+ place.getId() + "\n"
+ place.getLatLng().toString() + "\n"
+ place.getAddress() + "\n"
+ place.getAttributions();
Log.i("OnPlaceSelected", placeDetailsStr);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("OnPlaceSelected", "An error occurred: " + status);
}
});
syntax error was at
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
said that
Inconvertible type; cannot cast 'android.support.v4.app.Fragment' to 'com.google.android.gms.location.places.ui.PlaceAutocompleteFragment'
But when I put this set of code inside MainActivity, it works just fine. So I'm wondering if there's any way to call AutoComplete Widget inside Fragment it's just can't.
Any Answer will be appreciated. :)
Use getActivity()
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
You have to use something like this if you're trying to find the fragment from within a fragment:
placeAutocompleteFragment = (PlaceAutocompleteFragment)getChildFragmentManager().findFragmentById(R.id.fragmentPlaces);
You might run into issues with onPlaceSelected not being called, this is because your owning activity has to forward the result into the fragment.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mapFragment.onActivityResult(requestCode, resultCode, data);
}
and mapFragment has to forward the result into the places fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
placeAutocompleteFragment.onActivityResult(requestCode, resultCode, data);
}
Even with this, I've had issues with onPlacesSelected not being called. Its usually best to just not nest the map and places fragments, but just have them separate in the owning activity.
I have been searching around on the interwebz too and couldn't find a solution, until I realised I had the same exact problem with the MapFragment, so I applied that technique and it worked!
Fragment:
private SupportPlaceAutocompleteFragment autocompleteFragment;
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
...
autocompleteFragment = (SupportPlaceAutocompleteFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
if(autocompleteFragment==null){
autocompleteFragment = (SupportPlaceAutocompleteFragment) SupportPlaceAutocompleteFragment.instantiate(context, "com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
});
fm.beginTransaction().replace(R.id.autocomplete_fragment, autocompleteFragment).commit();
}
...
Note: I am using the support fragment (android.support.v4.app.Fragment), that's why I use SupportPlaceAutocompleteFragment
XML:
<RelativeLayout
android:id="#+id/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
You shoud use SupportPlaceAutocompleteFragment instead of PlaceAutocompleteFragment, it's replaced when using Fragment supportv4
SupportPlaceAutocompleteFragment autocompleteFragment
= (SupportPlaceAutocompleteFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
I had the very same question, and thanks to #Kalpesh idea, it works fine, and no problem of eventListenner, here's my code if it can help someone.
I have a tablayout with a viewpager and 3 fragment we can swipe right or left.
googlePLacesLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorFragment_bg">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp">
<fragment
android:id="#+id/autocomplete_fragment"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/largeTexxt"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
MyFragmentClass.java
package com.raccoon.trash.aregood.TabFragments;
public class MyFragmentClass extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(
R.layout.googlePLacesLayout, container, false);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setHint("Let's find some restaurants");
final TextView textView = (TextView) mRelativeLayout.findViewById(R.id.largeTexxt);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
textView.setText("Place: " + place.getName()+ place.getId()+
place.getAddress()+ place.getPhoneNumber()+ place.getWebsiteUri());
System.out.println("Place: " + place.getName()+ place.getId()+
place.getAddress()+ place.getPhoneNumber()+ place.getWebsiteUri());
}
#Override
public void onError(Status status) {
System.out.println("An error occurred: " + status);
}
});
return mRelativeLayout;
}
}

How can I transfer some value between activities in Android

I tried to send a int value from current activity to the new one, here is the parts in current activity.
dialog.setPositiveButton("4 players", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Start a new game!", Toast.LENGTH_SHORT).show();
// need send extra value to PlayerBoardActivity to decide how many buttons I should have
Intent intent = new Intent(MainActivity.this,
PlayBoardActivity.class);
intent.putExtra(PLAYER_NO, 4);
startActivity(intent);
}
});
dialog.setNegativeButton("2 players", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Start a new game!", Toast.LENGTH_SHORT).show();
// need send extra value to PlayerBoardActivity to decide how many buttons I should have
Intent intent = new Intent(MainActivity.this,
PlayBoardActivity.class);
intent.putExtra(PLAYER_NO, 2);
startActivity(intent);
}
});
The problem is, I create 2 layout files for the new activity. When I press the negative button in the dialog for example, what I want is let the new activity (PlayerBoardActivity in my case) load the layout file corresponding to the value I have sent by "intent.putExtra(PLAYER_NO, 2); "
The code in the new activity is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PLAYER_NO = "the number of players";
Bundle b = getIntent().getExtras();
int a = b.getInt(PLAYER_NO);
if (b != null) {
if (a == 2) {
setContentView(R.layout.two_player);
}
if(a == 4){
setContentView(R.layout.four_player);
}
}
}
I do want to know whether I can load different layout file in this way? Or is there any better solution for my problem.
Thank you all in advance.
If you use
intent.putExtra(PLAYER_NO, 2);
you should call following code to get values (without using "Bundle"):
getIntent().getIntExtra(PLAYER_NO, -1)
In your code, the problem is in your second activity to which you are calling.
You are trying to fetching the values from intent in incorrect way.
Try this in your second activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int b = intent.getIntExtra(PLAYER_NO, 0);
if (b == 2) {
setContentView(R.layout.two_player);
}
if(b == 4){
setContentView(R.layout.four_player);
}
}
Ji Yang... it is fine..if both the layout content the same kind of structure and dealing with different resources of any layout in the same activity is not so difficult..
suppose layout two_player.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#777370"
android:textSize="16sp"
android:paddingLeft="5dp"
android:text="Dummy Text"
android:visibility="gone"
android:textStyle="bold"/>
</RelativeLayout>
and layout four_player.xml is something like that
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:orientation="vertical">
<ImageView
android:id="#+id/iv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/order_content"
android:src="#drawable/order_next_sap"
android:layout_alignLeft="#+id/order_content"/>
<ImageView
android:id="#+id/iv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/order_content"
android:src="#drawable/order_next_sap"
android:layout_alignLeft="#+id/order_content"/>
</RelativeLayout>
means ...both layout of different defination.. than its difficult to use resource of both layout in same activity and its not good too..
The better solution in this case is to create fragment of both layout
class TwoPlayerFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.two_player, container, false);
return v;
}
}
class FourPlayerFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.four_player, container, false);
return v;
}
}
and use the fragment according to the intent value pass from dialog..
try this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PLAYER_NO = "the number of players";
Intent b = getIntent();
int a = b.getExtras().getInt(PLAYER_NO);
if (b != null) {
if (a == 2) {
setContentView(R.layout.two_player);
}
if(a == 4){
setContentView(R.layout.four_player);
}
}
}
You are doing very wrong way. You should use fragment for this. You should create two fragment in which you can inflate different different layout. But this is your call.
From PlayBoardActivity you are sending data like :
intent.putExtra(PLAYER_NO, 4);
So in new activity you need to retreive like:
int b=getIntent.getIntExtra(PLAYER_NO,defaulValue);
you are trying to get value from bundle which is wrong.

Categories