How to pass data from Activity A to fragment in Activity B? - java

I need to pass data from Activity "MainCalendar" to fragment "AddTaskFragment" in Activity "Add". I have a button in a fragment which opens an Activity "MainCalendar", where I select a date in the calendar, and then I need to send this date into a fragment.
When I click on Choose Button, there is opens a MainCalendar, where user need to choose date, after that, the activity closed, and than I want to put a date from MainCalendar to the text of "Choose Button".
Add Activity with a fragment,
MainCalendar Activity:MainCalendar
MainCalendar.class:
public class MainCalendar extends AppCompatActivity {
private CalendarView Calendar;
private String date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_calendar);
Calendar = (CalendarView) findViewById(R.id.calendarView);
Calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
date = (dayOfMonth+"/"+month+"/"+year);
System.out.println(date);
Intent intent = new Intent(MainCalendar.this, Add.class);
intent.putExtra("DATE_KEY", date);
finish();
}
});
}
Add.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setSelectedItemId(R.id.add);
Button notes_button = findViewById(R.id.notes_btn);
Button tasks_button = findViewById(R.id.tasks_btn);
Button goals_button = findViewById(R.id.goals_btn);
RadioButton rb = findViewById(R.id.choose_day_btn);
String date = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
date = extras.getString("DATE_KEY");
}
AddTasksFragment frag = new AddTasksFragment();
Bundle bundle = new Bundle();
bundle.putString("DATE_KEY", date);
frag.setArguments(bundle);
Fragment fragment1 = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment1).commit();
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notes:
startActivity(new Intent(getApplicationContext(), Notes.class));
overridePendingTransition(0,0);
return true;
case R.id.add:
return true;
case R.id.tasks:
startActivity(new Intent(getApplicationContext(), Tasks.class));
overridePendingTransition(0,0);
return true;
case R.id.goals:
startActivity(new Intent(getApplicationContext(), Goals.class));
overridePendingTransition(0,0);
return true;
case R.id.statistics:
startActivity(new Intent(getApplicationContext(), Statistics.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
tasks_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
notes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddNotesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
goals_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddGoalsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
//
AddTaskFragment.class, which is in Add.class:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_tasks_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
subtask_btn = (Button) view.findViewById(R.id.add_subtask_btn);
subtask_name = (EditText) view.findViewById(R.id.subtask_name);
task_name = (EditText) view.findViewById(R.id.task_name);
lin_lay = (LinearLayout) view.findViewById(R.id.linear_layout);
sb_lay = (LinearLayout) view.findViewById(R.id.subtask_lay);
apply_btn = (Button) view.findViewById(R.id.apply_btn);
rgDay = (RadioGroup) view.findViewById(R.id.date_group);
rgPriority = (RadioGroup) view.findViewById(R.id.priority_group);
todayBtn = (RadioButton) view.findViewById(R.id.today_btn);
tomorrowBtn = (RadioButton) view.findViewById(R.id.tomorrow_btn);
chooseDayBtn = (RadioButton) view.findViewById(R.id.choose_day_btn);
lowPrBtn = (RadioButton) view.findViewById(R.id.low_btn);
mediumPrBtn = (RadioButton) view.findViewById(R.id.medium_btn);
highPrBtn = (RadioButton) view.findViewById(R.id.high_btn);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
dataBase = FirebaseDatabase.getInstance().getReference(TASKS_KEY);
this.getResources().getDisplayMetrics();
subtask_btn.setOnClickListener(this);
apply_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeTask();
}
});
chooseDayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MainCalendar.class);
startActivity(intent);
}
});
String data;
data = getActivity().getIntent().getStringExtra(DATE_KEY);
}
#Override
public void onClick(View v) {
addView();
}
private void writeTask() {
String Task;
Task = task_name.getText().toString();
dataBase.push().setValue(Task);
String[] subTasks = new String[sb_lay.getChildCount()];
for (int i = 0; i < sb_lay.getChildCount(); i++) {
View subtaskView = sb_lay.getChildAt(i);
EditText editTextName = (EditText) subtaskView.findViewById(R.id.subtask_name);
subTasks[i] = editTextName.getText().toString();
dataBase.child(Task).child("Subtasks").push().setValue(subTasks[i]);
}
dataBase.child(Task).push().setValue(getDay());
}
private String getDay(){
String day=null;
if(todayBtn.isChecked()){
Date currentTime = Calendar.getInstance().getTime();
day = currentTime.toString();
}
else if(tomorrowBtn.isChecked()){
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
day = dt.toString();
}else if(chooseDayBtn.isChecked()) {
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed ----------------------------------------------------------------------------" + day);
chooseDayBtn.setText(day);
}
return day;
}
private void addView(){
final View subtaskView = getLayoutInflater().inflate(R.layout.subtask_raw, null, false);
EditText editText = (EditText)subtaskView.findViewById(R.id.subtask_name);
ImageView imageClose = (ImageView)subtaskView.findViewById(R.id.remove_subtask);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(subtaskView);
}
});
sb_lay.addView(subtaskView);
String day;
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed " + day);
}
private void removeView(View view){
sb_lay.removeView(view);
}

