如何将数据从片段发送到活动

时间:2015-10-26 15:15:35

标签: android android-fragments interface

我正在创建一个实现Scrollable Tabs的应用程序。每个选项卡都有一个列表视图,其中包含从Internet下载的项目。

我拥有ViewPager的活动我想使用搜索框搜索列表中的所有项目。

但我不知道如何将列表中的数据发送到活动。

我的代码:

public class Coffees extends Fragment{
    private View rootView;
    private ListView lv;
    private ArrayAdapter<ProductList> adapter;
    private String jsonResult, table;
    private String url = "http://my.chatapp.info/order_api/files/getkafedes.php", name, image, price;

    ProgressDialog pDialog;
    List<ProductList> customList;
    private static final String TABLE_INTENT_ID = "table_name";
    private static final String COMPANY_INTENT_ID = "magaziID";
    private static final String WAITER_INTENT_ID = "servitorosID";
    private TextView tv1, tv2;
    int pos;
    private CardView cardView;
    private String servitoros_id;
    private String magazi_id;
    private Communicator communicator;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.coffees_fragment, container, false);
        lv = (ListView)rootView.findViewById(R.id.coffeesListView);
        cardView = (CardView)rootView.findViewById(R.id.card_view);
        table = getActivity().getIntent().getStringExtra(TABLE_INTENT_ID);
        servitoros_id = getActivity().getIntent().getStringExtra(WAITER_INTENT_ID);
        magazi_id = getActivity().getIntent().getStringExtra(COMPANY_INTENT_ID);
        final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();

        if (!network_connected) {
            onDetectNetworkState().show();
        } else {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                accessWebService();
                pDialog.dismiss();
                setRetainInstance(true);
                registerCallClickBack();

                mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        accessWebService();
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
        return rootView;
    }   

    private void registerCallClickBack() {

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //pos = position;
                Intent intent = new Intent(getActivity(), CoffeesLayoutActivity.class);
                intent.putExtra("coffeeName", customList.get(position).getName());
                intent.putExtra("coffeePrice", customList.get(position).getPrice());
                intent.putExtra("coffeeImage", customList.get(position).getImage());
                intent.putExtra(TABLE_INTENT_ID, table);
                intent.putExtra(WAITER_INTENT_ID, servitoros_id);
                intent.putExtra(COMPANY_INTENT_ID, magazi_id);
                startActivity(intent);
            }
        });
    }


    public class JsonReadTask extends AsyncTask<String , Void, List<ProductList>> {
        public JsonReadTask() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setIndeterminate(true);
            pDialog.setMessage(getString(R.string.get_stocks));
            pDialog.setCancelable(false);
            pDialog.setInverseBackgroundForced(true);
            pDialog.show();
        }

        @Override
        protected List<ProductList> doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
                customList = new ArrayList<>();

                JSONObject jsonResponse = new JSONObject(jsonResult);
                JSONArray jsonMainNode = jsonResponse.optJSONArray("kafedes");
                for (int i = 0; i < jsonMainNode.length(); i++) {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    name = jsonChildNode.optString("name");
                    price = jsonChildNode.optString("price");
                    image = jsonChildNode.optString("image");
                    customList.add(new ProductList(image, name, price));

                }
                return customList;
            } catch (Exception e) {
                e.printStackTrace();
                getActivity().finish();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (Exception e) {
                getActivity().finish();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(List<ProductList> customList) {
            if(customList == null){
                Log.d("ERORR", "No result to show.");
                return;
            }
            ListDrawer(customList);
            pDialog.dismiss();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        task.execute(url);
    }

    public void ListDrawer(List<ProductList> customList) {
        adapter = new ProductListAdapter(getActivity().getApplicationContext(), R.layout.productlist_row_item, customList);
        adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);
    }

我创建了一个类似的界面:

public interface Communicator {
    void responseList(String name, String image, String price);
}

Fragment中的onActivityCreated方法

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        communicator = (Communicator)getActivity();
        communicator.responseList(name, image, price);
    }

活动:

public class ProductsViewOrder extends AppCompatActivity implements Communicator {

    private ViewPager viewPager;
    private ProductsTabPagerAdapter mAdapter;
    private PagerSlidingTabStrip tabs;
    private SearchBox box;
    private String title;
    private SearchResult option;
    private Intent intent;
    private ConnectivityManager cm;
    private NetworkInfo activeNetwork;
    boolean network_connected;
    private String servitoros_id;
    private String magazi_id;
    private static final String COMPANY_INTENT_ID = "magaziID";
    private static final String WAITER_INTENT_ID = "servitorosID";
    private static final String TABLE_INTENT_ID = "table_name";
    private Toolbar toolbar;
    private float mActionBarHeight;
    private String name, image, price;

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

    private void checkNetwork() {
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetwork = cm.getActiveNetworkInfo();
        network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();
        if (!network_connected) {
            DialogMessageDisplay.displayWifiSettingsDialog(ProductsViewOrder.this, ProductsViewOrder.this, getString(R.string.wifi_off_title), getString(R.string.wifi_off_message));
        } else {
            setupPages();
            setupSearch();
        }
    }

    private void setupSearch() {
        box = (SearchBox) findViewById(R.id.searchbox);
        box.setLogoText(getString(R.string.search));

    }

    private void setupPages() {
        toolbar = (Toolbar) findViewById(R.id.toolBar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setElevation(0);
        }
        viewPager = (ViewPager) findViewById(R.id.pager);
        intent = getIntent();
        servitoros_id = intent.getStringExtra(WAITER_INTENT_ID);
        magazi_id = intent.getStringExtra(COMPANY_INTENT_ID);
        title = intent.getStringExtra(TABLE_INTENT_ID);
        toolbar.setTitle(getString(R.string.table_id) + title);
        mAdapter = new ProductsTabPagerAdapter(getSupportFragmentManager(), ProductsViewOrder.this, ProductsViewOrder.this);
        viewPager.setAdapter(mAdapter);
        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        tabs.setViewPager(viewPager);
        tabs.setDividerColor(Color.TRANSPARENT);
        tabs.setIndicatorColor(Color.WHITE);
        tabs.setIndicatorHeight(6);
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int id = item.getItemId();
                switch (id) {
                    case R.id.search: {
                        showSearchResults();
                        break;
                    }
                    case R.id.cart: {
                        showCart();
                        break;
                    }
                }

                return true;
            }
        });
    }

    private void showCart() {
        Toast.makeText(ProductsViewOrder.this, R.string.cart_empty_toast, Toast.LENGTH_SHORT).show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_new_order, menu);
        return true;
    }

    private void showSearchResults() {
        box.revealFromMenuItem(R.id.search, this);
        box.setSearchListener(new SearchBox.SearchListener() {
            @Override
            public void onSearchOpened() {

            }

            @Override
            public void onSearchCleared() {
            }

            @Override
            public void onSearchClosed() {
                closeSearch();
            }

            @Override
            public void onSearchTermChanged() {
            }

            @Override
            public void onSearch(String searchTerm) {
                //Toast.makeText(ProductsViewOrder.this, searchTerm + " Searched", Toast.LENGTH_LONG).show();
            }
        });
    }

    protected void closeSearch() {
        box.hideCircularly(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_left);
    }


    @Override
    public void responseList(String name, String image, String price) {
        this.name = name;
        this.image = image;
        this.price = price;
    }
}

我仍然得到空数据。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用callBack,只需按照以下方式操作:http://developer.android.com/training/basics/fragments/communicating.html