将数据从Activity传递到Fragment不起作用

时间:2015-11-19 04:26:02

标签: java android android-fragments

我一直在做一个需要个人资料页面的应用。登录是一个活动,配置文件页面是片段。每当我进行传递时,它总是返回null。

这是我的MainActivity.java

public class MainActivity extends Activity {

 ConnectionClass connectionClass;
 EditText edtuserid,edtpass;
 Button btnlogin;
 ProgressBar pbbar;

 public int test2;
 public String test3 = "";
 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;
 int userIDD;

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

 edtuserid.setText(test3);

 btnlogin.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
     userid = edtuserid.getText().toString();
     password = edtpass.getText().toString();
 DoLogin doLogin = new DoLogin();
 doLogin.execute("");

 }
 });
 }
 public class DoLogin extends AsyncTask<String,String,String>
 {
int b;   
 String z = "";
 Boolean isSuccess = false;
 @Override
 public void onPreExecute() {
 pbbar.setVisibility(View.VISIBLE);
 }
 @Override
 public void onPostExecute(String r) {
 pbbar.setVisibility(View.GONE);

 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.getInt(1);

        Bundle profileBundle = new Bundle();
        profileBundle.putInt("userID", userIDD);


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


     z = "The ID is " + userIDD;

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


 }

    public String getMyData() {

        String test4 = test3;
        return test4;

 }



}

在片段中,我将数据检索为:

PathfinderAdd.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;
    int userID = 0;
    int user = 0;


    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 = "";


        //String userId = ((MainActivity)getActivity()).IDD;



        MainActivity getID = new MainActivity();
        String IDD = getID.getMyData();
        Toast.makeText(PathfinderAdd.this.getActivity(), IDD, Toast.LENGTH_SHORT).show();

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


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

        }

}

问题是无论何时执行此代码,我都会得到一个空值。我也尝试将它分配给一个方法,但它仍然返回null。

3 个答案:

答案 0 :(得分:1)

你必须使用相同的对象去片段。我认为你使用了另一个片段对象进行交易,这就是为什么它显示为空。

它必须有点像这样

--recursive

答案 1 :(得分:0)

如果您使用静态片段,setArguments()根本无法工作。在beginTransaction()中执行fragmentManager之前,您需要为事务设置参数。如果你在那之后再做,那么setArguments()也不会工作

答案 2 :(得分:0)

您也可以在不将数据传递给片段的情况下执行此操作。您可以直接从主Activity中获取数据。在您的主要活动中,只需执行此操作。

 if(rs.next())
 {
   userIDD = rs.getInt(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);
 }

然后在你的片段中得到这样的值:

userId = ((YourActivity)getActivity()).userIDD;

确保您的变量是全球活动。