Opening a new fragment from within a ViewPager in Android Studio - android-studio

I have a question about opening a new fragment from within a ViewPager.
I setup FragmentA, FragmentB and FragmentC to be fragments of a viewpager and then proceeded to setup Fragment1 and Fragment2 as fragments of another viewpager which resides in FragmentB.
So Fragment1 and Fragment2 are in a viewpager which is essentially nested in another viewpager. I'm playing around with UI styles etc and this is is similar to that found in the Flickr app.
The problem I'm having is that once I get into the fragment1 or fragment2 (the nested fragment) I want to be able to click on something and enter a full screen fragment bypassing the toolbar I set up in FragmentB.
Below is the the code I have for FragmentB with the toolbar, tablayout and viewpager.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
public class FragmentB extends Fragment {
public FragmentB() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b,container,false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewPagerFragmentB);
ViewPagerAdapter adapter = new ViewPagerAdapter(((FragmentActivity) getContext()).getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"Fragment 1");
adapter.addFragment(new Fragment2(),"Fragment 2");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
// Inflate the layout for this fragment
return rootView;
}
}
Here is the code I've put together for fragment2 which contains a button I would like to take to take me to another fragment.
package com.app.fragmentdemo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_2,container,false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new FragmentFull();
FragmentManager fm = ((FragmentActivity) getContext()).getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragmentFullContainer,fragment);
ft.commit();
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Upon clicking the button the app crashes. I get the error:
No view found for id 0x7f080084 (com.app.fragmentdemo:id/fragmentFullContainer) for fragment FragmentFull
If I change the id of the fragment container to the id I assigned to the Fragment2 layout file, it works fine. However, this is still contained in the nested viewpager and doesn't allow me to enter a new layout.
I really appreciate your help.
Thanks.

In the following line
ft.add(R.id.fragmentFullContainer,fragment);
fragmentFullContainer should be a view in your R.layout.fragment_2
You are getting the crash because the OS cannot find fragmentFullContainer in R.layout.fragment_2
UPDATE
replace getSupportFragmentManager with getChildFragmentManager
If you want full screen , you have to manually hide Activity View elements.
Most probably, you have toolbar from activity, you can remove it like that.
((AppCompatActivity)getActivity()).getSupportActionBar().hide();

Related

How can i get the information from dialog android studio

