Can't get Chronometer within fragment to start in Android Studio - java

I'm trying to make a stopwatch in one of my fragments but I'm am unable to get the stopwatch to start. Ideally it would start after pressing startButton but I can't even get the start() function to work at all. Right now this is what I have:
Fragment:
public class RunFragment extends Fragment implements View.OnClickListener {
private Chronometer sChronometer;
private long pauseOffset;
private boolean running;
Button startRun;
Button pauseRun;
Button stopRun;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public RunFragment() {
// Required empty public constructor
}
public void disable(View startButton){
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RunFragment.
*/
// TODO: Rename and change types and number of parameters
public static RunFragment newInstance(String param1, String param2) {
RunFragment fragment = new RunFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_run, container, false);
Button startRun = (Button) v.findViewById(R.id.startRun);
Button pauseRun = (Button) v.findViewById(R.id.pauseRun);
Button stopRun = (Button) v.findViewById(R.id.stopRun);
sChronometer = (Chronometer) v.findViewById(R.id.sChronometer);
startRun.setOnClickListener(this);
pauseRun.setOnClickListener(this);
stopRun.setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}
I'm not receiving any errors and the Toasts are showing up so I'm not sure what the problem is.
Here is the xml code:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".RunFragment">
<data>
<variable name="runLive" type="com.example.wam1.RunLive"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="450dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startRun"
android:onClick="startRun"
android:text="Start" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pauseRun"
android:onClick="pauseRun"
android:text="Pause" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/stopRun"
android:onClick="stopRun"
android:text="Stop" />
</LinearLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="100dp"
android:layout_marginHorizontal="10dp"
android:background="#f1f1f1"
>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heart Rate"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pace"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.distance}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginBottom="1dp"
android:layout_marginHorizontal="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.heartRate}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.pace}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recomendation"
android:textSize="32sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="250dp"/>
<Chronometer
android:id="#+id/sChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:format="00:00:00"
android:textSize="35sp">
</Chronometer>
</RelativeLayout>
</layout>
Any help or insight would be greatly appreciated!

since you are implementing an interface 'View.onClickListener', you should define it's method onClick and not your own. That difference can be made from you not overriding the onClick method. Just change your onClick method to
#Override
public void onClick(View view) {
//super.onClick(view);
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}

Related

Fragment Layout color changing issues

I have created three swiping splash screen layout fragments over an splash screen activity, and I want to change the color of the status bar for each fragment which matches the color of the fragment body.
My Code is
Fragment_a.xml
<?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=".FragmentA">
<ImageView
android:id="#+id/circle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_filled"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<ImageView
android:id="#+id/circle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle1"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<ImageView
android:id="#+id/circle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle2"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="Skip"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="120dp"
android:src="#drawable/ic_browsing"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:text="Move"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step by Step"
app:layout_constraintTop_toBottomOf="#id/textView2"
app:layout_constraintStart_toStartOf="#id/textView2"
android:layout_marginTop="6dp"
android:textSize="35sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a dummy text.\nMade for testing purpose!"
android:textSize="20sp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="#+id/textView3"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentA.java
package in.pratikchakraborty.liquidswipe;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class FragmentA extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentA() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentA.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
}
}
I am getting this error while building the project.
AndroidStudioProjects\LiquidSwipe\app\src\main\java\in\pratikchakraborty\liquidswipe\FragmentA.java:65: error: unreachable statement
if (Build.VERSION.SDK_INT >= 21) {
^
You are writing the code for change status color after the return statement so it is not reachable please try below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
return view;
}

Can the RecyclerView scroll with the rest of the fragment layouts?

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

Why when I want to access this fragment my application fails? Android Studio