As I understood, you Have to activities (Activity A and Activity B) and you have a fragment in Activity B. What you want to do is sending some data from activity A to that fragment for whatever reason.
Let's have a note first, You can't directly send data to any fragment of activity without launching it. So in order to send this data to the fragment you have to pass it from Activity A to Activity B as a first step and then send it from Activity B to the Fragment as a second step.
The type of data is very important. If you are sending a custom type (a model java class) you have to define it as Parcelable or if it is a primitive type such as int or float so you can send it directly
this is how to do it in Java
ActivityA.java
class ActivityA extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityA);
// define your data here
int data = 5;
// define an intent to send the data to the second activity
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("DATA_KEY", data);
startActivity(intent);
}
}
Then what we need to do is
receiving the data in the Activity B
Inflating the fragment
pass the data to the fragment
class ActivityB extends Activity{
Int data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityB);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
data = extras.getInt("DATA_KEY");
}
// Fragment instance
FragmentClass frag = new FragmentClass();
Bundle bundle = new Bundle();
bundle.putInt("DATA_KEY", data );
frag.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, mFeedFragment);
fragmentTransaction.commit();
}
}
and then receive it the same way we received it in the Activity B

Related

Pass data from Activity to Fragment in another Activity

I need to pass data from Activity "MainCalendar" to fragment "AddTaskFragment" in Activity "Add". I have a button in a fragment which opens an Activity "MainCalendar", where I select a date in the calendar, and then I need to send this date into a fragment.
When I click on Choose Button, there is opens a MainCalendar, where user need to choose date, after that, the activity closed, and than I want to put a date from MainCalendar to the text of "Choose Button".
MainCalendar Activity:
MainCalendar.class:
public class MainCalendar extends AppCompatActivity {
private CalendarView Calendar;
private String date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_calendar);
Calendar = (CalendarView) findViewById(R.id.calendarView);
Calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
date = (dayOfMonth+"/"+month+"/"+year);
System.out.println(date);
Intent intent = new Intent(MainCalendar.this, Add.class);
intent.putExtra("DATE_KEY", date);
finish();
}
});
}
Add.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setSelectedItemId(R.id.add);
Button notes_button = findViewById(R.id.notes_btn);
Button tasks_button = findViewById(R.id.tasks_btn);
Button goals_button = findViewById(R.id.goals_btn);
RadioButton rb = findViewById(R.id.choose_day_btn);
String date = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
date = extras.getString("DATE_KEY");
}
AddTasksFragment frag = new AddTasksFragment();
Bundle bundle = new Bundle();
bundle.putString("DATE_KEY", date);
frag.setArguments(bundle);
Fragment fragment1 = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment1).commit();
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notes:
startActivity(new Intent(getApplicationContext(), Notes.class));
overridePendingTransition(0,0);
return true;
case R.id.add:
return true;
case R.id.tasks:
startActivity(new Intent(getApplicationContext(), Tasks.class));
overridePendingTransition(0,0);
return true;
case R.id.goals:
startActivity(new Intent(getApplicationContext(), Goals.class));
overridePendingTransition(0,0);
return true;
case R.id.statistics:
startActivity(new Intent(getApplicationContext(), Statistics.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
tasks_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
notes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddNotesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
goals_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddGoalsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
//
AddTaskFragment.class, which is in Add.class:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_tasks_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
subtask_btn = (Button) view.findViewById(R.id.add_subtask_btn);
subtask_name = (EditText) view.findViewById(R.id.subtask_name);
task_name = (EditText) view.findViewById(R.id.task_name);
lin_lay = (LinearLayout) view.findViewById(R.id.linear_layout);
sb_lay = (LinearLayout) view.findViewById(R.id.subtask_lay);
apply_btn = (Button) view.findViewById(R.id.apply_btn);
rgDay = (RadioGroup) view.findViewById(R.id.date_group);
rgPriority = (RadioGroup) view.findViewById(R.id.priority_group);
todayBtn = (RadioButton) view.findViewById(R.id.today_btn);
tomorrowBtn = (RadioButton) view.findViewById(R.id.tomorrow_btn);
chooseDayBtn = (RadioButton) view.findViewById(R.id.choose_day_btn);
lowPrBtn = (RadioButton) view.findViewById(R.id.low_btn);
mediumPrBtn = (RadioButton) view.findViewById(R.id.medium_btn);
highPrBtn = (RadioButton) view.findViewById(R.id.high_btn);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
dataBase = FirebaseDatabase.getInstance().getReference(TASKS_KEY);
this.getResources().getDisplayMetrics();
subtask_btn.setOnClickListener(this);
apply_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeTask();
}
});
chooseDayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MainCalendar.class);
startActivity(intent);
}
});
String data;
data = getActivity().getIntent().getStringExtra(DATE_KEY);
}
#Override
public void onClick(View v) {
addView();
}
private void writeTask() {
String Task;
Task = task_name.getText().toString();
dataBase.push().setValue(Task);
String[] subTasks = new String[sb_lay.getChildCount()];
for (int i = 0; i < sb_lay.getChildCount(); i++) {
View subtaskView = sb_lay.getChildAt(i);
EditText editTextName = (EditText) subtaskView.findViewById(R.id.subtask_name);
subTasks[i] = editTextName.getText().toString();
dataBase.child(Task).child("Subtasks").push().setValue(subTasks[i]);
}
dataBase.child(Task).push().setValue(getDay());
}
private String getDay(){
String day=null;
if(todayBtn.isChecked()){
Date currentTime = Calendar.getInstance().getTime();
day = currentTime.toString();
}
else if(tomorrowBtn.isChecked()){
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
day = dt.toString();
}else if(chooseDayBtn.isChecked()) {
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed ----------------------------------------------------------------------------" + day);
chooseDayBtn.setText(day);
}
return day;
}
private void addView(){
final View subtaskView = getLayoutInflater().inflate(R.layout.subtask_raw, null, false);
EditText editText = (EditText)subtaskView.findViewById(R.id.subtask_name);
ImageView imageClose = (ImageView)subtaskView.findViewById(R.id.remove_subtask);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(subtaskView);
}
});
sb_lay.addView(subtaskView);
String day;
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed " + day);
}
private void removeView(View view){
sb_lay.removeView(view);
}
There are two ways to do that.
The first one is using callback and the second one is using a bundle.
In the first-way, you can create an interface and implement in your fragment and pass it to your activity. when users click the date you callback the parameter using this interface.
The second-way using bundles like this.
in your fragment create a constructor like this and call it in your activity :
public static YourFragment getInstance(obj yourParameter){
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
YourFragment fragobj = new YourFragment ();
fragobj.setArguments(bundle);
return fragobj;
}
in the onCreate method get obj in this way :
String strtext = getArguments().getString("edttext");

