0
我正在創建一個實現可滾動選項卡的應用程序。每個選項卡都有一個列表視圖,其中的項目是從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);
}
內部片段
的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;
}
}
而且我仍然得到空數據。任何建議將不勝感激。
我已經完成它已經但是problemm是,它只能說明總是最後一個項目... – ElouCapitan
ProductsViewOrder只有3場 - 名稱,形象,價格因此有隻能是一個記錄。您在每個回調中都覆蓋它們。如果您不在3個字符串的ProductsViewOrder中設置列表,然後在ProductsViewOrder.responseList的每個回調中添加列表? – Kalininskaya