Sending a variable from a fragment to MainActivity - java

In my app I have three fragments. In the third fragment, a variable is take from a seekBar. Now I want to use this variable in my MainActivity. I tried to send the variable with an intent and show it in a textView onClick to test it, but the textView only shows „null“. Why isn‘t the variable send to the activity?
My MainActivity:
public class MainActivity extends AppCompatActivity {
TextView textTest;
public int a = 33;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTest = (TextView) findViewById(R.id.textView3);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
String messages = intent.getStringExtra("message");
textTest.setText(String.valueOf(messages));
}
});
}
}
My Fragment that sends the variable:
public class ItemThreeFragment extends Fragment {
SeekBar seekBar;
TextView textView11;
int value = 10;
public static ItemThreeFragment newInstance() {
ItemThreeFragment fragment = new ItemThreeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_three, container, false);
seekBar = (SeekBar) view.findViewById(R.id.seekBar);
seekBar.setMax(25);
seekBar.setProgress(value);
textView11 = (TextView) view.findViewById(R.id.textView11);
textView11.setText("" + value);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
value = i;
textView11.setText("" + value);
Intent intent = new Intent(getActivity().getBaseContext(),
MainActivity.class);
intent.putExtra("message", value);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
})
return view;
}
}

The problems are
In your activity, Intent intent = getIntent(); will get the intent that starts MainActivity.
In your fragment's onProgressChanged, your code doesn't communicate with MainActivity at all.
I can think of two relatively simple solutions for now:
Call a MainActivity function using ((MainActivity) getActivity()).someFunction() in your fragment.
In the MainActivity, use ((YourFragment) getSupportFragmentManager().findFragmentById(R.id.your_fragment_id)).property to access the fragment object's content. You can put the seek bar value into a class variable.
And check this: Communicating between a fragment and an activity - best practices

getActivity().findViewById(R.id.textView3).setText(""+value);
put the code inside onProgressChanged(),I hope its help you.

I think you missed startActivity(intent).
Intent intent = new Intent(getActivity().getBaseContext(),
MainActivity.class);
intent.putExtra("message", value);
getActivity().startActivity(intent);

Related

Cant get an int value from on class to another class : android studio

I'm kind of new to android. I want to get an int value id(id of dynamically generated buttons) from class MainPage into class Note when a button is clicked. but the value of id always turns to zero in Note class.
here's the summerized code:
MainPage class:
public class MainPage extends AppCompatActivity {
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int j=0; j<allnotes.size(); j++) {
//generating buutons
final Button preview_text = new Button(this);
preview_text.setId(j)
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id=v.getId();
startActivity(new Intent(MainPage.this, Note.class));
}
});
}
}
}
Notes class:
public class Note extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
MainPage obj=new MainPage();
int id=obj.id
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout,Integer.toString(id) , 10000);
mySnackbar.show();
}
in snackbar message, id is always zero.
You need to add the id to the Intent you use to start the Note activity. You do this by using Intent.putExtra(...) and in Note you retrieve it via getIntent().getIntExtra(...)
Here I implemented #Riccully Answer in your code.
MainPage.java
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id = v.getId();
Intent intent = new Intent(MainPage.this, Note.class);
intent.putExtra("id_value", id);
startActivity(intent);
}
});
Note.java
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
int id = getIntent().getIntExtra("id_value", 0);
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout, Integer.toString(id), 10000);
mySnackbar.show();
}
we can do this via intent Because Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services, etc.
In Our case, we can send the v.getId() to Note.java, viaputExtra
intent.putExtra("view_id",v.getId());
and receive the value in Note.java by using
getIntent().getIntExtra("view_id", 0);

Sharing data between an adapter-recyclerview and another class

