简体   繁体   English

如何将变量从活动传递到片段?

[英]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 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 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? 您正在将Bundle设置为Fragment,但是要在哪里替换/添加Fragment? I can't see any FragmentTransaction. 我看不到任何FragmentTransaction。

Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html 这里有一些示例: http : //developer.android.com/reference/android/app/Fragment.html

"DetailsActivity" is what you need, if I'm not wrong. 如果我没有记错的话,“ DetailsActivity”是您所需要的。

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. 其中android.R.id.content是片段的容器。 When you do this your Fragment will be shown and the Bundle will be received. 当您执行此操作时,将显示您的片段并收到捆绑包。

In your Fragment "onCreate": 在您的片段“ onCreate”中:

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

You can add or replace Fragment by calling this in your activity 您可以通过在活动中调用Fragment来添加或替换Fragment

   // 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 更多片段信息,请查看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!! 希望这个帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在android中将数据从活动传递到片段 - How do I pass data from activity to fragment in android 如何将变量从活动传递到片段? 我对流行的解决方案有疑问 - How to pass variable from activity to fragment? I have problem with popular solutions 如何将变量从活动传递到片段不能解决所有先前的问题 - How to pass variable from activity to fragment not working all of previous question 如何将“主活动”中的布尔值传递给片段? - How do I pass a boolean value from my Main Activity to a fragment? Android Studio - 如何在不使用按钮的情况下将数据从活动传递到片段 - Android Studio - How do I pass data from an activity to a fragment without using a button 将活动中的变量传递到活动片段 - Pass variable in activity to activity fragment 如何通过清单 <Model> 从活动到片段 - How can I pass List<Model> from Activity to Fragment 如何将 Activity 中的参数传递给 Fragment 中的 function - how can I pass parameter from Activity to function in Fragment 从活动获取变量的值并将其传递给片段活动 - Get value of variable from activity and pass it to fragment activity 如何在第一个Activity中收到的sqlite查询中传递整数变量? - How do I pass integer variable in sqlite query which I receive from first Activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM