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

时间:2015-11-18 16:30:02

标签: java android android-fragments

我尝试过使用下面的代码,但它不起作用。它只是在从片段中检索时返回一个空值。

MainActivity.java

设置捆绑包:

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

将片段放入片段

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

    }

}

2 个答案:

答案 0 :(得分:0)

您正在将分区设置为片段,但是您在哪里替换/添加片段?我看不到任何FragmentTransaction。

这里有一些例子:http://developer.android.com/reference/android/app/Fragment.html

如果我没错,

“DetailsActivity”就是你所需要的。

示例:

如果您想从活动中启动片段:

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

其中android.R.id.content是Fragments的容器。当你这样做时,你的片段将被显示,并且将收到Bundle。

在你的片段“onCreate”中:

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

答案 1 :(得分:0)

您可以在活动中调用此片段来添加或替换片段

   // 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();

更多碎片信息检查此http://developer.android.com/guide/components/fragments.html

要从您的活动中获取数据,您可以在活动中创建方法

   public dataType getData() {
       return data;
   }
在您的片段中,您可以通过调用

来获取数据
   ((YourActivityClass) getActivity()).getData();

希望这有帮助!!