Problem with secondary Activity cant get data from texView (Solved -- Oleg Golomoz Answer)

Hi i have 2 Activitys in my app and i would take the data from the first activity and insert them on the second one.
Pics:
I have 2 datepickers to select date range and i save it on texView and texView2.
Code: Main Activity
selectDate = (Button) findViewById(R.id.button);
date = (TextView) findViewById(R.id.textView);
selectDate2 = (Button) findViewById(R.id.button2);
date2 = (TextView) findViewById(R.id.textView2);
selectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date.setText("Entrada: "+day + "/" + (month + 1) + "/" + year);
}
}, year, month, dayOfMonth);
datePickerDialog.show();
}
});
selectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calendar2 = calendar2.getInstance();
year2 = calendar2.get(Calendar.YEAR);
month2 = calendar2.get(Calendar.MONTH);
dayOfMonth2 = calendar2.get(Calendar.DAY_OF_MONTH);
datePickerDialog2 = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date2.setText("Salida: "+day + "/" + (month + 1) + "/" + year);
}
}, year2, month2, dayOfMonth2);
datePickerDialog2.show();
}
});
Activity2:
package com.example.mand.consumirapirest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class json extends AppCompatActivity {
TextView tvJSON;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
setTextView();
}
public void setTextView() {
tvJSON = (TextView) findViewById(R.id.tvJSON);
textView = (TextView) findViewById(R.id.textView);
String s = textView.getText().toString();
tvJSON.setText(s);
//String text = textView.getText().toString();
//return text;
}
/*public String getText()
{
}*/
}
Any idea thanks..!
Somewhere in first activity (MainActivity.java):
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// Pass some data
// Key "DATE_KEY" is static field from SecondActivity
intent.putExtra(DATE_KEY, "20.03.2019");
startActivity(intent);
}
});
And in second activity (SecondActivity.java):
public class SecondActivity extends AppCompatActivity {
static final String DATE_KEY = "DATE_KEY";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// Read passed data - String "20.03.2019"
String date = getIntent().getStringExtra(DATE_KEY);
}
}
Use startActivityForResult when calling your second activity then in your second activity use setResult to bring back selected values to first Activity:
in FirstActivity:
void openSecondActivity(){
Intent intent = Intent(context, SecondActivity.class)
startActivityForResult(intent,1004)
}
#Override
void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1004) {
if (resultCode == Activity.RESULT_OK) {
//do something with results
}
super.onActivityResult(requestCode, resultCode, data)
}
In SecondActivity:
void returnResult(String result){
Intent returnIntent = new Intent()
returnIntent.putExtra("result", result)
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
Try this
In your MainActivity
buscarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, json.class).putExtra("extra1",date.getText().toString()).putExtra("extra2",date2.getText().toString()));
}
});
In your json activity
if (getIntent().hasExtra("extra1")){
tvJSON.setText(getIntent().getStringExtra("extra1"));
}
if (getIntent().hasExtra("extra2")){
textView.setText(getIntent().getStringExtra("extra2"));
}
According to documentation.
Send data from FirstActivity:
public void sendMessage(View view) {
Intent intent = new Intent(this, SecondActivity.class);
String message = date.getText().toString();
String message2 = date2.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
intent.putExtra(EXTRA_MESSAGE_2, message2);
startActivity(intent);
}
Receive data in SecondActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE);
String message2 = intent.getStringExtra(FirstActivity.EXTRA_MESSAGE_2);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}