I am developing an application in which I want to insert data in firebase, but when I want to open the fragment in the application I get an error.
I am using nav_graph for navigation between screens and I am also using movile_navigation. I don't know if that is information that could be important.
This is the java code, I don't know what causes the error:
```
public class Pantalla1Fragment extends Fragment{
TextView editTextName;
TextView editTextEdad;
TextView editTextApellidos;
TextView editTextGenero;
TextView editPadecimientos;
TextView editTextObservaciones;
TextView getEditTextTratamientos;
Button btnRegistar;
FirebaseAuth mAuth;
DatabaseReference mDatabase;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Pantalla1Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Pantalla1Fragment.
*/
// TODO: Rename and change types and number of parameters
public static Pantalla1Fragment newInstance(String param1, String param2) {
Pantalla1Fragment fragment = new Pantalla1Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/*#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pantalla1, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}
public void registerPerfil() {
String nombre=editTextName.getText().toString();
String apellidos=editTextApellidos.getText().toString();
String edad=editTextEdad.getText().toString();
String genero=editTextGenero.getText().toString();
String padecimientos=editPadecimientos.getText().toString();
String tratamiento=getEditTextTratamientos.getText().toString();
String observaciones=editTextObservaciones.getText().toString();
if(!TextUtils.isEmpty(nombre)){
String id=mDatabase.push().getKey();
Registro_Perfiles perfil = new Registro_Perfiles(nombre, apellidos, edad, genero, padecimientos, tratamiento, observaciones);
mDatabase.child("Users").child(id).setValue(perfil);
//Toast.makeText(this, "Datos introducidos", Toast.LENGTH_LONG).show();
}
}
}
And this part is the fragment view:
<?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=".Pantalla1Fragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:padding="15dp"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre" />
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="#string/editTextNombre" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Apellidos" />
<EditText
android:id="#+id/editTextApellidos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Apellidos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Edad" />
<EditText
android:id="#+id/editTextEdad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Edad" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Genero" />
<EditText
android:id="#+id/editTextGenero"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Genero" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Padesimientos" />
<EditText
android:id="#+id/editTextPadesimientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Padesimientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Tratamientos" />
<EditText
android:id="#+id/editTextTratamientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Tratamientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Observaciones" />
<EditText
android:id="#+id/editTextObservaciones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Observaciones" />
<Button
android:id="#+id/btnRegistar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="REGISTRAR NUEVO PERFIL" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error in the logcat
--------- beginning of crash
2020-08-26 12:13:05.893 17635-17635/com.example.thebestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thebestapp, PID: 17635
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.push()' on a null object reference
at com.example.thebestapp.Pantalla1Fragment.registerPerfil(Pantalla1Fragment.java:126)
at com.example.thebestapp.Pantalla1Fragment$1.onClick(Pantalla1Fragment.java:111)
at android.view.View.performClick(View.java:6297)
at android.view.View$PerformClick.run(View.java:24797)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
You should never be using getActivity().findViewById in a Fragment.
Instead, override onViewCreated() and use view.findViewById() - the view that is passed to that method is the view you inflated in onCreateView():
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}

Send data inside recyclerview with button in Fragment

I have 2 layouts where first layout for Fragment and second layout for RecyclerView. I have created CardView in RecyclerView, every CardView has some data. And I have created button below RecyclerView where the function of button for sending Data on CardView. My problem is I don't know how to send data when i click button in Fragment.
Fragment Layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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_daftar_alamat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.menu.menu_signin.menu.MenuAddressFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMoveTambahAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#null"
android:drawableStart="#drawable/ic_tambah_alamat"
android:drawablePadding="10dp"
android:text="Tambah Alamat"
android:textAllCaps="false"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="normal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Daftar Alamat"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tambah_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/gunakanAlamat"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="100dp"
android:background="#drawable/bg_button_red"
android:text="Gunakan Alamat"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="16sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
RecyclerView Layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="12dp"
android:orientation="vertical"
app:cardBackgroundColor="#color/colorWhite"
app:cardCornerRadius="4dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/radioButton">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/nameUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Muhammad Rafi Bahrur Rizki"
android:textColor="#color/colorBlack"
android:textSize="14sp"
android:textStyle="bold"
tools:ignore="UnusedAttribute" />
<TextView
android:id="#+id/addressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:maxLines="1"
android:text="(Alamat Kantor)"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/streetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Mangga Dua Square Lantai 1 Jakarta,"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp"
tools:ignore="UnusedAttribute" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/blokAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="Blok C no. 148 - 150"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/cityAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/countryAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/phoneUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="0812951825"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<Button
android:id="#+id/buttonEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:drawableStart="#drawable/ic_edit"
android:text="Edit"
android:textAllCaps="false"
android:textSize="12sp" />
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#id/buttonEdit"
android:drawableStart="#drawable/ic_delete"
android:text="Hapus"
android:textAllCaps="false"
android:textSize="12sp" />
</RelativeLayout>
</TableLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When i select RadioButton, only data in RadioButton will be obtained. And when i click button, the data will be send to another activity.
Adapter RecyclerView :
public class AdapterGetAddress extends RecyclerView.Adapter<AdapterGetAddress.ViewHolder> {
Context context;
private List<ModelGetAddress> modelGetAddressList;
private BaseApiService baseApiService;
private int previousSelected = -1;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_address, parent, false);
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelGetAddress adapterAddress = modelGetAddressList.get(position);
}
#Override
public int getItemCount() {
return modelGetAddressList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nameUser, addressUser, streetName, blokAddressUser, cityAddressUser, countryUser, phoneUser;
private RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameUser = itemView.findViewById(R.id.nameUser);
addressUser = itemView.findViewById(R.id.addressUser);
streetName = itemView.findViewById(R.id.streetName);
countryUser = itemView.findViewById(R.id.countryAddressUser);
blokAddressUser = itemView.findViewById(R.id.blokAddressUser);
cityAddressUser = itemView.findViewById(R.id.cityAddressUser);
phoneUser = itemView.findViewById(R.id.phoneUser);
radioButton = itemView.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
}
});
}
}
}
Code in Fragment :
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here's were i'm stuck
}
});
return view;
}
}
You can solve this via an interface.
public interface ItemClickedCallback{
void onItemClicked(String nameUser //, the other data you wanna pass );
}
pass it through the constructor of your adapter.
Use this adapter constructor
ItemClickedCallback callback;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList, ItemClickedCallback callback) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
this.callback= callback;
}
When checking a radio button of any item; call the interface method, like this.
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
callback.onItemClicked(getNameUser //, the rest..);
}
});
Now, when you initialize the adapter in the fragment, create the new interface via the constructor and assign the data to class variables like this.
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
private String nameUser_;
// the rest...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
AdapterGetAddress adapter = new AdapterGetAddress(getActivity, list, new ItemClickedCallback() {
#Override
public void onItemClicked(String userName //, the rest..) {
// assign to the class variable like this
nameUser_ = userName;
// the rest..
}
}););
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the data as you want..
}
});
return view;
}
}

Fragment not inflating and app closing

I have implemented Android Tab Layout. I have created five fragments named, one_fragment, two fragment....five fragment.
My XML name five_fragment.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="com.unss.pa.bdapp.one_fragment"
android:background="#FFFFFF">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:paddingRight="15dp"
android:paddingLeft="15dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Give your feedback to improve this app better."
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#800000"
android:typeface="serif"
android:layout_marginTop="20dp"
android:id="#+id/textView05"
android:textAlignment="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your name"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:textAlignment="center"
android:id="#+id/textView01" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:background="#drawable/edit_text"
android:id="#+id/editText01"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\nYour email*"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:textAlignment="center"
android:id="#+id/textView02" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:background="#drawable/edit_text"
android:id="#+id/editText2" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\nYour feedback"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:id="#+id/textView03"
android:textAlignment="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="175dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/editText3"
android:layout_weight="0.23"
android:background="#drawable/edit_text"/>
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/send"
android:id="#+id/button01f"
android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\n"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="2dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:id="#+id/textView07" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Adapter in my Main Activity
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new ListContentFragment(), "Screen1");
adapter.addFragment(new one_fragment(), "Screen2");
adapter.addFragment(new CardContentFragment(), "Screen3");
adapter.addFragment(new two_fragment(), "Screen4");
adapter.addFragment(new CardContentFragment(), "Screen5");
adapter.addFragment(new TileContentFragment(), "Screen6");
adapter.addFragment(new three_fragment(), "Screen7");
adapter.addFragment(new five_fragment(), "Feedback");
viewPager.setAdapter(adapter);
}
My five_fragment.java
public class five_feedback extends Fragment implements View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public Button btn;
public EditText t1;
public EditText t2;
public EditText t3;
public five_feedback() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
btn = (Button) getView().findViewById(R.id.button01f);
t1 = (EditText) getView().findViewById(R.id.editText01) ;
t2 = (EditText) getView().findViewById(R.id.editText2) ;
t3 = (EditText) getView().findViewById(R.id.editText3) ;
btn.setOnClickListener(this);
return inflater.inflate(R.layout.five_fragment, container, false);
}
#Override
public void onClick(View v) {
if( t2.getText().toString().trim().equals("")){
Snackbar.make(v, "Email Required",
Snackbar.LENGTH_LONG).show();
} else {
String to = "pbharadwaj777#gmail.com";
String message = t2.getText().toString();
String subject = "Feedback";
Intent mEmail = new Intent(Intent.ACTION_SEND);
mEmail.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
mEmail.putExtra(Intent.EXTRA_SUBJECT, subject);
mEmail.putExtra(Intent.EXTRA_TEXT, message);
// prompts to choose email client
mEmail.setType("message/rfc822");
startActivity(Intent.createChooser(mEmail, "Choose an email client to send your feedback!"));
}
}
}
When I install the open, I am able to open the app. I can slide from screen 1 to screen 7. However when I open Feedback, the app crashes. What is the issue?
The issue is you are trying to access the view before you actually inflated it. Change your onCreateView to the following or alternatively you could move your findViewById and setOnClickListener code to the onViewCreated function of the Fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.five_fragment, container, false);
btn = (Button) view.findViewById(R.id.button01f);
t1 = (EditText) view.findViewById(R.id.editText01) ;
t2 = (EditText) view.findViewById(R.id.editText2) ;
t3 = (EditText) view.findViewById(R.id.editText3) ;
btn.setOnClickListener(this);
return view;
}

Categories