简体   繁体   中英

How do I pass a variable from an activity to a fragment?

I have tried using the code below but it does not work. it just returns a null value when retrieved from the fragment.

MainActivity.java

setting the bundle:

public class MainActivity extends Activity {
 ConnectionClass connectionClass;
 EditText edtuserid,edtpass;
 Button btnlogin;
 ProgressBar pbbar;

 int user_id;
 int lala;
 int test2;
 String userIDD;
 String user_fname;
 String user_lname;
 int dept_id;
 String test;
 String user_email;
 String user_password;
 String user_username;
 Bundle profileBundle;
 String userid;
 String password;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 connectionClass = new ConnectionClass();
 edtuserid = (EditText) findViewById(R.id.edtuserid);
 edtpass = (EditText) findViewById(R.id.edtpass);
 btnlogin = (Button) findViewById(R.id.btnlogin);
 pbbar = (ProgressBar) findViewById(R.id.pbbar);
 pbbar.setVisibility(View.GONE);

 btnlogin.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 userid = edtuserid.getText().toString();
 password = edtpass.getText().toString();
 int lala = Integer.parseInt(userid);
 test2 = lala;
 DoLogin doLogin = new DoLogin();
 doLogin.execute("");
 }
 });
 }
 public class DoLogin extends AsyncTask<String,String,String>
 {

 String z = "";
 Boolean isSuccess = false;
 @Override
 protected void onPreExecute() {
 pbbar.setVisibility(View.VISIBLE);
 }
 @Override
 protected void onPostExecute(String r) {
 pbbar.setVisibility(View.GONE);

 Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
 if(isSuccess) {
     //DITO ANG REDIRECTION
     Intent base = new Intent(MainActivity.this, OtherActivity.class);

     startActivity(base);
     finish();
 }
 }
 @Override
 public String doInBackground(String... params) {

 if(userid.trim().equals("")|| password.trim().equals(""))
 z = "Please enter User Id and Password";
 else
 {
 try {
 Connection con = connectionClass.CONN();
 if (con == null) {
 z = "Error in connection with SQL server";
 } else {
 String query = "select user_id, user_fname, user_lname,department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
 Statement stmt = con.createStatement();
 ResultSet rs = stmt.executeQuery(query);
 if(rs.next())
 {
    userIDD = rs.getString(1);
    user_fname = rs.getString(2);
    user_lname = rs.getString(3);
    dept_id = rs.getInt(4);
    user_email = rs.getString(5);
    user_password = rs.getString(6);
    user_username = rs.getString(7);
    profileBundle = new Bundle();
    profileBundle.putInt("userID", user_id);
    profileBundle.putInt("deptID", dept_id);
    profileBundle.putString("fname", user_fname);
    profileBundle.putString("lname", user_lname);
    profileBundle.putString("email", user_email);
    profileBundle.putString("pass", user_password);

    Fragment fragobj=new PathfinderAdd();
    fragobj.setArguments(profileBundle);

    //Fragment fragobj = new PathfinderAdd();
    //fragobj.setArguments(profileBundle);

 z = "Logged In as: " + user_username;

 isSuccess=true;
}
 else
 {
 z = "Invalid Credentials";
 isSuccess = false;
 }
 }
 }
 catch (Exception ex)
 {
 isSuccess = false;
 Log.e("MYAPP", "exception", ex);
 z = "Error Somewhere";
 }
 }
 return z;
 }


 }
public int getMyData() {
    int wa = lala;
 return wa;
 }
}

PahtfinderAdd.java

getting the bundle in the fragment

public class PathfinderAdd extends Fragment {

ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;

String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
Integer userID;
int user;

public PathfinderAdd(){}

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


    View rootView = inflater.inflate(R.layout.addpathfinder, container, false); 


    connectionClass = new ConnectionClass();
    edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
    edtbenefit = (EditText)  rootView.findViewById(R.id.edtbenefit);
    edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
    edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
    targetdate = (EditText) rootView.findViewById(R.id.target);
    spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
    spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
    btnadd = (Button)  rootView.findViewById(R.id.btnadd);
    pbbar = (ProgressBar)  rootView.findViewById(R.id.pbbar);
    targettv = (TextView) rootView.findViewById(R.id.tvtarget);
    pbbar.setVisibility(View.GONE);
    calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
    proid = "";


    userID = getArguments().getInt("userID");
    Bundle bundle = this.getArguments();
    user = bundle.getInt("userID");

    //String lol = new getMyData().





    btnadd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AddPro addPro = new AddPro();