how to manage new FrameLayout in the second activity based onClicklistener in fragment?

I'm doing android project implementing fragment and get a trouble.
here is the trouble story:
I've created Main activity which is hold the fragment using Fragment Layout. I do this because i want to implement navigation menu using drawer menu. It works fine for all these steps.
here is the code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.layout_drawer);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(this,drawer,toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Main_fragment()).commit();
navigationView.setCheckedItem(R.id.home);
}
}
it works fine until here.
Then in the fragment activity, i triggered a Textview and invoke new activity. i do that because i want to make a new Place Holder for the fragments and put different Drawer Menu.
her is the code:
public class Main_fragment extends Fragment{
TextView t1,t2,t3,t4,t5,t6,t7;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.main_fragment,container,false);
//define buttons
t1 = (TextView) v.findViewById(R.id.txt1);
t2 = (TextView) v.findViewById(R.id.txt2);
t3 = (TextView) v.findViewById(R.id.txt3);
t4 = (TextView) v.findViewById(R.id.txt4);
t5 = (TextView) v.findViewById(R.id.txt5);
t6 = (TextView) v.findViewById(R.id.txt6);
t7 = (TextView) v.findViewById(R.id.txt7);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//intent to the second activity
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
}
});
t2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
}
});
t3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
}
});
t4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
/**
//this code just for trial fragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new Fragment_Pengurusan());
fr.commit();
**/
}
});
t5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
/**
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new Fragment_Politic());
fr.commit();
**/
}
});
t6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
/**
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new Fragment_Industri());
fr.commit();
**/
}
});
t7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), Social_Container.class);
startActivity(i);
/**
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container, new Fragment_Awam());
fr.commit();
**/
}
});
return v;
}
}
the question is, how can i triggered the fragment activity to be set on the second class place holder (FrameLayout) based onCLick that i set on the Textview that i attached in the last Fragment activity which is inside the Main Activity?
note: I didn't set anything inside the second class yet. I just want to know how to invoke the fragment inside that Second Class based onClickListener from TextView there.

Passing value of rating bar to next activity/intent

