How to pass data from activity to fragment? - android-studio

I'm creating a basic app and i stucked at this point where I'm unable to pass data from an activity to fragment.
EmailPage.java
public class EmailPage extends AppCompatActivity{
ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emailpage);
btn = (ImageButton) findViewById(R.id.emailButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(EmailPage.this, YourName.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
});
}
}
Email Page
NavHeaderMainMenu1.java
public class NavHeaderMainMenu1 extends Fragment {
public NavHeaderMainMenu1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.nav_header_main_menu1, container , false);
}
}
NavHeaderMainMenu1

Related

Step Counter in Android Studio doesn't count steps

I have a problem with an app I'm trying to develop in Android Studio. I'm trying to develop a step counter using the STEP_COUNTER sensor in a Fragment.I decided to show my results in a TextView ('mStepsSinceReboot'), but it keeps being empty. Do you have any idea on how to make it work?
An hypotesis is that I should use a Service, but online I only found implementations that don't require it.
Thanks in advance for your answer. This is the code of my Fragment.
public class StepFragment extends Fragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounter;
private boolean isSensorPresent;
private TextView mStepsSinceReboot;
public StepFragment() {
// Required empty public constructor
}
public static StepFragment newInstance(String param1, String param2) {
StepFragment fragment = new StepFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_step, container, false);
mStepsSinceReboot=v.findViewById(R.id.stepssincereboot);
mSensorManager=(SensorManager) this.getActivity().getSystemService(getContext().SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
mStepCounter=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
isSensorPresent=true;
}
else{
isSensorPresent=false;
}
return v;
}
#Override
public void onSensorChanged(SensorEvent event) {
mStepsSinceReboot.setText(("Steps since reboot: "+String.valueOf(event.values[0])));
Log.d("Passi", String.valueOf(mStepsSinceReboot));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onResume(){
super.onResume();
if(isSensorPresent){
mSensorManager.registerListener(this,mStepCounter,SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public void onPause(){
super.onPause();
if(isSensorPresent){
mSensorManager.unregisterListener(this);
}
}
#Override
public void onDestroy(){
super.onDestroy();
mSensorManager=null;
mStepCounter=null;
}
}
you added the permission in the manifest file ?
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

How to edit a TextView in a fragment from MainActivity

I have a textview in a fragment that I want to edit in MainActivity.java (The parent activity). I've tried many methods such as creating a function in the fragment code:
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
public void status(String txt){
TextView textView = getView().findViewById(R.id.status_message);
textView.setText(txt);
}
}
and calling it in MainActivity like so:
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeFragment fragment = new HomeFragment();
fragment.status("Test");
}
}
But this results in the app crashing. How can I fix this? I am using the Bottom Navigation Activity Template.
Best thing I would advice is to create your fragment instance in your main activity like this:
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeFragment fragment =
HomeFragment.createInstance("Test");
}
}
And then in your fragment:
public class HomeFragment extends Fragment {
private string text;
public View onCreateView(#NonNull LayoutInflater
inflater, ViewGroup container, Bundle
savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home,
container, false);
TextView textView =
root.findViewById(R.id.status_message);
return root;
}
public static HomeFragment createInstance(String text)
{
HomeFragment f =new HomeFragment ();
Bundle bundle=new Bundle();
bundle.putString("key", text);
f.set arguments(bundle);
return f;
}
#Override
public void onCreate(#Nullable Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments != null) {
text= getArguments.getString("key");
status(text);
}
}
public void status(String txt){
textView.setText(txt);
}
}
Hopes this helps
Fixed this by accessing MainActivity from the fragment rather than accessing Fragment from MainActivity. Instead of changing the textview from MainActivity, send the string you want to put in the textview through a method and change the textview in the fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity{
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String sendData(){
return text;
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
TextView tv;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
tv = root.findViewById(R.id.textview);
MainActivity ma = (MainActivity)getActivity();
tv.setText(ma.sendData());
return root;
}
}

How to add PreferenceActivity to fragment activity

