简体   繁体   中英

Passing values from main activity to another fragment

This is my Main Activity.class file . It contains a navigation drawer where i am using a login section. In the login fragment if the user log in successfully then an int flag is set to 1. which I am receiving here. Now I want to send this value to the services fragment. But I am unable to understand how to do so. MainActivity.class

package net.simplifiedcoding.navigationdrawerexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //add this line to display menu1 when the activity is loaded
    displaySelectedScreen(R.id.nav_menu1);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void displaySelectedScreen(int itemId) {

    //creating fragment object
    Fragment fragment = null;
    String auth= getIntent().getStringExtra("authentication");

    //initializing the fragment object which is selected
    switch (itemId) {
        case R.id.nav_menu1:

            fragment = new Services(auth);
            break;
        case R.id.nav_menu2:
            fragment = new Login();
            break;
        case R.id.nav_share:
            fragment = new Share();
            break;
        case R.id.nav_rate:
            fragment = new Rate();
            break;


    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}


@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    //calling the method displayselectedscreen and passing the id of selected menu
    displaySelectedScreen(item.getItemId());
    //make this method blank
    return true;
}
}

Services.class

package net.simplifiedcoding.navigationdrawerexample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;




public class Services extends Fragment {
String itemValue;

public Services(String auth) {

}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    return inflater.inflate(R.layout.fragment_services, container, false);
}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("Our Services");
    final ListView listView = (ListView) view.findViewById(R.id.listView);
    String[] values = new String[]{"Allergist", "Cardiologist", "Dermatologist","Endocrinologist","Gastroenterologists","Neurologist","OBGYN","Oncologists","Ophthalmologists","Pediatrician","Psychologist"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int itemPosition=position;
            itemValue= (String) listView.getItemAtPosition(position);
            Intent intent= new Intent((Context)getContext(),Doctor.class);
            startActivity(intent);
        }
    });


}


}

It is saying the error as Avoid non default constructors in fragments. Use Fragment#setArguments(Bundle) instead. Please help guys. I am a novice in android app development.

From Activity you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Also You can access activity data from fragment:

Activity:

public class MyActivity extends Activity {

    private String myString = "hello";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        ...
    }

    public String getMyData() {
        return myString;
    }
}

Fragment:

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        MyActivity activity = (MyActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
        return view;
    }
}

Use following flow

Bundle bundle = new Bundle(); //declare global

case R.id.nav_menu1:

        fragment = new Services(auth);           
        bundle.putString("value", "3");// use from static variable  in activity 

        break;

then

   if (fragment != null) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.setArguments(bundle);
    ft.commit();}    }

then fragment get

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
String value = getArguments().getString("value");    // you can get 3
return inflater.inflate(R.layout.fragment, container, false);
 }

In Activity, your create:

public String myData;

myData = "YourData";

public String getData(){

return myData;

}

In Fragment:

MainActivity activity = (MainActivity)getActivity;

String b = activity.getData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM