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;
}
}
Related
I'm trying to update a TextView object's text by calling the setText() method. I provide a string value directly to it, but I can't get it to update on the UI of the app running on the Emulator.
This is taking place on a fragment (one of the fragments automatically generated when a project with a simple activity is created on Android Studio)
A couple points about my situation thus far:
I tried calling the setText() method with the runOnUiThread "pattern" to no avail.
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
textView.setText("Service online");
}
});
I checked property mText of the TextView instance. It IS UPDATED. It just doesn't update on the UI :/
In short, no matter what I try to do, the UI element sticks to whatever string value is set on the XML Fragment file (or no value, if I delete the android:text attribute). Other posts on Stack Overflow similar to this issue did not help me either. Any idea what it could be?
Also, I'm posting the entire fragment related java code:
public class FirstFragment extends Fragment
{
public Gson serializer;
public TextView textView;
private NetworkManager networkManager;
private boolean serviceIsBound;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
textView = (TextView) view.findViewById(R.id.main_window);
textView.setText(R.string.app_name);
return inflater.inflate(R.layout.fragment_first, container, false);
}
#Override
public void onStart() {
super.onStart();
Intent bindIntent = new Intent(getActivity(), NetworkManager.class);
getActivity().bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
public void onStop()
{
super.onStop();
getActivity().unbindService(serviceConnection);
serviceIsBound = false;
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("DEV UPDATE", "Starting Request ");
if (serviceIsBound)
{
GetAPIStatusResult result = networkManager.GetAPIStatus();
if (result.GetStatus())
{
Log.v("REQUEST RESULT", "API is Fine");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("Service online");
}
});
}
else
{
Log.v("REQUEST RESULT", "API is Down or a problem occurred");
textView.setText("Service down");
}
}
}
});
}
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName className, IBinder service)
{
NetworkManager.NetworkManagerServiceBinder binder = (NetworkManager.NetworkManagerServiceBinder) service;
networkManager = binder.GetService();
serviceIsBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg)
{
serviceIsBound = false;
}
};
}
The associated XML for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".FirstFragment">
<TextView
android:id="#+id/main_window"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Here will appear API status"
app:layout_constraintBottom_toTopOf="#id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="SendRequest"
android:text="#string/SendRequest"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/main_window" />
</androidx.constraintlayout.widget.ConstraintLayout>
As user Cheticamp commented, I had an issue on my onCreateView() method, where I was calling the infalter.inflate() method twice, and not returning my view object.
I replaced the second inflate() method call with a return of my view object and it immediately worked! My UI was now being updated as expected!
You're trying to reference a view that belongs to the activity. If you want to update something in the activity you need to look at other methods rather than trying to directly reference the views.
A good place to start would be an interface you pass to the fragment that is created by the activity. Call the interface method from the fragment when you want to set the next. Then let the activity handle the updating. This is cleaner too as each view is responsible for its own elements only.
You also don't need to use runOnUIThread as onViewCreated isn't an ansychronos function you're already on the UI thread anyway.
Hopefully that helps.
I am trying to implement an external colorwheel and the fragment where it should appear in keeps crashing my app. I think I understood why this happen´s, but after around 6 hours of trying to fix it I´m about to give up. I know this was asked befor, but I could not derive a fix for my specific problem. Here ist my code:
private ColorchoiceViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(ColorchoiceViewModel.class);
View root = inflater.inflate(R.layout.fragment_colorchoice, container, false);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
ColorPickerView colorPickerView = (ColorPickerView) root.findViewById(R.id.colorPickerView);
colorPickerView.setColorListener (new ColorListener() {
#Override
public void onColorSelected(ColorEnvelope colorEnvelope) {
Toast.makeText(getActivity(), "Color:" + colorEnvelope.getColorRGB(), Toast.LENGTH_SHORT).show();
}
});
return root;
}
}
And this is the Logcat-Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.skydoves.colorpickerpreference.ColorPickerView.setColorListener(com.skydoves.colorpickerpreference.ColorListener)' on a null object reference
at com.lsh.homeauto.ui.colorchoice.ColorchoiceFragment.onCreateView(ColorchoiceFragment.java:43)
It would be really great if someone could help me fix this. Thanks in advance^^
Edit: Here´s my XML, as requested:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="horizontal"
android:gravity="center">
<com.skydoves.colorpickerpreference.ColorPickerView
android:id="#+id/colorPickerView"
android:layout_width="300dp"
android:layout_height="300dp"
app:palette="#drawable/palette"
app:selector="#drawable/wheel" />
</LinearLayout>
This might be because you are trying to use setColorListener on a view which is not even created. Note that you are using this method in onCreateView method. I suggest you to move those lines in onViewCreated method.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ColorPickerView colorPickerView = (ColorPickerView) view.findViewById(R.id.colorPickerView);
colorPickerView.setColorListener (new ColorListener() {
#Override
public void onColorSelected(ColorEnvelope colorEnvelope) {
Toast.makeText(getActivity(), "Color:" + colorEnvelope.getColorRGB(), Toast.LENGTH_SHORT).show();
}
});
}
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
I'm trying to use Google's Place Autocomplete (https://developers.google.com/places/android-api/autocomplete) to implement into a fragment in my app. But I got this error when navigating from this fragment to other fragment and then coming back into this fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #30: Duplicate id 0x7f0f010f, tag null, or parent id 0x7f0f00c0 with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2148)
This is the java code
private PlaceAutocompleteFragment mSearchPAF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.some_layout, container, false);
mSearchLocationPAF = (PlaceAutocompleteFragment) parentActivity.getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
}
This is the XML file
<RelativeLayout
android:id="#+id/someRelativeLayout"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="30dp"
android:background="#drawable/some_drawable">
<fragment
android:id="#+id/place_autocomplete_fragment"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
I also have another map fragment in this same java and xml file but I managed to solve it by following the answers in this post (Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment) but I can't find any solution for this Place Autocomplete fragment
I have solved this problem myself by following one of the answers here
Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
private PlaceAutocompleteFragment mSearchPAF;
#Override
public void onDestroyView() {
super.onDestroyView();
PlaceAutocompleteFragment f = (PlaceAutocompleteFragment) getFragmentManager()
.findFragmentById(R.id.place_autocomplete_fragment);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
I am currently working on my Project and implemented my main activity with multiple fragments(Still a novice in Android Studio). In my Navigation fragment, I used an googleAutocomplete provided by Google.
This code here is implemented inside the OnCreateView().
mPlace_Starting = (PlaceAutocompleteFragment)
this.getChildFragmentManager().findFragmentById(R.id.place_starting);
AutocompleteFilter countryFilter = new AutocompleteFilter.Builder()
.setTypeFilter(Place.TYPE_COUNTRY)
.setCountry("PH")
.build();
mPlace_Starting.setFilter(countryFilter);
mPlace_Starting.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place:
Log.i(TAG, "Starting Place:" + place.getName());
Toast.makeText(getActivity(), "Starting Place: " + place.getName(),
Toast.LENGTH_SHORT).show();
double mLongitude = place.getLatLng().longitude;
double mLatitude = place.getLatLng().latitude;
mStartingpoint = new Waypoint(mLongitude,mLatitude);
mStartpoint = new GeoCoordinate(mLongitude,mLatitude);
}
#Override
public void onError(Status status) {
//TODO: Handle the Error.
Log.i(TAG, "An error occured: " + status);
}
});
I inflated my PlaceAutocompleteFragment widget from Google by using getChildFragmentManager() since the widget is a fragment to be inflated inside another fragment(my Navigation Fragment).
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.