如何将对象从活动访问到片段?

时间:2016-06-14 05:50:43

标签: java android android-fragments

我想将一个对象从一个活动传递给一个片段。我的活动有一个标签布局,包括视图寻呼机和四个片段。

我在活动中有一个对象,我想在所有片段中访问它。

我尝试在activity中创建一个getMethod然后访问fragment中的对象。但它无法正常工作,我将对象作为null的所有方式。

的活动:

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setTitle("Profile");

    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);


    setSupportActionBar(toolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            finish();

        }
    });

    GetProfileAsyncTask task = new GetProfileAsyncTask(ProfileActivity.this,this,profile);

   // task.setTaskCompletedListener(this);

    task.execute("sid");

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),mTitles,mNumbOfTabs);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager)findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
    mTabs.setDistributeEvenly(true);
    mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tab_scroll_color);
        }
    });
    mTabs.setViewPager( mViewPager);


}


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

public JSONObject getProfile(){
    return this.profile;
}
@Override
public void doInBackground() {

}

@Override
public void doPostExecute(JSONObject response) {
    profile = response;
    Toast.makeText(ProfileActivity.this,
            "Finish", Toast.LENGTH_LONG).show();
}

我想将配置文件对象传递给片段。

片段:

public class BasicInformationFragment extends android.support.v4.app.Fragment{

    EditText email,pass,mobile,code;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;
    JSONObject profile;
    String userUsername,password,mobileNumber,emailId;
    private ProfileActivity myActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_basic_information,
                container, false);
      //  try{



    ((ProfileActivity)getActivity()).getProfile();

          //  password = profile.getString("userPassword");
         //   mobileNumber = profile.getString("userMobileNo");
         //   emailId = profile.getString("userEmailid");



            email = (EditText) view.findViewById(R.id.edt_email);
            pass = (EditText) view.findViewById(R.id.edt_pass);
            mobile = (EditText) view.findViewById(R.id.edt_mobile);
            code = (EditText) view.findViewById(R.id.edt_code);


         //   email.setText(emailId);
         //   pass.setText(password);
          //  mobile.setText(mobileNumber);


       // }


     //   catch (JSONException e)
     //   {}
        return view;
    }

这里出了什么问题?请帮忙。谢谢..

基本上我想访问Fragment中的Activity对象。如果有其他方法让我知道。感谢

6 个答案:

答案 0 :(得分:0)

覆盖onAttched()方法在一段时间内给它的活动对象getActivity()方法给出活动的空引用。

<Route path="settings/online-order" component={OnlineOrderComponent}/>
<Route path="settings/online-order?status=complete" onEnter={/*do something here*/}/>

答案 1 :(得分:0)

为JSON Object创建一个单独的公共类。并从主活动中分配值self..i.e,

public class Common{
    public static JSONObject commonprofileobject;
}

然后从活动中分配价值.. Common.commonprofileobject=XXXX; 然后你可以从片段

访问它

答案 2 :(得分:0)

我认为你在这个AsyncTask之前尝试使用profile对象(下面是         一段代码)返回。你可以做的一件事就是使用回调         当asnyctask返回时,Activity将通知您的片段。

task.setTaskCompletedListener(new GetProfileAsyncTask.OnTaskCompleted() {
    public void onTaskCompleted(JSONObject response) {

        profile = response;

    }
});

有关详细信息,请访问此link,或者您也可以参考已批准的答案here

答案 3 :(得分:0)

为什么要在Activity中运行Async Task。意味着您也可以在Fragment中运行Async Task。并从片段回调中获取结果。

答案 4 :(得分:0)

为此在项目中添加一个basefragment类,并从basefragment类扩展你的片段

public class BaseFragment extends Fragment{

private Activity activity;
public ProgressDialog prog = null;

private MainActivity parent;
private final String TAG = "";//MainActivity.class.getName().toString();

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity = activity;
    setParent(getHomeActivity());
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void onStart() {
    super.onStart();
}

@Override
public void onStop() {
    super.onStop();
}

public MainActivity getHomeActivity() {
    try {
        return (MainActivity) activity;
    } catch (Exception ex) {
        return null;
    }
}

public MainActivity getParent() {
    return parent;
}
public void setParent(MainActivity parent) {
    this.parent = parent;
}
}

例如像这样扩展片段并使用片段中的getparent方法从mainactivity访问您的对象

public class BasicInformationFragment extends BaseFragment {

EditText email, pass, mobile, code;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
JSONObject profile;
String userUsername, password, mobileNumber, emailId;
private ProfileActivity myActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getParent().yourobjectnametoaccess;

}
}

答案 5 :(得分:0)

在您的&#39; ProfileActivity&#39;中创建活动的静态实例类

public static ProfileActivity instance;

public static ProfileActivity getInstance() {
    if (instance == null) {
        instance = new ProfileActivity ();
    }
    return instance;
}

然后编写具有JSON对象的方法

public JSONObject getProfile(){
return this.profile;
}

现在在你的片段里面&#39; onCreateView&#39;您可以直接访问JSON对象的方法&#39; getProfile&#39;方法跟随方式

JSONObject profileObj = ProfileActivity .getInstance().getProfile();

我希望这会对你有所帮助。