setText in fragment from another activity not related with fragment - java

i wanna set textView in fragment from another activity which this activity is not MainActivity has fragment transaction ..
already tried some method from the other related article which related with my problem, but got an error..
here's my method inside fragment to recieve from another activity
Fragment A
public class FragmentA extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setCancelable(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_A, container, false);
//Put Data to id fragment
valueName = (TextView) layout.findViewById(R.id.valueNameNav);
valueStatus = (TextView) layout.findViewById(R.id.valueStatusNav);
}
public void setText(String name, String status){
valueName = (TextView) getView().findViewById(R.id.valueNameNav);
valueName.setText(name);
valueStatus = (TextView) getView().findViewById(R.id.valueStatusNav);
valueStatus.setText(status);
}
}
and this is how i call setText method in fragment from activity
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
FragmentA mFragment = (FragmentA )
getSupportFragmentManager().findFragmentById(R.id.fragment_A);
mFragment.setText(editValueName, lastStatus);
but got an error like this
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.study.fragment.fragmentA.setText(java.lang.String,
java.lang.String)' on a null object reference
100% sure there's a data string on string getText

Create a FrameLayout in your activity with id container with height width to MATCH_PARENT
Then add fragment in your activity like this
FragmentA newFragment = new FragmentA ();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).commit();
and than set your text
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
newFragment .setText(editValueName, lastStatus);

You can useing store SharedPreferences for save your string and load it in every where.Of course, if you like to change your code.

No need to findView in setText method you should do in this way and it will work
public class FragmentA extends Fragment {
TextView valueName,valueStatus ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setCancelable(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_A, container, false);
//Put Data to id fragment
valueName = (TextView) layout.findViewById(R.id.valueNameNav);
valueStatus = (TextView) layout.findViewById(R.id.valueStatusNav);
return layout;
}
public void setText(String name, String status){
valueName.setText(name);
valueStatus.setText(status);
}
}

Try to do like this and make sure your fragment is attached with activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grupos);
if(savedInstanceState == null)
{
fragment = new FragmentA();
fragment.setTag(R.id.myfragmentId);
getFragmentManager().beginTransaction()
.add(R.id.container, fragment).commit();
}
else
{
if(fragment == null)
{
fragment = (FragmentA) getFragmentManager().findFragmentByTag(R.id.myfragmentId);
}
}
}

Related

How to setOnclick Listener to image in fragment

I have image in my fragment. I want click on the picture and... for example change the fragment. I have found the same topic How to setOnclick Listener to button in fragment but ClickListner does not work.
I have tried make the same code in Activity and onClickListner is work, but in the frame it does not work.
Below my code in the Fragment.
public class Fragment2 extends Fragment {
ImageView imageView;
MyListner listner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View getview = inflater.inflate(R.layout.fragment_2, container, false);
imageView = (ImageView) getview.findViewById(R.id.imageView1);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listner.callback();
}
});
return inflater.inflate(R.layout.fragment_2, container, false);
}
Below my interface
public interface MyListner {
public void callback();}
Below my MainActivity
public class MainActivity extends AppCompatActivity implements MyListner {
Fragment2 fragment2;
Fragment1 fragment1;
ImageView imageViewMain;
ImageView imageViewFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment2 = new Fragment2();
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment2);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
#Override
public void callback() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment1);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}}
Please, let me know where is the problem?
It seems you are inflating your fragment's view twice. Instead of this you need to return the view which you have already inflated as a result of your onCreateView inside Fragment2.
Try changing
return inflater.inflate(R.layout.fragment_2, container, false);
to
return getview;

ClassCastException occurs when calling another fragment's method