I have a class Fragment1 1) and I want to extend also PreferenceActivity to add 2) so as to include in my fragment 1) a menu preference.any ideas on how to implement it
1.
public class Fragment1 extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
if(container == null){
return null;
}
return inflater.inflate(R.layout.fragment_main1, container, false);
}
}
2)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pred_general);

How to implement onActivityResult within RecyclerView Fragment

I am trying to have a button within a Tab which is part of an activity for uploading images, when clicking the button inside one of the 2 Tabs presented in the activity ( Tab 1 pics, Tab 2 Vid ) the user could choose an image from the device.
My problem is implemneting the onClick Listener and onActivityResult which is not being used when placed after onClick, plus the #Override is being underlined as an error.
I guess i am not implementing the onClick the right way and not sure how to activate onActivityResult the proper way, i would appreciate any guidance;
MainActivty;
public class upload extends AppCompatActivity {
public String UserID;
private static final int REQUEST_SIGNUP = 0;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Firebase.setAndroidContext(this);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new UploadPictures(), "Pictures");
adapter.addFragment(new UploadVideos(), "Videos");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And here is the Fragment Code;
public class UploadPictures extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView picture;
public EditText tagEditText;
public Button tagCurLoc, choosePic, uploadContent;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.pictue_upload, parent, false));
picture = (ImageView) itemView.findViewById(R.id.imgToUpload);
tagEditText = (EditText) itemView.findViewById(R.id.tagEditText);
tagCurLoc = (Button) itemView.findViewById(R.id.tagCurLoc);
choosePic = (Button) itemView.findViewById(R.id.choosePic);
choosePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
onActivityResult(requestCode, resultCode, data);
Toast.makeText(getActivity().getApplicationContext(), "Canceled ", Toast.LENGTH_SHORT).show();
} else {
if (requestCode == RESULT_LOAD_IMAGE) {
Uri selectedImgPath = data.getData();
picture.setImageURI(selectedImgPath);
RealFilePath = Uri.parse(String.valueOf(selectedImgPath));
Toast.makeText(getActivity().getApplicationContext(), " " + RealFilePath, Toast.LENGTH_SHORT).show();
}
}
}
});
uploadContent = (Button) itemView.findViewById(R.id.uploadContent);
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private Context mContext;
public ContentAdapter(Context context) {
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return LENGTH;
}
}
Not sure if the onClick listener for the button should be implemented in the Adapter or the View holder, and from there the issue of onActivityResult cant be used ?
Weel, solved after some more reading and few try outs.
The onClick listener should be implemented at the ViewHolder class followed by
#Override
onActivityResult.
within the onClickListener onActivityResult invoked by;
startActivityForResult(intent, RESULT_LOAD_IMAGE);
and within onActivityResult;
onActivityResult(requestCode, resultCode, data);
Considering all of this taking place in an activity extending Fragment.

ActionBar.Tablistener deprecated

I'm trying to build a swipe tabs view by using fragment activity and actionbar.tablistener. I have referenced other people tutorial and do it, however, it keep on deprecated and do not successful run it. Then I changed to AppComBatActivity and it do not works, show viewgroup error which I don't know why. THen I changed to ActionBarActivity, it worked finally, but no matter how I edit my tab activity, in java class and xml too, it does not show anything.
I have actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) deprecated as well.
I have attached my code as following...
fragmentmenu.class
public class FragmentMenu extends FragmentActivity implements ActionBar.TabListener {
ActionBar actionBar;
ViewPager viewPager;
FragmentPageAdapter ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_menu);
viewPager = (ViewPager)findViewById(R.id.pager);
ft = new FragmentPageAdapter(getSupportFragmentManager());
actionBar = getActionBar();
viewPager.setAdapter(ft);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Menu").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Report").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Setting").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}
</code>
FragmentPagerAdapter
<code>
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new MyActivity();
case 1:
return new Report();
case 2:
return new Setting();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
</code>
One of the fragment
<code>
public class Report extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.report, container, false);
}
}
}}
Please help!
ActionBar.Tablistener is deprecated. You need to use the TabLayout instead.
Check this tutorial for more infos :
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

Resources