Cannot see Mapbox map on the screen - java

I'm trying to implement Mapbox map to my project where i use Fragments.
Here is MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MainMenu()).commit();
}
}
}
activity_main.xml:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
MainMenu.java (Fragment where i'm trying to show the map):
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
public class MainMenu extends Fragment {
private MapView mapView;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_menu, container, false);
Mapbox.getInstance(getContext().getApplicationContext(), getString(R.string.access_token));
mapView = rootView.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
return rootView;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
And my main_menu.xml file:
(I'm using RelativeLayout and CoordinatorLayout here. I won't past all the code, only beginning)
<?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:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="37.7749"
mapbox:mapbox_cameraTargetLng="-122.4194"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12"
/>
I only have one error in Logcat, but I don't think that's the source of the problem (sorry if I'm wrong). I'll attach screenshot of the error and emulator below
Error
Screen of the emulator
The app doesn't crash, I just can't see the map.
Thank you for your answers!

Related

Mapbox SDK in Android Fragment

I want to show mapbox mapview in fragment but i cant do that. I looked lots of problems and solutions however i cant solve my issue. App is crashing always. BottomNavigation class is main class, MapFragment is fragment class which i want to see map. Also i attached Xml codes. Thank you!
BottomNavigation.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class BottomNavigation extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
loadFragment(new MapFragment());
}
private boolean loadFragment(Fragment fragment){
if (fragment != null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()){
case R.id.navigation_map:
fragment = new MapFragment();
break;
case R.id.navigation_search:
fragment = new SearchFragment();
break;
case R.id.navigation_event:
fragment = new EventsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
}
MapFragment.java
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
public class MapFragment extends Fragment {
private MapView mapView;
public MapFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container,false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(new Style.Builder().fromUrl("mapbox://styles/orucbe/cjqnneisv0gns2ro1fy83ucgl"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(41.885, -87.679)) // set the camera's center position
.zoom(12) // set the camera's zoom level
.tilt(20) // set the camera's tilt
.build();
// Move the camera to that position
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
activity_bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BottomNavigation">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="56dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
>
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</com.mapbox.mapboxsdk.maps.MapView>
</android.support.constraint.ConstraintLayout>
Problem is that there is no setted access token. Access token should be set before inflating. That's all.
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
public class MapFragment extends Fragment {
private MapView mapView;
public MapFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Mapbox.getInstance(getContext().getApplicationContext(),"access_token");
View view = inflater.inflate(R.layout.fragment_map,container,false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(new Style.Builder().fromUrl("style_url"));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
}
}

Java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getWidth()' on a null object reference

I have developed an app which contains fragment View but I was exposed to a problem, the app is crashing. Can you help me in solving the problem?
Error I am getting is:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getWidth()' on a null object reference
at com.abdeljalilkchih.palestine.Fragment.FragmentOne$1.run(FragmentOne.java:59)
04-28 13:45:51.898 23913-24013/com.abdeljalilkchih.palestine E/chromium: [ERROR:gl_context_virtual.cc(39)] Trying to make virtual context current without decoder.
Can you please tell me how can I solve this error?
FragmentOne.Java
package com.abdeljalilkchih.palestine.Fragment;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.abdeljalilkchih.palestine.R;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.AdView;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
public class FragmentOne extends Fragment implements ScreenShotable {
private AdView MyAdView2;
private View Fragmentone_view;
private Bitmap bitmap;
public static FragmentOne newInstance() {
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
MobileAds.initialize(this.getContext(), "ca-app-pub-9961705383410701~3103812044");
MyAdView2 = rootView.findViewById(R.id.MyAdView2);
AdRequest adRequest = new AdRequest.Builder().build();
MyAdView2.loadAd(adRequest);
WebView webView;
webView=(WebView) rootView.findViewById(R.id.Web_View2);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
//ربط الفيو بالصفحات
webView.loadUrl("file:///android_asset/webfiles/index.html");
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.Fragmentone_view = view.findViewById(R.id.container);
}
#Override
public void takeScreenShot() {
Thread threads = new Thread() {
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(Fragmentone_view.getWidth(),
Fragmentone_view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Fragmentone_view.draw(canvas);
FragmentOne.this.bitmap = bitmap;
}
};
threads.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<io.codetail.widget.RevealFrameLayout
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">
<FrameLayout
android:id="#+id/Container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/Main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<!--
your code here
-->
<com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/MyAdView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0"
ads:adSize="BANNER"
ads:adUnitId="#string/ad_unit_banner2"></com.google.android.gms.ads.AdView>
<WebView
android:id="#+id/Web_View2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0" />
</LinearLayout>
</FrameLayout>
</io.codetail.widget.RevealFrameLayout>
Looks like you have defined the variable Fragmentone_view locally to method onViewCreated()
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.Fragmentone_view = view.findViewById(R.id.container);
}
To utilize the variable in another method, you need to define it globally.
private View Fragmentone_view;
didnt initialize properly thats why you getting null pointer exception
try below code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one,container,false);
this.Fragmentone_view = rootView
MobileAds.initialize(this.getContext(), "ca-app-pub9961705383410701~3103812044");
MyAdView2 = rootView.findViewById(R.id.MyAdView2);
AdRequest adRequest = new AdRequest.Builder().build();
MyAdView2.loadAd(adRequest);
WebView webView;
webView=(WebView) rootView.findViewById(R.id.Web_View2);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
//ربط الفيو بالصفحات
webView.loadUrl("file:///android_asset/webfiles/index.html");
return rootView;
}
Try this \
replace :
public class FragmentOne extends Fragment implements ScreenShotable {
...
//replace this line with >> private FrameLayout Fragmentone_view;
private View Fragmentone_view;
...
}
with :
private FrameLayout Fragmentone_view;

How to display two fragments at the same time using TabLayout?

I use Android Tab Example with two tabs, view pager and fragments (structure on the image):
For get fragments i use the solution from this post.
When my device is rotation i want to display two fragments at the same time.
I the stackoverflow.com/questions/17970021 a similar problem, but I don't know how to apply the solution to my task, because i have TabLayout.
If you know idea, can you help me?
In activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
>
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
</FrameLayout>
In MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.annotation.NonNull;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(0);
}
public void replaceFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabOneFragment();
break;
case 1:
fragment = new TabTwoFragment();
break;
default:
break;
}
if (null != fragment) {
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
in TabOneFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabOneFragment extends Fragment {
private View inflatedView = null;
public TabOneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_one, container, false);
return this.inflatedView;
}
}
in TabTwoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabTwoFragment extends Fragment {
private View inflatedView = null;
public TabTwoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_two, container, false);
return this.inflatedView;
}
}