I want to save some data from the dialog to use it in my app, but after enetering the data and going to the next step my app is crushing instantly (after pressing on Create).So i'm practicing with a textView(fragment layout). What should i do, bcs i didn't manage even with an method or class .Actually my purpose is to print in the text ,the input without crashing.
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class Passwords_Fragment extends Fragment {
FloatingActionButton floating_button;
AlertDialog dialog;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_passwords_, container, false);
floating_button=view.findViewById(R.id.floatingActionButton);
buildDialog();
floating_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.show();
}
});
return view;
}
private void buildDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name_of_platform=view.findViewById(R.id.platform_name);
EditText name_of_password=view.findViewById(R.id.password_name);
builder.setView(view)
.setTitle("Save a new password")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
addItem(name_of_platform.getText().toString()); // my app crashes here
}
});
dialog=builder.create();
}
private void addItem(String name){
View view = getLayoutInflater().inflate((R.layout.item),null);
TextView text= view.findViewById(R.id.textView2);
text.setText(name);
}
}```
My error at Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.passowrdgenerator.Passwords_Fragment.buildDialog(Passwords_Fragment.java:65)
at com.example.passowrdgenerator.Passwords_Fragment.onCreateView(Passwords_Fragment.java:32)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1808)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

new View.OnClickListener () greyed out ->" No Adapter Attached, skipping Layout" error message

I copied code for a recycler View from a Youtube tutorial but it won't work out for me. The new View.OnClickListener() is greyed out, with Android Studio suggesting to replace out with lambda. This is the only difference from my code to the one from the tutorial... The App runs through, but doesn't show the Layout, as I get the error message E/RecyclerView: No adapter attached; skipping layout.
what can I do to fix this?
This is the Adapter class:
package com.example.yourfoodweek;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class MealsRecViewAdapter extends RecyclerView.Adapter<MealsRecViewAdapter.ViewHolder>{
private static final String TAG = "MealsRecViewAdapter";
private ArrayList <Food> meals = new ArrayList<>();
private Context mContext;
public MealsRecViewAdapter(Context mContext) {
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_meals_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: Called");
holder.txtName.setText(meals.get(position).getName());
Glide.with(mContext)
.asBitmap()
.load(meals.get(position).getImageUrl())
.into(holder.imgFood);
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
Toast.makeText(mContext, meals.get(position).getName() + "Selected", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return meals.size();
}
public void setMeals(ArrayList<Food> meals) {
this.meals = meals;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private CardView parent;
private ImageView imgFood;
private TextView txtName;
public ViewHolder(#NonNull View itemView){
super(itemView);
parent = itemView.findViewById(R.id.parent);
txtName = itemView.findViewById(R.id.txtMealName);
imgFood = itemView.findViewById(R.id.imgFood);
}
}
}
both problems are totally different. first one was suggestion means if you don't want to apply you can skip it. but i will not suggest to do that.
for example:
(without Lambda)
myButton.setOnClickListener(new View.OnClickListerner(){
#Override
void onClick(View v) {
// do some stuff related to action
}
});
(with Lambda)
myButton.setOnClickListener(v -> {
// do some stuff related to action
})
for other question
no layout manager attached:
if your RecyclerView doesn't have any LayoutManager attached to it then it will skip cause it will not know how to arrange/show items.
Some LayoutManagers:
LinearLayoutManager
GridLayoutManager
StaggeredGridLayoutManager
if you want to create your own LayoutManager you can do it by just extending class LayoutManager
how to use it:
....
LinearLayoutManager layoutManager = new LinearLayoutManager();
layoutManager.setOrientation = LinearLayoutManager.HORIZONTAL
myRecyclerViewObj.setLayoutManager(layoutManager);
....
no adapter attached
similar to no layout manager this will be shown when no adapter attached to recycler view for this you have to use setAdapter method to set your adapater
for example:
....
MealsRecViewAdapter adapter = new MealsRecViewAdapter(this);
myRecyclerViewObj.setAdapter(adapter);
....

How to use 2 public classes, protected void on creat functions in the same fragments?

How to put more than one class,overview,void in MainActivity java of Android Studio? I need to have both the button and a code to make the map of google have some restricions in the same page. What names of the classes should be changed for it to work. The codes work when put independently but not together.How to make them work good together?
package com.example.maps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class FirstFragment extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFoodFragment();
}
});
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
}
public class MainACTIVITY extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mapAPI;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment =(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
#Override
public void onMapReady(GoogleMap googleMap){
mapAPI = googleMap ;
LatLng one = new LatLng(-21.754812, -48.219451);
LatLng two = new LatLng(-21.787443, -48.113332);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//add them to builder
builder.include(one);
builder.include(two);
LatLngBounds bounds = builder.build();
//get width and height to current display screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20);
mapAPI.setLatLngBoundsForCameraTarget(bounds);
mapAPI.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mapAPI.setMinZoomPreference(mapAPI.getCameraPosition().zoom);
LatLng Kampai = new LatLng(-21.780985, -48.186859);
mapAPI.addMarker(new MarkerOptions().position(Kampai).title("Kampai"));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Kampai));
}
}
Yes the can be in the same file but you have your mainACTIVITY inside your FirstFragment which cannot happen you need to remove the bottom most bracket and place it right above the start of your mainACTIVITY class, your FirstFragment's brackets need to close before you paste another class into the file.

Android Studio Tutorial (Error with referencing xml file)

Error when transitioning from first activity to next activity.
Cant seem to reference the R.layout.activity_display_message even though its under that folder,
when I type out the R.layout portion, it only autofills with activity_main.xml and cant reference the activity_display_message.xml file.
package com.example.friendmeter;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}
}

cannot find symbol variable Android Studio 0.8.1

I am new to android studio and I am trying to run this code.
My code:
package app.sunshine.android.example.com.sunshine;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
// Create some dummy data for the ListView. Here's a sample weekly
// Represented as "day, whether, high/low"
String[] forecastArray= {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
// Now that we have some dummy forecast data, create an ArrayAdapter.
// The ArrayAdapter will take data from a source ( Like our dummy forecast
// use to populate the ListView it's attached to
mforecastAdapter =
new ArrayAdapter<String>(
//The current context( this fragment's parent activity
getActivity(),
// ID of list item layout
R.layout.list_item_forecast,
// ID of the textview to populate
R.id.list_item_forecast_textview,
// Forecast data
weekForecast);
// Get a reference to the LIstView and attach this adpater to it
ListView listView = (ListView) rootView.findViewById(
R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
but I get the following error : cannot find symbol variable
I tried cleaning the project gradle and restarted android application .
but I am still encountering the issue
any help would be greatly appreciated :)
I am following this tutorial https://www.udacity.com/course/viewer#!/c-ud853/l-1395568821/e-1395668601/m-1395668603
You need to declare mForecastAdapter.
public static class PlaceholderFragment extends Fragment {
ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment() {
}
Since you have not done that yet it does not recognize the variable mForecastAdapter. Hope this helps.

Resources