I want to send in a variable the position of a click on an Item in a other activity. I show you my work that does not work. The application quits when I press an item.
MyViewHolder in my adapter:
public myViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get position
int poss = getAdapterPosition();
// sharing position
Intent intent = new Intent(mContext, Main2Activity.class);
intent.putExtra("position", poss );
mContext.startActivity(intent);
}
}
});
And my Activity for recept:
public class Main2Activity extends AppCompatActivity {
private TextView textTest;
int id = getIntent().getExtras().getInt("position");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
String position = String.valueOf(id);
textTest = findViewById(R.id.text_test);
textTest.setText(position);
}
Try
public class Main2Activity extends AppCompatActivity {
private TextView textTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textTest = findViewById(R.id.text_test);
int id = getIntent().getExtras().getInt("position");
String position = String.valueOf(id);
textTest.setText(position);
}
Remove this line of code int id = getIntent().getExtras().getInt("position"); from outside of the onCreate() method & put this code inside of your onCreate Method in Main2Activity
textTest = findViewById(R.id.text_test);
int id = getIntent().getExtras().getInt("position");
String position = String.valueOf(id);
textTest.setText(position);
Create Interface class
Public interface OnPostionClick{
Public void yourmethod(int pos)
}
Place interface method on Adapter viewHolder onClick method
If(context instanceof OnPostionClick){
((OnPostionClick) context).yourmethod(poss);
}
implement OnPostionClick interface on Second Activity and override yourmethod

int/string value becomes "0"/null when passed from one activity to another

I have two activities, MainActivity and SecondActivity. While passing int value from MainActivity to SecondActivity it becomes "0". I have tried with and without bundle, tried various solution already present on StackOverFlow, but no go.
Here is my code:
MainActivity
final Intent intent = new Intent(MainActivity.this, SecondActivity.class);
final TextView textView = findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Bundle bundle = new Bundle();
bundle.putInt("category",9);
intent.putExtras(bundle);
startActivity(intent);
}
});
SecondActivity:
package com.example.app;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SecondActivity extends AppCompatActivity {
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;
private int mMedCategory = 6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// String stringCategory = getIntent().getStringExtra("category_string");
int medCategory = getIntent().getIntExtra("category_int", -1);
setMedCategory(medCategory);
viewPager = findViewById(R.id.viewpager);
pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public int getMedCategory(){
return mMedCategory; //This value goes to TabsPagerAdapter
}
public void setMedCategory(int i){
mMedCategory = i;
}
}
You can try this:
MainActivity
TextView textView = findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("category_int", 9);
intent.putExtra("category_string", "9");
startActivity(intent);
}
});
SecondActivity
private int medCategoryInt;
private String medCategoryString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
medCategoryInt = getIntent().getIntExtra("category_int", 0);
medCategoryString = getIntent().getStringExtra("category_string");
}
You can have a look at How do I pass data between Activities in Android application?
Use Intent#getIntExtra() to retrieve an integer value from the intent:
From MainActivity:
Intent myIntent = new Intent(MainActivity.this, SecondActivity.class);
myIntent.putExtra("category", 9);
MainActivity.this.startActivity(myIntent);
From SecondActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
medCategory = intent.getIntExtra("category", -1);
}
Note that this would assign a default value of -1 to medCategory in the event that the key cannot be found.
I'm not sure but You may use this for second activity:
SecondActivity secondActivity = new SecondActivity();
if (secondActivity.getIntent.getExtras() != null)
{
int medCat = secondActivity.getIntent.getExtras().getInt("category");
}
Use this code. Remove final and try to initialize intent in onclick method not outside of it.
In your OnClick
Intent intent=new Intent(this,Main2Activity.class);
Bundle bundle = new Bundle();
bundle.putInt("category",9);
intent.putExtras(bundle);
startActivity(intent);
In your second activity
public class Main2Activity extends AppCompatActivity {
private int mMedCategory =0;
public int getmMedCategory() {
return mMedCategory;
}
public void setmMedCategory(int mMedCategory) {
this.mMedCategory = mMedCategory;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
int demoCategory =bundle.getInt("category");
setmMedCategory(demoCategory);
}else {
Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
}
}
public void Show(View view) {
Toast.makeText(this, String.valueOf(getmMedCategory()), Toast.LENGTH_SHORT).show();
}
}
EDIT
Created a demo project for you it is working. Show method is onclick method of a button.

how get data from DialogFragment to Mainactivity