            addPro.execute("");

        }
    });

    calendar.setOnDateChangeListener(new OnDateChangeListener() {


        public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
                int dayOfMonth) {

            int day = dayOfMonth;
            int month = month_date;
            int year = year_date;

            DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);





        }
    });






    return rootView;

}


public class AddPro extends AsyncTask<String, String, String> {



    String z = "";
    Boolean isSuccess = false;

    String observation = edtobservation.getText().toString();
    String quickwin = edtquickwin.getText().toString();
    String ideaname = edtideaname.getText().toString();
    String benefit = edtbenefit.getText().toString();
    String target_date = targetdate.getText().toString();





    String process = spinner1.getSelectedItem().toString();
    String benefitType = spinner2.getSelectedItem().toString();
    String lol = "2015-11-28";

    Integer benefit_type = spinner2.getSelectedItemPosition();
    Integer idea_type = spinner1.getSelectedItemPosition();
    Integer idea_id;
    Integer benefit_id;

    Integer pathfinder_id = 1;
    Integer pathfinder_status = 9;
    Integer pathfinder_prog = 0;

    @Override
    protected void onPreExecute() {
        pbbar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPostExecute(String r) {
        pbbar.setVisibility(View.GONE);
        Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
        if(isSuccess==true) {
            edtideaname.setText(null);
            edtbenefit.setText(null);
            edtobservation.setText(null);
            edtquickwin.setText(null);
            targetdate.setText(null);
        }

    }

    @Override
    protected String doInBackground(String... params) {
        if (ideaname.trim().equals("") || benefit.isEmpty()  || observation.trim().equals("") || quickwin.trim().equals(""))
            z = "Please fill all the fields";
        else {
            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                    z = "Error in connection with SQL server";
                } else {

                    //timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
                    //finalDate = timeFormat.format(targ);

                    //sql = new java.sql.Date(targ.getTime());

                    int lol=1;


                     double benefitInt = Double.parseDouble(benefit);
                    date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);

                    String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);

                    DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
                    Date date3 = format2.parse(newDateString);

                    java.sql.Date finalDt = new java.sql.Date(date3.getTime());  




                    String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
                    .format(Calendar.getInstance().getTime());

                    //String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
                    //.format(calendar.getDate());


                    switch (idea_type)
                    {
                    case 0:
                        idea_id = 1;
                        break;
                    case 1:
                        idea_id = 2;
                        break;
                    case 2:
                        idea_id = 3;
                        break;
                    case 3:
                        idea_id = 4;
                        break;
                    case 4:
                        idea_id = 5;
                        break;
                    default:
                        idea_id = 1;
                        break;
                    }

                    switch(benefit_type)
                    {
                    case 0:
                        benefit_id = 1;
                        break;
                    case 1:
                        benefit_id = 2;
                        break;
                    default:
                        benefit_id = 1;
                        break;
                    }

                    String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" + 
                            "values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";                                            
                    PreparedStatement preparedStatement = con.prepareStatement(query);
                    preparedStatement.executeUpdate();
                    z = "Added Successfully";
                    isSuccess = true;
                }
            } catch (Exception ex) {
                isSuccess = false;
                z = "Exceptions";
                Log.e("MYAPP", "exception", ex);
            }
        }
        return z;
    }

    }

}

You are setting the Bundle to the Fragment, but where are you replacing/adding the Fragment? I can't see any FragmentTransaction.

Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html

"DetailsActivity" is what you need, if I'm not wrong.

Example:

When you want to start your Fragment from the Activity:

Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
getFragmentManager().beginTransaction().add(android.R.id.content, fragobj).commit();

Where android.R.id.content is the container for your Fragments. When you do this your Fragment will be shown and the Bundle will be received.

In your Fragment "onCreate":

   if (getArguments() != null) {
        Bundle bundle = this.getArguments();
        user = bundle.getInt("userID");
   }

You can add or replace Fragment by calling this in your activity

   // Create new fragment and transaction
   Fragment newFragment = new ExampleFragment();
   FragmentTransaction transaction = getFragmentManager().beginTransaction();

   // Replace whatever is in the fragment_container view with this fragment,
   // and add the transaction to the back stack
   transaction.replace(R.id.fragment_container, newFragment);
   transaction.addToBackStack(null);

   // Commit the transaction
   transaction.commit();

more Fragment information check this http://developer.android.com/guide/components/fragments.html

To get data from you activity you can create a method in your activity

   public dataType getData() {
       return data;
   }

in your fragment, you can get data by calling

   ((YourActivityClass) getActivity()).getData();

Hope this help!!

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