Why text in TextView doesn't update when button pressed on fragment? - android

I created my app with the Tabbed Activity. I created some fragments and simple UI. Swipe and tabs work. I want to make really simple calculator-like app but I can't even change the text.
I tried so many solutions found on the Internet, but nothing works. I'm a beginner in Android development and now my code is a real mess.
What change to make it work? I just want to change some TextView's texts after clicking calculate button.
SingleLeg.java
package com.mycompany.hoptestcalculator;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
//import android.text.Editable;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
//import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SingleLeg.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SingleLeg#newInstance} factory method to
* create an instance of this fragment.
*/
public class SingleLeg 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;
private OnFragmentInteractionListener mListener;
/**
* 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 SingleLeg.
*/
// TODO: Rename and change types and number of parameters
public static SingleLeg newInstance(String param1, String param2) {
SingleLeg fragment = new SingleLeg();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public SingleLeg() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// ImageButton calculate = (ImageButton) getView().findViewById(R.id.calculate);
//
//
// calculate.setOnClickListener(this);
}
// #Override
// public void onClick(View v) {
// int id = v.getId();
//
//
// left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// right1 = (EditText) getView().findViewById(R.id.RightTr1);
// left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// right2 = (EditText) getView().findViewById(R.id.RightTr2);
//
// if(id == R.id.calculate && (!left1.getText().equals("")) ) {
// avgL.setText("2");
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_single_leg, container, false);
View v = inflater.inflate(R.layout.fragment_single_leg,
container, false);
Button calculate = (Button) getView().findViewById(R.id.calculate);
final TextView textView = (TextView) getView().findViewById(R.id.avgLeft);
calculate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
textView.setText("abc");
}
});
return v;
}
//
// EditText left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// EditText right1 = (EditText) getView().findViewById(R.id.RightTr1);
// EditText left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// EditText right2 = (EditText) getView().findViewById(R.id.RightTr2);
// TextView avgL; //= (TextView) getView().findViewById(R.id.avgLeft);
// TextView avgR = (TextView) getView().findViewById(R.id.avgRight);
// TextView leftOfRight = (TextView) getView().findViewById(R.id.Left_Right);
// TextView rightOfLeft = (TextView) getView().findViewById(R.id.Right_Left);
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
// //Declaration
// private class GenericTextWatcher implements TextWatcher{
//
// private View view;
// private GenericTextWatcher(View view) {
// this.view = view;
// }
//
// public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
// public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//
// public void afterTextChanged(Editable editable) {
// String text = editable.toString();
// switch(view.getId()){
// case R.id.LeftTr1:
// text.setName(text);
// break;
// case R.id.RightTr1:
// model.setEmail(text);
// break;
// case R.id.LeftTr2:
// model.setPhone(text);
// break;
// }
// }
// }
// left1.addTextChangedListener(new TextWatcher() {
// #Override
// public void afterTextChanged(Editable arg0) {
// enableSubmitIfReady();
// }
//
// #Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// }
//
// #Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// }
// });
public void updateTextView(String toThis) {
TextView avg = (TextView) getView().findViewById(R.id.avgLeft);
avg.setText("567");
return;
}
}
fragment_single_leg.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.mycompany.hoptestcalculator.SingleLeg"
android:id="#+id/container"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<View
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_leg"
android:id="#+id/textView"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_leg"
android:id="#+id/textView2"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="10dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_1"
android:id="#+id/trial1" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr1"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_2"
android:id="#+id/trial2" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr2"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/average"
android:id="#+id/avg" />
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgLeft"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg"
android:text="rgrrgrgrg"
android:enabled="true"
android:editable="false" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgRight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_of_right"
android:id="#+id/lofR"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Left_Right"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="10dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_of_left"
android:id="#+id/RofL"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Right_Left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/calculate"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:textSize="35dp" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.hoptestcalculator" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Inside onCreateView() of the fragment :
Button calculate = (Button) convertView.findViewById(R.id.calculate);
final TextView textView = (TextView) convertView.findViewById(R.id.textViewId);
Then set a click listener on the button. :
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Here goes sample text");
}
});

Related

Interaction betweens Fragments and Activity