Fragment in Android unnecessarily repeating more than once

Iam trying to keep a simple fragment with only one button.But it is coming 2 times like this
I had a linear layout and another nested linear layout in it.These are all present in activity_welcome.xml whose content is as follows :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#99cc00"
android:orientation="vertical"
tools:context="com.acs.AfterLogin.WelcomeActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/replacable_container"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Iam trying to replace the replacable_container(Linear Layout) with the fragment whose java class is this :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.acs.AfterLogin.WelcomeActivity;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeFragment1 extends Fragment{
View v;
CardView cardView1,cardView2,cardView3;
CircleImageView userIcon;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return inflater.inflate(R.layout.welcome_fragment_1,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The xml content of fragment is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e0ebe5"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
</LinearLayout>
The operations like fragment transcation and all are contained in the mainactivity whose java code is this :
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.acs.AfterLogin.WelcomeFragments.WelcomeFragment1;
import com.acs.R;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class WelcomeActivity extends AppCompatActivity {
FragmentTransaction transaction;
WelcomeFragment1 frag1;
FragmentManager manager;
String imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
(new FragTask()).execute();
}
private class FragTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
transaction = manager.beginTransaction();
frag1 = new WelcomeFragment1();
transaction.replace(R.id.replacable_container, frag1, "welcome_1");
transaction.commit();
return null;
}
}
}
Thanks a lot in advance :)
Try to change this line
v=inflater.inflate(R.layout.welcome_fragment_1,container);
to
v=inflater.inflate(R.layout.welcome_fragment_1,container, false);
And return the inflated view. The boolean value indicates that you don't want to attach your view to container. Check this. Fragment will attach it later by itself.
Please return inflated view instead of inflating again in return statement.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v=inflater.inflate(R.layout.welcome_fragment_1,container);
return v;
}

Implementing multiple fragments in a single activity Dynamically