**Re-attached the relevant code
When I run the email app in FragmentB, the activity's 'onStop' is called.
At this time, FragmentA's method in 'onStop' does not work.
※ FragmentA and FragmentB have the same parent Activity
※ No error occurs when the app is terminated in FragmentB.
MainActivity.java
public class MainActivity extends FragmentActivity {
public Fragment fragmentA, fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
fragmentA = new FragmentA();
fragmentB = new FragmentB();
fragmentA.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentA).commit();
}
}
#Override
protected void onStop() {
super.onStop();
((FragmentA) getSupportFragmentManager().findFragmentById(R.id.fragment_container)).saveData();
}
}
FragmentA.java
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_timer, container, false);
if(isLoadData){ loadData(); }
return view;
}
public void saveData() {
SharedPreferences timerSharedPref = getActivity().getSharedPreferences("timer", Context.MODE_PRIVATE);
//...
SharedPreferences.Editor editor = timerSharedPref.edit();
String json = jsonArray.toString();
editor.putString("jsonString", json);
editor.apply();
}
FragmentB.java
public class FragmentB extends Fragment implements View.OnClickListener {
View view;
CardView cvContactUs;
MainActivity activity;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity = (MainActivity) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_b, container, false);
cvContactUs = view.findViewById(R.id.cv_contact_us);
return view;
}
#Override
public void onStart() {
super.onStart();
cvContactUs.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.cv_contact_us) {
sendEmail(getActivity(), "Ask a question", new String[]{"help_center#gmail.com"});
}
}
public static void sendEmail(Context context, String title, String[] receivers){
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, title);
email.putExtra(Intent.EXTRA_EMAIL, receivers);
email.setType("message/rfc822");
context.startActivity(email);
}
}
You say you are getting a ClassCastException. The only class cast from the code you posted is
(FragmentA) getSupportFragmentManager().findFragmentById(...)
So check whether findFragmentById might return FragmentB or something else. Maybe you want to
either cast to the common parent activity
check whether the returned value is an instance of FragmentA before casting
You have two Fragments in the stack and a single ID and the findFragmentByID() method returns the last fragment added to the container. very well when the application ends with the FragmentA I believe that you don't have any error because in the onStop() method you are casting with the FragmentA, but if you end with the FragmentB in this case you are casting the FragmentB by the FragmentA which throws the ClassCastException exception. so I suggest you use the findFragmentByTag() method here is an example
When you add fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* rest of your code
*/
// when you add the Fragment A
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, new FragmentA(), "A")
.commit();
// when you add the Fragment A
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, new FragmentB(), "B")
.commit();
}
and when you call the onStop() methode:
#Override
protected void onStop() {
super.onStop();
// ((FragmentA) getSupportFragmentManager().findFragmentByTag("A")).save();
// ((FragmentB) getSupportFragmentManager().findFragmentByTag("B")).save();
Fragment f = getSupportFragmentManager().findFragmentByTag("A");
// you check if the fragment is add
if (f != null)
((FragmentA) f).save();
}

Layout inflation issues: Two layouts are inflated in a fragment, instead of one

I want to open a fragment from my activity, but when I do both the Activity layout and fragment layout is inflated, I only want the fragment layout to display. Why is this?
Activity Code:
public class Login extends Activity {
public static String res="";
private EditText login_username,login_pass;
private TextView test_login;
private SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btn_login = (Button) findViewById(R.id.btnLogin);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login(login_username.getText().toString(),login_pass.getText().toString());
}
});
private void login(final String user,String pass){
new Login_Server("http://192.168.1.100/test/index.php/client_users/Login",user,pass).execute();
final ProgressDialog pd=new ProgressDialog(Login.this);
pd.setMessage("Please Wait...");
pd.show();
final Timer tm=new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (res.equals("login")) {
Index index = new Index();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, index); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
tm.cancel();
res = "";
}
}
});
}
}, 1, 1500);
}
Fragment code:
public class Index extends Fragment implements View.OnClickListener {
private Button Index,Share;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.index, container, false);
Index=(Button)rootview.findViewById(R.id.index_page);
Share=(Button)rootview.findViewById(R.id.share_page);
btn_click();
return rootview;
}
public void btn_click(){
Index.setOnClickListener(this);
Share.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.share_page:
Share share_page = new Share();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, share_page); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
break;
}
}
}
xml layout fragment:
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:weightSum="100">
<include layout="#layout/main_index"></include>
<include layout="#layout/bottom_menu"></include>
</LinearLayout>
On your login activity
setContentView(R.layout.login);
inflates the activity layout
and on your fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.index, container, false);
Index=(Button)rootview.findViewById(R.id.index_page);
Share=(Button)rootview.findViewById(R.id.share_page);
btn_click();
return rootview;
}
inflates the fragment's layout
therefor you inflate 2 layouts
anyway if u wish to use the fragment layout allover the activity screen
u should change the activity layout to host a container with an ID
like in your code on the activity u have this line:
transaction.replace(android.R.id.content, index);
you should just have a view on the activity layout with the id=content and make it match_parent on height and width
this one should be the parent of all the other childs on the layout
that way the fragment will cover all of the activity layout when u replace the container
gl..

New fragment on button click from another fragment?

can anyone point me in the right direction and tell me what I'm doing wrong?
I have here a fragment with a button. When the button is pressed, it needs to replace the current fragment and load a new one. I've figured how to go from Fragment to Activity, and Activity to Fragment, just not Fragment to Fragment. I'm aware this question has been asked a few times but I'm just so new I couldn't figure it out myself.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
I think you are not initialising the FragmentManager. Without FragmentManager it is not possible to replace,update,create any fragment. Beacuse it is responsible replace or deleting any fragment. Hope this will help.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}

No view found for id ... for fragment (Android application)

I am struggling with following error when I try to invoke fragment layout. Here is the code.
MainActivity;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showFragOne(View view){
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.layout.frag_one, new FragOne());
FT.commit();
}
}
showFragOne is called when button click on ativity_main layout.
frag_one is layout for FragOne Fragment
Fragment Class;
public class FragOne extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_one, container, false);
return view;
}
}
Please help me in resolving this.
the way you are calling add() is wrong. The first parameter is the id of a ViewGroup that is going to host the fragment, not the layout of the fragment itself. For instance
FT.add(android.R.id.content, new FragOne());

Categories

Resources