I'm having some difficulty facing the interactions between Fragments and between Fragments and my Activity, especially ClickListener-wise.
I'm developing a Calculator app composed of 2 fragments:
one Fragment contains all the Buttons (numbers and operators)
the other contains the 2 TextViews (operation and result)
The goal here is to make these two Fragments communicate between each other. I'm supposed to send characters and strings to a TextView until I click the on the "equals" button (on which I've put a ClickListener) but I can't seem to neither use the other buttons or send the information (it keeps warning me that the TextView is null, despite the interfaces).
This is the Fragment containing all the buttons and operators :
package fr.android.calculator.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import fr.android.calculator.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link LowerCalculatorFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link LowerCalculatorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class LowerCalculatorFragment 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;
private OnFragmentInteractionListener mListener;
public LowerCalculatorFragment() {
// 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 LowerCalculatorFragment.
*/
// TODO: Rename and change types and number of parameters
public static LowerCalculatorFragment newInstance(String param1, String param2) {
LowerCalculatorFragment fragment = new LowerCalculatorFragment();
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 view = inflater.inflate(R.layout.fragment_lower_calculator, container, false);
Button button = new Button(getContext());
LinearLayout buttonContainer = view.findViewById(R.id.resultButtonFragment);
button.setText("=");
button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
button.setId(R.id.buttonEqualsFragment);
buttonContainer.addView(button);
button.setOnClickListener(v -> onButtonPressed(v));
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(View view) {
if (mListener != null) {
mListener.lowerFragmentInteraction(view);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void lowerFragmentInteraction(View 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=".Activities.CalculatorSecondActivity"
android:id="#+id/frameLayout">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/numberOperators" android:baselineAligned="false">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/numbers" android:layout_weight="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent" android:id="#+id/SevenToPlus">
<Button
android:text="7"
android:layout_width="0dp"
android:layout_height="match_parent" android:id="#+id/button18" android:layout_weight="1"
android:onClick="onButtonClick"/>
<Button
android:text="8"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button19" android:layout_weight="1"
/>
<Button
android:text="9"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button20" android:layout_weight="1"
/>
<Button
android:text="+"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button21" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent" android:id="#+id/FourToMinus">
<Button
android:text="4"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button22" android:layout_weight="1"
/>
<Button
android:text="5"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button23" android:layout_weight="1"
/>
<Button
android:text="6"
android:layout_width="0dp"
android:layout_height="match_parent" android:id="#+id/button24" android:layout_weight="1"
/>
<Button
android:text="-"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button25" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_weight="1" android:id="#+id/OneToAsterix">
<Button
android:text="1"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button26" android:layout_weight="1"
/>
<Button
android:text="2"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button27" android:layout_weight="1"
/>
<Button
android:text="3"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button28" android:layout_weight="1"
/>
<Button
android:text="*"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button29" android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_weight="1">
<Button
android:text="0"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button32" android:layout_weight="1"
/>
<Button
android:text="/"
android:layout_width="0dp"
android:onClick="onButtonClick"
android:layout_height="match_parent" android:id="#+id/button33" android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/resultButtonFragment" android:layout_weight="4" android:orientation="vertical"
>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And this is the Fragment containing both TextViews :
package fr.android.calculator.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import fr.android.calculator.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link UpperCalculatorFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link UpperCalculatorFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class UpperCalculatorFragment 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;
private TextView resultDisplay;
private TextView operations;
private OnFragmentInteractionListener mListener;
public UpperCalculatorFragment() {
// 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 UpperCalculatorFragment.
*/
// TODO: Rename and change types and number of parameters
public static UpperCalculatorFragment newInstance(String param1, String param2) {
UpperCalculatorFragment fragment = new UpperCalculatorFragment();
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 view = inflater.inflate(R.layout.fragment_upper_calculator, container, false);
operations = view.findViewById(R.id.operationsFragment);
resultDisplay = view.findViewById(R.id.resultDisplayFragment);
return view;
}
public void setOperationsText(String operationsText){
operations.setText(operationsText);
}
public void setResultDisplayText(String resultDisplayText){
resultDisplay.setText(resultDisplayText);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String operations) {
if (mListener != null) {
mListener.operationsFragmentInteraction(operations);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void operationsFragmentInteraction(String operations);
void resultDisplayFragmentInteraction(String resultDisplay);
}
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".Fragments.UpperCalculatorFragment"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:background="#drawable/textview_border"
android:layout_marginRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/operationsFragment" android:layout_weight="2"/>
<TextView
android:background="#drawable/textview_border"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/resultDisplayFragment" android:layout_weight="3"/>
</LinearLayout>
</FrameLayout>
The activity itself that's in the middle is this one :
package fr.android.calculator.Activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import fr.android.calculator.Fragments.LowerCalculatorFragment;
import fr.android.calculator.Fragments.UpperCalculatorFragment;
import fr.android.calculator.R;
import org.mozilla.javascript.Context;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class CalculatorSecondActivity extends AppCompatActivity implements LowerCalculatorFragment.OnFragmentInteractionListener, UpperCalculatorFragment.OnFragmentInteractionListener {
private LowerCalculatorFragment lowerCalculatorFragment;
private UpperCalculatorFragment upperCalculatorFragment;
private Context rhino = Context.enter(); // runtime environment
private TextView operations;
private Button value;
private String result;
private TextView resultDisplay;
private Handler handler;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private String resp;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator_second);
lowerCalculatorFragment = LowerCalculatorFragment.newInstance("fragment", "you");
upperCalculatorFragment = UpperCalculatorFragment.newInstance("new fragment", "you 2");
getSupportFragmentManager().beginTransaction().add(R.id.lowerCalculator, lowerCalculatorFragment);
getSupportFragmentManager().beginTransaction().add(R.id.upperCalculator, upperCalculatorFragment);
getSupportFragmentManager().beginTransaction().commit();
}
#Override
public void operationsFragmentInteraction(String message) {
upperCalculatorFragment = (UpperCalculatorFragment) getSupportFragmentManager().findFragmentById(R.id.upperCalculator);
upperCalculatorFragment.setOperationsText(message);
}
#Override
public void resultDisplayFragmentInteraction(String message) {
upperCalculatorFragment = (UpperCalculatorFragment) getSupportFragmentManager().findFragmentById(R.id.upperCalculator);
upperCalculatorFragment.setResultDisplayText(message);
}
#Override
public void lowerFragmentInteraction(View view) {
value = view.findViewById(view.getId());
System.out.println("Value : " + value.getText());
if (value != view.findViewById(R.id.buttonEqualsFragment)) {
System.out.println("Value : " + value.getText());
operationsFragmentInteraction((String) value.getText());
} else {
// Avec Async
new AsyncTaskRunner().execute((String) operations.getText());
/* Avec Handler*/
//calculate((String) operations.getText());
}
}
public void onButtonClick(View view){
lowerCalculatorFragment.onButtonPressed(view);
}
public void calculate(String operations) {
Runnable runnable = () -> {
try {
socket = new Socket("10.0.2.2", 9876);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(operations);
result = dataInputStream.readUTF();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
handler.post(() -> resultDisplay.setText(result));
};
new Thread(runnable).start();
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
socket = new Socket("10.0.2.2", 9876);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(params[0]);
result = dataInputStream.readUTF();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(params[0]); // Calls onProgressUpdate()
resp = "Slept for " + 5 + " seconds";
return resp;
}
protected void onProgressUpdate(String... text) {
resultDisplayFragmentInteraction(result);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_calculator_second"
tools:context=".Activities.CalculatorSecondActivity">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="5">
<fragment android:layout_width="match_parent" android:layout_height="119dp"
android:name="fr.android.calculator.Fragments.UpperCalculatorFragment"
android:id="#+id/upperCalculator"
tools:layout="#layout/fragment_upper_calculator"
android:layout_weight="1"/>
<fragment android:name="fr.android.calculator.Fragments.LowerCalculatorFragment"
android:layout_width="409dp" android:layout_height="413dp"
android:id="#+id/lowerCalculator" tools:layout="#layout/fragment_lower_calculator"
android:layout_weight="4"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Do you guys have any ideas why?
Thanks in advance,
Fares.
EDIT : I've added methods to my Fragments after the wise advice from Edgar. If I understood correctly, the interfaces allow us to fetch the informations, that will be used in the methods of the fragments. However even though I've added ClickListeners to my buttons, only the buttonEqualsFragmentis "listened" to.
Even if I debug unless I click on the buttonEqualsFragment the other buttons aren't taken in account.
I created a method in the Activity to do that called the Fragment's implemented interface. (onButtonClick)
The problem is you are trying to display the info in the activity and not in the fragment. Try the following suggestions.
In yourUpperCalculatorFragment class place this at the top:
private Textview operations, results;
then in onCreateView() add the following to ensure the textviews are not null:
operations = view.findViewById(R.id.operationsFragment);
results = view.findViewById(R.id.resultDisplayFragment);
Next you have to define a public method still in this fragment (UpperCalculatorFragment) that will handle information from the Activity. I only show result you need another for operation as well
public void displayResult(String result){
results.setText(result);//this displays the result on textview
}
To display the result/operation you have to call that method from the CalculatorSecondActivity like so;
public void displayResultInFragment(String message) {
UpperCalculatorFragment upperFrag =
(UpperCalculatorFragment) getSupportFragmentManager()
.findFragmentById(R.id.upperCalculator);
//show the result here after all calculation
upperFrag.displayResult(message);
}
please refer to this android developers docs

How to create nested child on firebase android

[Solved. I solved it myself]
Tips: if you want to access a child in the firebase realtime database for collecting data and then by using that data u store or upload something at that child on the firebase realtime database again, then you can't access it. Either u have to create another child or u must not use that child. (I don't no the actual solution but It works for me)]
I want to create a child under the reference of the user phone number. That child will store one or more childs. These child will be called "serialNo" of the item. And under serialNo child, the item name and amount of piece will store. I want to create like this:
[N: B: I've created this on firebase directly, not by my application.]
But when I put my data object as .setValue(dtObject) the previous one will always be replaced.
"orderNo: 1" child was replaced by "orderNo: 2" child
I also use .updateChildren(dtMap) but everytime previous orderNo child was replaced.
My Code of confirm Fragment(from where I upload):
package com.binarysoftwareltd.airaid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class AddressFragment extends Fragment {
private int orderNo = 1;
private int orderSerial = 0;
private DatabaseReference dbReference, dbr;
private static final String STATE_USER = "user";
private String mUser;
private View oldView;
private TextView numWarning;
private EditText nameField, phoneField, areaField, addressField,
detailsField;
private CardView confirmCV;
private int len;
private String nameOfPerson, phoneNumber, areaName, addressOfOrder,
detailsOfOrder;
private int[] serialNos = new int[100];
private String[] names = new String[100];
private int[] pieces = new int[100];
private String imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new
instance
mUser = "NewUser";
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
if (oldView != null) {
return oldView;
}
View v = inflater.inflate(R.layout.fragment_address, container,
false);
initializeAll(v);
Bundle bundle = getArguments();
if (bundle != null) {
len = bundle.getInt("cValue");
imageUri = bundle.getString("imgUri");
serialNos = bundle.getIntArray("mSerialNos");
names = bundle.getStringArray("mNames");
pieces = bundle.getIntArray("mPieces");
}
confirmCV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
collectAllData();
if (!phoneNumber.equals("")) {
checkOrderSerial();
} else {
phoneField.requestFocus();
Toast.makeText(getContext(), orderSerial,
Toast.LENGTH_SHORT).show();
}
}
});
oldView = v;
return v;
}
private void checkOrderSerial() {
dbr=FirebaseDatabase.getInstance().getReference(phoneNumber).
child("currentOrderSerial");
dbr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Integer value = dataSnapshot.getValue(Integer.class);
if (value != null)
orderSerial = value;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showConfirmDialog();
}
private void showConfirmDialog() {
AlertDialog.Builder alb = new AlertDialog.Builder(getContext());
alb.setIcon(R.drawable.question);
alb.setTitle("Confirm");
alb.setMessage("Are you sure want to order?");
alb.setPositiveButton(R.string.exit_no, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alb.setNegativeButton(R.string.exit_yes, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setOrderSerial();
}
});
AlertDialog ald = alb.create();
ald.show();
}
private void setOrderSerial() {
dbr = FirebaseDatabase.getInstance().getReference(phoneNumber);
if (orderNo <= orderSerial) {
orderNo = orderSerial;
orderNo += 1;
}
OrderSerial osObject = new OrderSerial(orderNo);
dbr.setValue(osObject);
uploadAllData();
}
private void uploadAllData() {
dbReference =
FirebaseDatabase.getInstance().getReference(phoneNumber).child("orderNo:
"+orderNo);
DataTemplate dtObject;
int i;
for (i = 0; i < len; i++) {
if (pieces[i] != 0) {
dtObject = new DataTemplate(names[i],pieces[i]);
dbReference.child("serialNo:
"+serialNos[i]).setValue(dtObject);
}
}
}
private void collectAllData() {
nameOfPerson = nameField.getText().toString();
phoneNumber = phoneField.getText().toString();
areaName = areaField.getText().toString();
addressOfOrder = addressField.getText().toString();
detailsOfOrder = detailsField.getText().toString();
}
private void initializeAll(View v) {
numWarning = v.findViewById(R.id.numWarning);
nameField = v.findViewById(R.id.nameField);
phoneField = v.findViewById(R.id.phoneField);
areaField = v.findViewById(R.id.areaField);
addressField = v.findViewById(R.id.addressField);
detailsField = v.findViewById(R.id.detailsField);
confirmCV = v.findViewById(R.id.confirmCV);
}
}
My OrderSerial Class::
package com.binarysoftwareltd.airaid;
public class OrderSerial {
private int currentOrderSerial;
public OrderSerial() {
}
public OrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
public int getCurrentOrderSerial() {
return currentOrderSerial;
}
public void setCurrentOrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
}
The XML code of the AddressFragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="match_parent"
android:background="#drawable/app_main_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="120dp"
android:text="#string/address_fragment_title"
android:textColor="#color/pureBlack"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/numWarning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/number_warning"
android:textColor="#color/img_warning"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/name_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_person"/>
<EditText
android:id="#+id/nameField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="70dp"
android:hint="#string/name_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/phone_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_phone"/>
<EditText
android:id="#+id/phoneField"
android:layout_marginStart="5dp"
android:inputType="phone"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="4"
android:hint="#string/phone_field" />
<EditText
android:id="#+id/areaField"
android:layout_marginStart="10dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:hint="#string/area_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/address_fragment_title"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_location"/>
<EditText
android:id="#+id/addressField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/address_fragment_title" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/details_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_details"/>
<EditText
android:id="#+id/detailsField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/details_field" />
</LinearLayout>
<androidx.cardview.widget.CardView
android:id="#+id/confirmCV"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
app:cardCornerRadius="18dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_view_bg"
android:gravity="center">
<ImageView
android:contentDescription="#string/order_now"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_confirm" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="#string/order_now"
android:textColor="#color/pureWhite"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
here my JSON::
{
"23" : {
"currentOrderSerial" : 2,
"orderNo: 2" : {
"serialNo: 1" : {
"name" : "napa Extra",
"piece" : 200
}
}
}
}
[I use phone number as primary Identifier for every user. That's why phone numbers must be required.]
Please help to fix this...
Thanks in Advance...

passing edittext values to another activity getting null values

here's my sample task app, I have six clases Employee, Department, EmployeeActivity , ViewEmployeeInfo, ViewDepartmentInfo,
When user click on add employee it must be navigate to EmployeeActivity, and the same thing when click on department it's navigate to Department class, I created an employee object on EmployeeActivity to send it to ViewEmployeeInfo activity and it must view it on the five EditText that I created it, the problem is that when I Click on Submit button to send data via Intent with putExtra method that takes Serializable object I see no values on EditTexts on anther activity, I tried to send it with regual putExtra method as int,String,String,double,String also got NullPointerException
Here's my code, first this the Employee class
package com.companyactivityexample.companyactivityexample;
import android.widget.Button;
import android.widget.EditText;
import java.io.Serializable;
/**
* Created by MML on 24/12/2017.
*/
public class Employee implements Serializable {
private int id;
private String name;
private String address;
private double salary;
private String job;
public Employee(int id, String name, String address, double salary, String job) {
this.id = id;
this.name = name;
this.address = address;
this.salary = salary;
this.job = job;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
this activity_main
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.companyactivityexample.companyactivityexample.MainActivity"
android:orientation="vertical"
>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="10dp"
android:text="Add employee"
android:textSize="25sp"
android:textAllCaps="false"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:text="Add department"
android:textSize="25sp"
android:textAllCaps="false"
/>
</LinearLayout>
and this Main Class
`package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button addEmployee;
private Button addDepartment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addEmployee = (Button) findViewById(R.id.button1);
addDepartment = (Button) findViewById(R.id.button2);
addEmployee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,EmployeeActivity.class);
startActivity(i);
}
});
addDepartment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,Department.class);
startActivity(i);
}
});
}
}
the employee_activity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<EditText
android:id="#+id/empID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="ID"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="number"
/>
<EditText
android:id="#+id/empName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Name"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<EditText
android:id="#+id/empAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Address"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<EditText
android:id="#+id/empSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Salary"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="numberDecimal"
/>
<EditText
android:id="#+id/empJob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Job"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:text="Submit"
android:textSize="25sp"
android:textAllCaps="false"
/>
</LinearLayout>
</ScrollView>
the EmployeeActivity class
package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by MML on 27/12/2017.
*/
public class EmployeeActivity extends AppCompatActivity {
private EditText editTextID;
private EditText editTextName;
private EditText editTextAddress;
private EditText editTextSalary;
private EditText editTextJob;
private Button submitButton;
private Employee employee1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employee_activity);
editTextID = (EditText) findViewById(R.id.empID);
editTextName = (EditText) findViewById(R.id.empName);
editTextAddress = (EditText) findViewById(R.id.empAddress);
editTextSalary = (EditText) findViewById(R.id.empSalary);
editTextJob = (EditText) findViewById(R.id.empJob);
submitButton = (Button) findViewById(R.id.submit);
if(isEmpty(editTextID) || isEmpty(editTextSalary)){
editTextID.setText("0");
editTextSalary.setText("0");
}
employee1 = new Employee(Integer.parseInt(editTextID.getText().toString())
, editTextName.getText().toString(), editTextAddress.getText().toString()
, Double.parseDouble(editTextSalary.getText().toString())
, editTextJob.getText().toString());
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putExtra("emp",employee1);
startActivity(i);
}
});
}
/*i.putExtra("id",id);
i.putExtra("name",name);
i.putExtra("address",address);
i.putExtra("salary",salary);
i.putExtra("job",job);*/
private static boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
}
the view_employee_info activity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:fillViewport="true"
tools:context=".ViewEmployeeInfo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="ID"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Name"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Address"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Salary"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Job"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextJob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<Button
android:id="#+id/editButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="Edit"
android:textAllCaps="false"
android:textSize="25sp" />
</LinearLayout>
</ScrollView>
the ViewEmployeeInfo class
package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by MML on 24/12/2017.
*/
public class ViewEmployeeInfo extends AppCompatActivity {
private EditText editID;
private EditText editName;
private EditText editAddress;
private EditText editSalary;
private EditText editJob;
private Button editButton;
private Employee employee;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_employee_info);
Intent i = getIntent();
employee = (Employee) i.getSerializableExtra("emp");
editID = (EditText) findViewById(R.id.editTextID);
editID.setText(employee.getId() + "");
editName = (EditText) findViewById(R.id.editTextName);
editName.setText(employee.getName());
editAddress = (EditText) findViewById(R.id.editTextAddress);
editAddress.setText(employee.getAddress());
editSalary = (EditText) findViewById(R.id.editTextSalary);
editSalary.setText(employee.getSalary() + "");
editJob = (EditText) findViewById(R.id.editTextJob);
editJob.setText(employee.getJob());
editButton = (Button) findViewById(R.id.editButton);
/*Intent i = getIntent();
int getID = i.getIntExtra("id", 0);
String getName = i.getStringExtra("name");
String getAddress = i.getStringExtra("address");
double getSalary = i.getDoubleExtra("salary", 0.0);
String getJob = i.getStringExtra("job");
editID.setText(getID);
editName.setText(getName);
editAddress.setText(getAddress);
editSalary.setText(getSalary + "");
editJob.setText(getJob);*/
}
}
You put the extra in with key of "emp1" and are trying to retrieve it using a key of "emp" in getSerializableExtra("emp"). Simple typo.
Edit: Not a typo. Instead of putExtra("emp", employee1) , cast like putExtra("emp", (serializable) employee1)
Pass the serializable list using Bundle.Serializable
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putSerializable("emp",employee1);
startActivity(i);
Instead
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putExtra("emp",employee1);
startActivity(i);
Receive
Intent i = getIntent();
employee = (Employee) i.getSerializableExtra("emp");
The problem was resolved, it was supposed to put the new object of employee1
inside the action of submit button
employee1 = new Employee(Integer.parseInt(editTextID.getText().toString())
, editTextName.getText().toString(), editTextAddress.getText().toString()
, Double.parseDouble(editTextSalary.getText().toString())
, editTextJob.getText().toString());

onOptionsItemClick or onMenuItemClick not being called

(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView 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.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?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:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.

Android Fragments showing irregular behavior

I have multiple fragments in my Activity. It should initiate only first fragment at start up. It initializes the second one also. More over I move from one fragment to the other though a swipe action. When I swipe from first fragment to the next, third in the row is also initiated.
I have to get data from the server and then populate that fragment. Network request is sent but not for the one for which I am sending but for the fragment next to it.
Please suggest me where I am mistaken...
Thanks in advance.
Following is the code:
Note: Sample code is being used, Please consider the other fragments and their layouts as the same as that for Fragment1.
Main Activity
package com.example.fragments;
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements OnClickListener {
/**
* Constants for tabs
*/
public static final int TAB_SCORES = 0;
public static final int TAB_PAVILION = 1;
public static final int TAB_FRIENDS = 2;
public static final int TAB_OTHER = 3;
public static final int TAB_CROWD = 4;
public static final int TAB_SOCIAL = 5;
private List<Fragment> fragments=null;
private FragmentsAdaptor _adapter;
/** The context object. */
public static Object contextObject = null;
private TableLayout scoresTab, socialTab, pavilionTab, friendsTab, othersTab, crowdTab;
private TextView mScoresTv, mPavilionTv, mFriendsTv, mOtherTv, mCrowdTv, mSocialTv;
private HorizontalScrollView tabsLayout;
private int fragmentPosition;
public ViewPager mViewPager;
private int moveRight = 100;
#Override
protected void onStart() {
super.onStart();
}
/**
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mViewPager = (ViewPager)findViewById(R.id.viewPager);
setViews();
addListeners();
setTab();
addFragments();
}
private void setViews() {
scoresTab = (TableLayout)findViewById(R.id.scores_tab);
pavilionTab = (TableLayout)findViewById(R.id.pavilion_tab);
friendsTab = (TableLayout)findViewById(R.id.friends_tab);
othersTab = (TableLayout)findViewById(R.id.others_tab);
crowdTab = ((TableLayout)findViewById(R.id.crowd_tab));
socialTab = (TableLayout)findViewById(R.id.social_tab);
tabsLayout = (HorizontalScrollView)findViewById(R.id.tabs_layout);
mScoresTv = (TextView)findViewById(R.id.scores);
mPavilionTv = (TextView)findViewById(R.id.pavilion);
mFriendsTv = (TextView)findViewById(R.id.friends);
mOtherTv = (TextView)findViewById(R.id.other);
mCrowdTv = (TextView)findViewById(R.id.crowd);
mSocialTv = (TextView)findViewById(R.id.social);
}
private void addListeners() {
mScoresTv.setOnClickListener(MainActivity.this);
mPavilionTv.setOnClickListener(MainActivity.this);
mFriendsTv.setOnClickListener(MainActivity.this);
mOtherTv.setOnClickListener(MainActivity.this);
mCrowdTv.setOnClickListener(MainActivity.this);
mSocialTv.setOnClickListener(MainActivity.this);
}
private void addFragments(){
fragments = new Vector<Fragment>();
fragments.add(new Fragment1(this));
fragments.add(new Fragment2(this));
fragments.add(new Fragment3(this));
fragments.add(new Fragment4(this));
fragments.add(new Fragment5(this));
fragments.add(new Fragment6(this));
this._adapter = new FragmentsAdaptor(super.getSupportFragmentManager(), fragments);
mViewPager.setAdapter(this._adapter);
}
#Override
public void onClick(View v){
onTabsClick(v);
}
public void onTabsClick(View v) {
//reset layout of all the text views
resetlayouts();
if(v == mScoresTv) {
if(mViewPager.getCurrentItem() != TAB_SCORES) {
changeTab(TAB_SCORES);
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mCrowdTv) {
if(mViewPager.getCurrentItem() != TAB_CROWD) {
changeTab(TAB_CROWD);
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mFriendsTv) {
if(mViewPager.getCurrentItem() != TAB_FRIENDS) {
changeTab(TAB_FRIENDS);
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mOtherTv) {
if(mViewPager.getCurrentItem() != TAB_OTHER) {
changeTab(TAB_OTHER);
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mPavilionTv) {
if(mViewPager.getCurrentItem() != TAB_PAVILION) {
changeTab(TAB_PAVILION);
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mSocialTv) {
if(mViewPager.getCurrentItem() != TAB_SOCIAL) {
changeTab(TAB_SOCIAL);
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
}
}
}
private void changeTab(int tabType) {
mViewPager.setCurrentItem(tabType);
System.out.println("tab to change to: " + tabType);
}
private void resetlayouts(){
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
othersTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
socialTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mScoresTv.setTextColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.black));
}
private void setTab() {
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
System.out.println("setTab:::::::::::::::::::::::::::::::::::" + position);
int previousFragment = fragmentPosition;
if(previousFragment < position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() + moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
if(previousFragment > position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() - moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
fragmentPosition = position;
resetlayouts();
System.out.println("In on tab change listener!");
switch(position) {
case TAB_SCORES:
System.out.println("scores");
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
case TAB_PAVILION:{
System.out.println("pavilion");
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_FRIENDS:{
System.out.println("friends");
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_OTHER:{
System.out.println("others");
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_CROWD:{
System.out.println("crowd");
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_SOCIAL:{
System.out.println("social");
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
}
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null)
fragment.onPause();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentsAdapter
package com.example.fragments;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentsAdaptor extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public FragmentsAdaptor(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
public Fragment getFragment(int position) {
return this.fragments.get(position);
}
}
Fragment1
package com.example.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
public class Fragment1 extends Fragment implements OnClickListener {
private Context context;
public Fragment1() {}
public Fragment1(Context contex) {
this.context=contex;
}
#Override
public void onClick(View arg0) {
}
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
System.out.println("Fragment1.onInflate() called................");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
System.out.println("Fragment1.onAttach() called................");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Fragment1.onCreate() called................");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
System.out.println("Fragment1.onCreateView() called................");
View root = (View) inflater.inflate(R.layout.fragment1_screen, null);
updateArticleView(root);
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("Fragment1.onActivityCreated() called................");
}
#Override
public void onStart() {
super.onStart();
System.out.println("Fragment1.onStart() called................");
}
#Override
public void onResume() {
super.onResume();
System.out.println("Fragment1.onResume() called................");
}
#Override
public void onPause() {
super.onPause();
System.out.println("Fragment1.onPause() called................");
onDestroyView();
}
#Override
public void onDestroyView() {
super.onDestroyView();
System.out.println("Fragment1.onDestroyView() called................");
onDestroy();
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Fragment1.onDestroy() called................");
onDetach();
}
#Override
public void onDetach() {
super.onDetach();
System.out.println("Fragment1.onDetach() called................");
}
public void updateArticleView(View view) {
}
}
Main Activity Layout
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<HorizontalScrollView
android:id="#+id/tabs_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="2dp"
android:paddingRight="2dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<!-- First Tab -->
<TableLayout
android:id="#+id/scores_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/scores"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Scores"
android:textColor="#android:color/white"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Second Tab -->
<TableLayout
android:id="#+id/pavilion_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/pavilion"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="25dp"
android:text="Pavilion"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Third Tab -->
<TableLayout
android:id="#+id/friends_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/friends"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Friends"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fourth Tab -->
<TableLayout
android:id="#+id/others_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/other"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Other"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fifth Tab -->
<TableLayout
android:id="#+id/crowd_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/crowd"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Crowd"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="0px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Sixth Tab -->
<TableLayout
android:id="#+id/social_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/social"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Social"
android:textColor="#android:color/black"
android:textSize="12sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#id/tabs_layout"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" >
</android.support.v4.view.ViewPager>
Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/text1"
android:text="Fragment1 Text"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I achieved it by placing the following code at the end of OnPageChangeListener.onPageSelected()
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null) {
fragment.onPause();
}
I am using onPause() in the following way
public void onPause(){
super.onPause();
onDestroyView();
}
public void onDestroyView() {
super.onDestroyView();
onDestroy();
}
public void onDestroy() {
super.onDestroy();
onDetach();
}
public void onDetach() {
super.onDetach();
}
this is a known issue, that ViewPager(FragmentAdapter(Fragements)) created and destroyed according to the actual page.
I also came across with this situation, furthermore the data (Object) not referenced, because of a destroy will be collected by the GC so this is difficult.
I would use a static object at the main Activity and with the onRetainNonConfigurationInstance method I would save and load Fragment state.
Also found another solution which concentrated on the passed data between the Fragments (A,B and passed String data) here.
I hope one of these solutions are suitable for you!
Just call setOffscreenPageLimit() in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page. Set the minimum number of fragments you want to initiate either side.

Categories

Resources