Problem: I cannot pass the rating value/data from the rating bar to another intent. It only shows me this instead of the value/data from the rating bar.
Rating: MainActivity#79b604
I think the error is that it did not properly get the value from the rating bar or it did not pass the value correctly. Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
String rating_float = "0.0";
private TextView txtRatingValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_float = String.valueOf(rating);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
CharSequence text = "";
Intent intent_rating = new Intent(this, SecondActivity.class);
intent_rating.putExtra("rating_float", toString());
startActivity(intent_rating);
return super.onOptionsItemSelected(item);
}}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView Msg;
String PassedValue = null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
PassedValue = getIntent().getStringExtra("rating_float");
Msg = (TextView) findViewById(R.id.Msg);
Msg.setText("Dimension: 479\nFormat: JPEG\nSize: 360x360\nRating: " + PassedValue);
}
Questions:
Am I doing the right way on getting the value for the rating bar?
How to pass the value/data from the rating bar into the next activity/intent and how to get it from the SecondActivity.java?
That is because you pass the result of MainActivity.toString() to your second activity
Instead of
intent_rating.putExtra("rating_float", toString());
you should presumably write
intent_rating.putExtra("rating_float", this.rating_float);
You are receiving it well but not sending what you have to.
Just use this:
intent_rating.putExtra("rating_float", rating_float);
First you need to save your value into the putExtra of the intent you use to go to the another activity
intent_rating.putExtra("rating_float", rating_float);
to get the value in the SecondActivity you just need to do this wherever you need the value.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String rating_value =(String) b.get("rating_float");
}
Simple and Clear Solution
//1stActivity
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float rating = rate.getRating();
Intent intent = new Intent(ContactActivity.this,RatingIntentSOF.class);
Bundle bundle = new Bundle();
bundle.putFloat("totalRating",rating);
intent.putExtras(bundle);
startActivity(intent);
//2nd Activity, get the data of 1st Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating_intent_sof);
TextView textView = (TextView) findViewById(R.id.text);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
float totalRating = bundle.getFloat("totalRating");
textView.setText(String.valueOf(totalRating));
}

How to update image in fragment when selecting an image in an Activity?

Hello I'm trying to select an Image in an activity page and that selected image to update in my Fragment page. I've tried what I've learnt previously, but it's not working at all. Below is what I've attempted. I'm still new to android development, so please bear with me.
ProfileSettingsActivity.java:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
profileImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Below is the Fragment that contains the page I start on from and go to the ProfileSettingsActivity page
PeopleFragment.java:
public class PeopleFragment extends Fragment {
ImageButton settingsButton;
PieChart pieChart;
ImageButton profileImage;
private FirebaseAuth mAuth;
TextView fullName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_people2, container,
false);
profileImage = (ImageButton) view.findViewById(R.id.imageButton4);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
getActivity().startActivityForResult(settingsClick,0);
}
});
fullName = (TextView) view.findViewById(R.id.userProfileFullName);
mAuth = FirebaseAuth.getInstance();
return view;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
/**
* Updates the view according to the authentication status.
* #param user the current FirebaseUser
*/
private void updateUI(FirebaseUser user) {
if (user != null) {
fullName.setText(user.getDisplayName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) return;
//Getting the Avatar Image we show to our users
ImageView avatarImage =
(ImageView)getView().findViewById(R.id.imageButton4);
//Figuring out the correct image
String drawableName = "profile1";
switch (data.getIntExtra("imageID",R.id.teamid00)) {
case R.id.teamid00:
drawableName = "profile1";
break;
case R.id.teamid01:
drawableName = "profile2";
break;
case R.id.teamid02:
drawableName = "profile3";
break;
case R.id.teamid03:
drawableName = "profile4";
break;
case R.id.teamid04:
drawableName = "profile5";
break;
case R.id.teamid05:
drawableName = "profile6";
break;
default:
drawableName = "profile1";
break;
}
int resID = getResources().getIdentifier(drawableName, "drawable",
getActivity().getPackageName());
avatarImage.setImageResource(resID);
}
}
Currently with what I have above, I can move from the fragment page to the activity page and I can press on the buttons to select the images and then the activity closes for me. But when I'm back on the fragment page, the profile image isn't updated at all, and displays the default one.
Try to use startActivityForResult() instead of getActivity().startActivityForResult(). So, change your Fragment code to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
startActivityForResult(settingsClick,0);
}
});
...
return view;
}
Note: This is not related to your problem.
You can simplify you activity code to this:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
};
profileImage1.setOnClickListener(clickListener);
profileImage2.setOnClickListener(clickListener);
profileImage3.setOnClickListener(clickListener);
profileImage4.setOnClickListener(clickListener);
profileImage5.setOnClickListener(clickListener);
profileImage6.setOnClickListener(clickListener);
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Probably you've got some problems with your onActivityResult method. Check these answers.
Also there is a solution that is going to work:
1. Tag your fragments when you create them:
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.main_layout, new PeopleFragment(), "PeopleFragmentTag"));
fTrans.commit();
2. Write method in PeopleFragment, which could setImage:
public void updateProfileImage(int profileImgID){
/* Update your image here */
}
3. Get a fragment by tag and call the method:
public void setProfilePicture(View view) {
/* Your code */
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentByTag("PeopleFragmentTag");
peopleFragment.updateProfileImage(selectedImage.getId());
}
Hope, I helped you somehow. Good luck!

Categories