将数据从活动传递到可滑动视图片段

时间:2014-06-19 15:47:56

标签: java android listview android-fragments tabs

好的,我是android编程的新手,这是我的问题。我有一个异步任务,它在httpget请求中从服务器收集json数据,并在可滑动视图中更新listview片段。我想要一种方法将数据(一串字符串)从主TabActivity类发送到Tab1Fragment类。

我已经完成了将代码拆分为基本要素的最佳水平。

注意:我已经尝试过在其他类似问题中读过的bundle方法,但是它们最终都会在片段中抛出NULL指针异常,这意味着bundle没有被发送。(?)

这是我的主要标签活动:

 TabActivity.java
public class TabActivity extends ActionBarActivity  implements ActionBar.TabListener {
private String phoneno;
private static String url = "http://my/url/forjson";

//JSON Node Names 
private static final String TAG_OPERATOR = "operator";
private static final String TAG_REGNO = "Reg No";

public String  operator;
public String regNo;


private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Details", "Others"};
Bundle bundle = new Bundle();

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

        Intent intent = getIntent();
    phoneno = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
    new JSONParse().execute();

    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getSupportActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

/*Private Class to parse JSON*/
private class JSONParse extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(TabActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @SuppressWarnings("finally")
    @Override
        protected JSONObject doInBackground(String... args) {

    //*     
    JSONParser jParser = new JSONParser();

        // Getting JSON from URL    
        StringBuilder finalUrl = new StringBuilder();
        JSONObject jsonForData = new JSONObject();
        try{
        finalUrl.append(url);
        jsonForData = jParser.getJSONFromUrl(finalUrl.toString());

        }catch (JSONException e) {
              e.printStackTrace();
            }
        return jsonForData;
      }

       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {

            Bundle bundle=new Bundle();
            bundle.putString("oper", json.getString(TAG_OPERATOR));
            bundle.putString("regNo", json.getString(TAG_REGNO));

            mAdapter.getData(bundle);

        } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
 }

在上面的代码中,请理解我实例化的JSONPasrser类从url返回一个JSONObject并且它可以工作。所以,那里没有问题。

此外,我的片段类是listview,如下所示:

Tab1Fragment.java

public class Tab1Fragment extends ListFragment{

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
        String abc = "No Details Presently Available";

        //Fill all string values with something
        String[] values = new String[2];
        for(int i=0;i<values.length;i++)
            values[i] = " ";
        //Make Sure number of elements match
        try{
        values[0] = "Provider: " +  getArguments().getString("oper");//Gives a NULL value
        values[1] = "No: " + +  getArguments().getString("regNo");//Gives a NULL value

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1,values);
        // Assign adapter to ListView
        setListAdapter(adapter); 
        }
        catch(Exception e){
            e.printStackTrace();
            Log.w("Error","The App didn't have enough elements specified to populate the listview");
        }
        return rootView;
    }
 }

我已经硬编码的“abc”字符串理想情况下应该包含从TabActivity类发送的详细信息。

我希望上面的片段从TabActivity类接收数据以填充listview。任何帮助表示赞赏:)

编辑:我已根据非法参数的建议更改了适配器类,如下所示。

所以现在,捆绑包作为TabActivity-&gt; TabsPagerAdapter-&gt; Tab1Fragment传递 但仍然返回NULL值。

我的Adapter类现在如下:

  TabsPagerAdapter.java
 public class TabsPagerAdapter extends FragmentStatePagerAdapter {
 Bundle bundle = new Bundle();

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        Fragment fragment = new Tab1Fragment();

        this.bundle.putString("operator", "hi");
        fragment.setArguments(this.bundle);
        return fragment;
    case 1:
        return new Tab2Fragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 2;
}

public void getData(Bundle bundle){
    this.bundle = bundle;
}

}

1 个答案:

答案 0 :(得分:1)

我可以看到您已成功通过捆绑包传递数据。请删除它。来自您的代码:

this.bundle.putString("operator", "hi");
    fragment.setArguments(this.bundle);

更改它,因为不需要以这种方式访问​​它:

bundle.putString("operator", "hi");
    fragment.setArguments(bundle);

在你的Tab1Fragment.java上你可以尝试这样的事情:

    if(getArguments()!=null){
String sentString = getArguments().getString("operator");
}