How con I get text from TextView in DialogFragment to MainActivity or how i make event in MainActivity when Button in DialogFragment clicked. pleas help me i tried like this in below:but it dose not work what is the problem.
public class MainActivity extends AppCompatActivity {
Button b; Button b2; String name;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
name = data.getStringExtra("name").toString();
Toast.makeText(MainActivity.this,name+ "", Toast.LENGTH_LONG).show();}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.b);
b=(Button)findViewById(R.id.b);
b2=(Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b2.setText(name);}});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager manager = getFragmentManager();
fragment afr = new fragment();
afr.setTargetFragment(afr, 1);
afr.show(manager, "dialog");
return true;}}
class fragment extends DialogFragment {
View v; Intent intent; EditText t1; Button b1; String name;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment, container, false);
t1=(EditText) v.findViewById(R.id.t1);
b1=(Button) v.findViewById(R.id.b1);
intent = new Intent();
int resultCode = 1;
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
getDialog().dismiss();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=t1.getText().toString();
intent.putExtra("name", name);
fragment.this.dismiss();
}}); return v;}}
You can use interfaces.
Declare interface in fragment and implement it in MainActivity.
https://developer.android.com/training/basics/fragments/communicating.html
In DialogFragment declare
public IDialogCallback {
void onTextWritted(String text);
void onDialogBtnClick()
}
Then declare field in Dialog:
OnDialogCallback mCallback
Later:
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (ITailLiftCallback) context;
}
Now you can call mCallback.onTextWritted() or mCallback.onDialogBtnClick in DialogFragment. In first case you may put text from TextView and second - put it in OnClickListener of a button.
Then make MainActivity implements IDialogCallback and it is all! :)

Handling Multiple Fragments when orientation changes

I have a MainActivity, and I want to attach a fragment with 3 buttons in it to that activity. On clicking button 1 it should replace this fragment with another fragment. But when I change orientation the current fragment and the old fragment are both getting attached. Can someone help me solve this ?
Following is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements OnButtonsClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.mainactivity, new FragmentHomepage(), "aboutMe")
.commit();
}
#Override
public void button1Action() {
FragmentAboutMe fragmentAboutMe=new FragmentAboutMe();
getSupportFragmentManager().beginTransaction()
.add(R.id.mainactivity,fragmentAboutMe)
.commit();
}
#Override
public void button2Action() {
Intent intent =new Intent(this,ActivityMasterDetail.class);
startActivity(intent);
}
#Override
public void button3Action() {
Intent intent =new Intent(this,ActivityViewPager.class);
startActivity(intent);
}
}
This is my FragmentHomepage.java:
public class FragmentHomepage extends Fragment {
private static final String ARG_SECTION_NUMBER ="section number";
OnButtonsClickListener onButtonsClickListener;
public static FragmentHomepage newInstance(int sectionNumber){
FragmentHomepage fragmentHomepage=new FragmentHomepage();
Bundle args=new Bundle();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragmentHomepage.setArguments(args);
return fragmentHomepage;
}
public FragmentHomepage(){}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onButtonsClickListener= (OnButtonsClickListener) context;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Button button1= (Button) getActivity().findViewById(R.id.aboutMe);
final Button button2= (Button) getActivity().findViewById(R.id.task2);
final Button button3= (Button) getActivity().findViewById(R.id.task3);
button1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button1Action();
}
});
button2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button2Action();
}
});
button3.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
onButtonsClickListener.button3Action();
}
});
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView=null;
rootView =inflater.inflate(R.layout.fragment_homepage,container,false);
return rootView;
}
}
and my second activity is as follows
(in FragmentAboutMe.java):
public class FragmentAboutMe extends Fragment {
int counters=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null)counters=0;
else counters=savedInstanceState.getInt("count");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count",13);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_aboutme,container,false);
}
}
In your onCreate() method put a check whether the fragment is already present. Android automatically restores the fragment manager state upon orientation change and hence upon orientation change, the fragment which you added on button click would automatically be added. Thus if you will add new fragment in onCreate() without check, this would result in adding the 2 fragments. This is causing the issue.
FragmentManager fm = getSupportFragmentManager();
if (fm.findfragmentById(R.id.mainactivity) == null) {
FragmentHomepage fragment = new FragmentHomepage ();
fm.beginTransaction().add (R.id.mainactivity, fragment).commit();
}
You would want to save the state. You would need to extend Fragment to store the objects that need saving.
Override the onConfigurationChanged(..) and it should work out.
When I had to handle screen orientation changes, I recall having used this reference [link].
There are two ways.
Either you need to save the state in the bundle in onSaveInstanceState() method. Also save the states of fragment.
When activity recreate itself then check the value of bundle inside onCreate() or onRestoreInstanceState() method. Now initialize all the objects as before.
Else
set the value of activity inside manifest file as
android:configChanges="layoutDirection|orientation|screenLayout|screenSize"
and override the method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
Second technique will not allow the activity to restart on orientation change.

Categories