我有一个名为RestaurantActivity
的主要活动,上面有3个标签。 MenuFragment
是默认标签,当用户选择列表中的某个项目时,它会启动startActivityForResult()
并进入SelectedMealActivity
。从那里返回结果后,它会从onItemSelected()
调用RestaurantActivity
中的MenuFragment
。最后,onItemSelected()
方法将数据传递到第二个标签OrderFragment
但是使用getArgument()
方法获取了错误的数据。
RestaurantActivity.java
public class RestaurantActivity extends ActionBarActivity{
private String resName;
private static int tableNo;
private static String resId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
resName = getIntent().getExtras().getString("resName");
tableNo = getIntent().getExtras().getInt("tableNo");
resId = getIntent().getExtras().getString("resId");
TextView tableNoText = (TextView)findViewById(R.id.tableNoText);
tableNoText.setText("Masa No: " + String.valueOf(tableNo));
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(resName);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar.newTab()
.setText(R.string.menu_fragment)
.setTabListener(new TabListener(this, "menü", MenuFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.order_fragment)
.setTabListener(new TabListener(this, "sipariş", OrderFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.detail_fragment)
.setTabListener(new TabListener(this, "detay", DetailFragment.class));
actionBar.addTab(tab);
}
public void onItemSelected(ArrayList<String> item){
Bundle arguments = new Bundle();
arguments.putStringArrayList("item", item);
OrderFragment fragment = new OrderFragment();
fragment.setArguments(arguments);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private android.support.v4.app.Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* @param activity The host Activity, used to instantiate the fragment
* @param tag The identifier tag for the fragment
* @param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
@Override
public void onTabReselected(Tab arg0,
android.support.v4.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab arg0,
android.support.v4.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
if (mFragment == null) {
// If not, instantiate and add it to the activity
Bundle bundle = new Bundle();
bundle.putString("resId", resId);
bundle.putInt("tableNo", tableNo);
mFragment = Fragment.instantiate(mActivity, mClass.getName(), bundle);
ft.add(android.R.id.content, mFragment, mTag);
}
else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab arg0,
android.support.v4.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MenuFragment.java
public class MenuFragment extends ListFragment{
private static final String MEAL_URL = "http://kacyakiyor.net/meals.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
JSONParser jsonParser = new JSONParser();
ArrayList<String> resIdArray;
String resId, orderTabText, mealName;
JSONArray meals, resIdJarr;
JSONObject resIdJobj;
Meal clicked;
Set<String> clickedItems = new LinkedHashSet<String>();
ArrayList<String> clickedArr, orderedItem = new ArrayList<String>();
int clickedItemsCount = 0, itemCount = 0, mealPrice, tableNo;
public MenuFragment() {
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
resId = this.getArguments().getString("resId");
tableNo = this.getArguments().getInt("tableNo");
try {
resIdJobj = new JSONObject("{\"resId\":[{\"resId\":\""+ resId + "\"}]}");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
resIdJarr = resIdJobj.getJSONArray("resId");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
meals = new GetMeals().execute(resIdJarr).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Menu> items = new ArrayList<Menu>();
for(int i = 0; i < meals.length(); i++){
try {
if(i > 0 && meals.getJSONObject(i-1).getString("type").equals(meals.getJSONObject(i).getString("type")) == false){
items.add(new Header(meals.getJSONObject(i).getString("type")));
}
else if(i == 0){
items.add(new Header(meals.getJSONObject(i).getString("type")));
}
items.add(new Meal(meals.getJSONObject(i).getString("name"), meals.getJSONObject(i).getInt("price")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CustomArrayAdapter adapter = new CustomArrayAdapter(getActivity(), items);
setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
clicked = (Meal) l.getItemAtPosition(position);
mealName = clicked.getName(clicked);
mealPrice = clicked.getPrice(clicked);
Intent i = new Intent(getActivity(), SelectedMealActivity.class);
i.putExtra("mealName", mealName);
i.putExtra("mealPrice", mealPrice);
startActivityForResult(i,1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == getActivity().RESULT_OK){
itemCount++;
ArrayList<String> result = data.getStringArrayListExtra("item");
data.putExtra("item", result);
((RestaurantActivity)getActivity()).onItemSelected(result);
TextView itemCountText = (TextView)getActivity().findViewById(R.id.itemCountText);
itemCountText.setText("Toplam ürün: " + itemCount);
}
}
}
class GetMeals extends AsyncTask<JSONArray, Void, JSONArray>{
ArrayList<String> mealArray = new ArrayList<String>();
protected JSONArray doInBackground(JSONArray... args) {
// TODO Auto-generated method stub
JSONObject json = new JSONObject();
JSONArray arr = null;
try {
resId = args[0].getJSONObject(0).getString("resId");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("resId", resId.toString()));
json = jsonParser.makeHttpRequest(MEAL_URL, "POST", params);
try {
arr = json.getJSONArray("meals");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr;
}
}
}
SelectedMealActivity.java
public class SelectedMealActivity extends ActionBarActivity implements OnItemSelectedListener, OnClickListener {
private String mealName;
private int mealPrice, count = 1;
TextView mealNameText, priceText;
Spinner countSpinner;
EditText mealNote;
Button backToMenu, addToBasket;
ArrayList<String> item;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_meal);
mealName = getIntent().getExtras().getString("mealName");
mealPrice = getIntent().getExtras().getInt("mealPrice");
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Ürün Detayı");
mealNameText = (TextView)findViewById(R.id.mealNameText);
countSpinner = (Spinner)findViewById(R.id.countSpinner);
priceText = (TextView)findViewById(R.id.priceText);
mealNote = (EditText)findViewById(R.id.mealNoteText);
backToMenu = (Button)findViewById(R.id.backToMenuButton);
addToBasket = (Button)findViewById(R.id.addToBasketButton);
mealNameText.setText(mealName);
priceText.setText(mealPrice*count + "TL");
countSpinner.setOnItemSelectedListener(this);
backToMenu.setOnClickListener(this);
addToBasket.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chosen_meal, menu);
return true;
}
@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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3) {
count = Integer.valueOf(parent.getItemAtPosition(pos).toString());
priceText.setText(mealPrice*count + " TL");
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.backToMenuButton){
finish();
}
else if(v.getId() == R.id.addToBasketButton){
item = new ArrayList<String>();
item.add(String.valueOf(count));
item.add(mealName);
item.add(String.valueOf(mealPrice));
if(mealNote != null){
item.add(mealNote.getText().toString());
}
Toast.makeText(SelectedMealActivity.this, "Ürün sepete eklendi", Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("item", item);
setResult(RESULT_OK, returnIntent);
finish();
}
}
}
OrderFragment.java
public class OrderFragment extends Fragment {
ArrayList<String> item = new ArrayList<String>();
int count;
double price;
String mealName, mealNote;
public OrderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle arguments = getArguments();
if(arguments != null){
ArrayList<String> item = arguments.getStringArrayList("item");
}
return inflater.inflate(R.layout.fragment_order, container, false);
}
}
答案 0 :(得分:0)
好的,我通过使用getter和setter而不是bundle来得到答案。