I am working on fragments
Use case i am trying to implement::
I am using dynamic fragments
I am using three fragments in a single activity
my goal is to communicate between all the three fragments
I am using support package for fragments
Each fragment has a single widget
my_fragment1 has edittext
my_fragment2 has button
my_fragment3 has TextView
On click of button the text from the edittext must be displayed in the textview
What i have tried so far i have constructed most of the scenario below
Top_Fragment.java
public class Top_Fragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
}
Middle_Fragment.java
package com.example.deleteme;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class Middle_Fragment extends Fragment{
View view;
Button btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
btn=(Button) view.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Bottom_Fragment.java
public class Bottom_Fragment extends Fragment{
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
display_text=(TextView) view.findViewById(R.id.editText1);
return view;
}
public void setName(String Name){
display_text.setText("Result::" + Name);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg=new Top_Fragment();//create the fragment instance for the top fragment
Middle_Fragment frg1=new Middle_Fragment();//create the fragment instance for the middle fragment
Bottom_Fragment frg2=new Bottom_Fragment();//create the fragment instance for the bottom fragment
FragmentManager manager=getSupportFragmentManager();//create an instance of fragment manager
FragmentTransaction transaction=manager.beginTransaction();//create an instance of Fragment-transaction
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:background="#color/black">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#color/yellow">
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_2_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_1_ID"
android:background="#color/Orange" >
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_3_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_2_ID"
android:background="#color/purple" >
</FrameLayout>
</RelativeLayout>
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/green" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
</RelativeLayout>
my_fragment2.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:orientation="vertical"
android:background="#color/pink">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/black"
android:text="Button"
android:textColor="#FFFFFF" />
</RelativeLayout>
my_fragment3.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textColor="#000000"
android:textSize="30dp" />
</RelativeLayout>
My output is Like below ::
What I am having problem in achieving ::
I am not able to set the value obtained from edit text to
textview on click of the button
Any Ideas?
All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
http://developer.android.com/training/basics/fragments/communicating.html
test.java // in your case its MainActivity
public class test extends FragmentActivity implements textEntered {
String value;
boolean check = false;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg = new Top_Fragment();
frg2 = new BottomFragment();
FragmentManager manager = getSupportFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void setValue(String editextvalue) {
value = editextvalue;
if (frg2 != null) {
frg2.setName(value);
} else {
Toast.makeText(getApplicationContext(), "fragment 2 is null", 1000).show();
}
}
}
Top_Fragment.java
public class Top_Fragment extends Fragment {
textEntered mCallback;
Button b;
EditText ed;
public interface textEntered {
public void setValue(String editextvalue);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.my_fragment1, container, false);
ed = (EditText) view.findViewById(R.id.editText1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
b = (Button) getView().findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = ed.getText().toString();
mCallback.setValue(s);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (textEntered) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
" must implement textEntered");
}
}
}
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Button" />
</RelativeLayout>
Change to
display_text=(TextView) view.findViewById(R.id.textView1);
// id is textView 1 not editText1
in BottomFragment
snap
Communication between Fragments
There can be many scenarios where communication between fragment is required. You need to pass data between fragments on button click event. You may also use Android toolbar to switch between fragments. When you add buttons to your toolbar, you need to dynamically change screen using fragment.
Create an interface which will help us to communicate
Communicate.java
package com.example.amaanmemon.testfragment;
interface Communicate {
public void sendData();
}
TopFragment.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class TopFragment extends Fragment {
EditText firstName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
firstName = (EditText) getActivity().findViewById(R.id.editText1);
}
public String getData(){
return firstName.getText().toString();
}
}
MiddleFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MiddleFragment extends Fragment implements OnClickListener{
View view;
Button btn;
Communicate cm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
cm = (Communicate) getActivity();
btn = (Button) getActivity().findViewById(R.id.button1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
cm.sendData();
}
}
BottomFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class BottomFragment extends Fragment{
int count;
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
display_text = (TextView)getActivity().findViewById(R.id.textView1);
}
public void incrementData(String displayText){
display_text.setText(displayText);
}
}
MainActivity.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements Communicate{
TopFragment frg;
MiddleFragment frg1;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frg = new TopFragment();
frg1 = new MiddleFragment();
frg2 = new BottomFragment();
FragmentManager manager=getSupportFragmentManager();
transaction=manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void sendData() {
String temp = frg.getData();
frg2.incrementData(temp);
}
}
You can copy xml files from question.
you can watch the output below.
You can use the Activity for that.
in the onClick of the bottom fragment you can do something like
((MainActivity) getActivity()).doIt();
And make a method doIt in your MainActivity maybe something like this
public void doIt(){
frg2.setName(frg.getText())
}
and in the top fragment make a method getText that returns the text of the EditText

Categories

Resources