简体   繁体   中英

Layout Refresh issues in Activity with Tabs

Its an Activity with Tabs , I'm getting data from API using Volley library . There is only one Fragment . Whenever Tab is changed either by sliding or clicking the Tab , the function that calls the APIs is called with different data.

Problems:

1) It loads items every time on working internet, but it sometimes shows and sometimes not. When I press home button (ie activity is running and in background) and then select the app from opened apps list it shows data. I've to pause and resume app to view changes by pressing home button and reselecting from opened apps. If I lock screen and unlock screen then also it shows the content.

2) Similar to problem 1) there is an info button on top right corner it shows/hides a layout when clicked. But some time when problem 1) occurs it also behaves same.

3) Also looks similar to 1) and 2) there is TextView (Options) that shows/hides a layout when clicked But some time when problem 1) occurs it also behaves same.

Any help would be appreciated, I'm running out of time...

Here is screenshot: Screenshot

RestaurantDetailActivity.java

public class RestaurantDetailActivity extends AppCompatActivity {
    LinearLayout contactLayout;
    TabLayout tabLayout;
    ViewPager viewPager;
    TextView nameTv, descrTv, timingsTv, totalRatingsTv;
    RatingBar ratingsRb;
    ImageView restaurantIv;
    String resId;

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

        //get data from previews activity
        Intent intent = getIntent();

        //init views
        nameTv = findViewById(R.id.nameTv);
        ratingsRb = findViewById(R.id.ratingsRb);
        descrTv = findViewById(R.id.descrTv);
        timingsTv = findViewById(R.id.timingsTv);
        totalRatingsTv = findViewById(R.id.totalRatingsTv);
        contactLayout = findViewById(R.id.contactLayout);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        timingsTv = findViewById(R.id.timingsTv);
        restaurantIv = findViewById(R.id.restaurantIv);

        resId = intent.getStringExtra("id");

        //setup tabs
        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);

        final String name = intent.getStringExtra("name");
        final String ratings = intent.getStringExtra("ratings");
        String description = intent.getStringExtra("description");
        String status = intent.getStringExtra("status");
        String resPaused = intent.getStringExtra("resPaused");
        String open = intent.getStringExtra("openTime");
        String close = intent.getStringExtra("closeTime");

        //set data in header
        nameTv.setText(name);
        ratingsRb.setRating(Float.parseFloat(ratings));
        descrTv.setText(description);
        final String timings;
        if (resPaused.equals("0")) {
            timings = con24to12(open) + " - " + con24to12(close);timingsTv.setTextColor(getApplicationContext().getResources().getColor(R.color.colorWhite));
        } else {
            timings = "Closed Today";
          timingsTv.setTextColor(getApplicationContext().getResources().getColor(R.color.colorRadish));
        }
        //set timings
        if (Utils.compareOpenTime(open)) {
            timingsTv.setTextColor(getApplicationContext().getResources().getColor(R.color.colorWhite));
            timingsTv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_time_white, 0, 0, 0);
            timingsTv.setText(con24to12(open));
        } else {
            timingsTv.setText(timings);
        }

        totalRatingsTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(getApplicationContext(), RestaurantReviewsActivity.class);
                intent1.putExtra("restId", resId);
                intent1.putExtra("restName", name);
                intent1.putExtra("restRatings", ratings);
                startActivity(intent1);
            }
        });


        final Bitmap b = BitmapFactory.decodeFile(getExternalCacheDir() + "/TopServeImages" + "/" + intent.getStringExtra("image"));
        restaurantIv.setImageBitmap(b);

    }

    ViewPagerAdapter adapter;

    private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());


        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Getting Menu...");
        progressDialog.show();

        String token = "auth" + System.currentTimeMillis();

        Map<String, String> params = new HashMap<>();
        params.put("Token", token);
        params.put("RestaurantID", resId);
        Log.d("TheToken", Utils.getToken() + "" + Utils.getEmail());

        String url = ApiManager.headerUrl + ApiManager.menuItemsUrl;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                url, new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        progressDialog.dismiss();
                        Log.d("TheResponse", response.toString());

                        try {
                            JSONObject jsonObject = response.getJSONObject("Response");
                            JSONArray jsonArray = jsonObject.getJSONArray("MenuCategories");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                String menuItemCategoryID = jsonArray.getJSONObject(i).getString("MenuItemCategoryID");
                                String name = jsonArray.getJSONObject(i).getString("Name");
                                String restaurantID = jsonArray.getJSONObject(i).getString("RestaurantID");

                                adapter.addFragment(RestaurantFragment.newInstance((i + 1), "" + name, restaurantID, menuItemCategoryID), "" + name);
                                adapter.notifyDataSetChanged();

                            }
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                try {
                    if (error.getMessage().toLowerCase().contains("no address associated with hostname")) {
                        Toast.makeText(getApplicationContext(), "Slow or no Internet connection...", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        Volley.newRequestQueue(this).add(jsonObjReq);

        viewPager.setAdapter(adapter);
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> fragmentList = new ArrayList<>();
        private final List<String> fragmentTitleList = new ArrayList<>();

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

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }
    }

    public void clicks(View view) {
        if (view == findViewById(R.id.backTv)) {
            onBackPressed();
        } else if (view == findViewById(R.id.infoBtn)) {
            if (contactLayout.getVisibility() == View.GONE) {
                contactLayout.setVisibility(View.VISIBLE);
            } else {
                contactLayout.setVisibility(View.GONE);
            }
        }
    }

    public String con24to12(String from) {
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        DateFormat outputformat = new SimpleDateFormat("hh:mm aa");
        Date date = null;
        String output = null;
        try {
            date = df.parse(from);
            output = outputformat.format(date);
            from = output;
        } catch (Exception pe) {
            Toast.makeText(getApplicationContext(), "" + pe.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return from;
    }

}

RestaurantFragment.java

public class RestaurantFragment extends Fragment {

    String title;
    int page;
    String restaurantId;
    String menuItemCategoryID;

    AdapterMenu mAdapter;
    List<ModelMenu> menuList;

    ImageView fabCartIv;
    RecyclerView recyclerView;

    public RestaurantFragment() {

    }

    public static RestaurantFragment newInstance(int page, String title, String restID, String menuItemCategoryID) {
        RestaurantFragment fragmentFirst = new RestaurantFragment();
        Bundle args = new Bundle();
        args.putInt("someInt", page);
        args.putString("someTitle", title);
        args.putString("restId", restID);
        args.putString("menuItemCategoryID", menuItemCategoryID);
        fragmentFirst.setArguments(args);
        return fragmentFirst;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = getArguments().getInt("someInt", 0);
        title = getArguments().getString("someTitle");
        restaurantId = getArguments().getString("restId");
        menuItemCategoryID = getArguments().getString("menuItemCategoryID");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_restaurant, container, false);

        recyclerView = view.findViewById(R.id.menuRecyclerView);
        fabCartIv = view.findViewById(R.id.fabCartIv);

        loadMenuItems();

        return view;
    }

    private void loadMenuItems() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
        menuList = new ArrayList<>();
        String token = "auth" + System.currentTimeMillis();

        Map<String, String> params = new HashMap<>();
        params.put("Token", token);
        params.put("RestaurantID", restaurantId);

        String url = ApiManager.headerUrl + ApiManager.menuItemsUrl;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                url, new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONObject joResponse = response.getJSONObject("Response");
                            JSONArray jaMainMenu = joResponse.getJSONArray("MainMenu");
                            JSONArray jaMenuItemImages = joResponse.getJSONArray("MenuItemImages");
                            JSONArray jaLinkedMenuItems = joResponse.getJSONArray("LinkedMenuItems");


                            for (int i = 0; i < jaLinkedMenuItems.length(); i++) {
                                String menuItemCategoryID1 = jaLinkedMenuItems.getJSONObject(i).getString("MenuItemCategoryID");

                                if (menuItemCategoryID.equals(menuItemCategoryID1)) {
                                    String menuItemID1 = jaLinkedMenuItems.getJSONObject(i).getString("MenuItemID");
                                    for (int j = 0; j < jaMainMenu.length(); j++) {
                                        String deleted = jaMainMenu.getJSONObject(j).getString("Deleted");
                                        String description = jaMainMenu.getJSONObject(j).getString("Description");
                                        String ingredients = jaMainMenu.getJSONObject(j).getString("Ingredients");
                                        String inventory = jaMainMenu.getJSONObject(j).getString("Inventory");
                                        String menuItemID = jaMainMenu.getJSONObject(j).getString("MenuItemID");
                                        String name = jaMainMenu.getJSONObject(j).getString("Name");
                                        String paused = jaMainMenu.getJSONObject(j).getString("Paused");
                                        String price = jaMainMenu.getJSONObject(j).getString("Price");
                                        String rating = jaMainMenu.getJSONObject(j).getString("Rating");
                                        String restaurantID = jaMainMenu.getJSONObject(j).getString("RestaurantID");
                                        String servedEnd = jaMainMenu.getJSONObject(j).getString("ServedEnd");
                                        String servedStart = jaMainMenu.getJSONObject(j).getString("ServedStart");
                                        String imageURL = jaMenuItemImages.getJSONObject(j).getString("ImageURL");
                                        if (menuItemID1.equals(menuItemID)) {
                                            ModelMenu cModels = new ModelMenu("" + deleted,
                                                    "" + description,
                                                    "" + ingredients,
                                                    "" + inventory,
                                                    "" + menuItemID,
                                                    "" + name,
                                                    "" + paused,
                                                    "$" + price,
                                                    "" + rating,
                                                    "" + restaurantID,
                                                    "" + servedEnd,
                                                    "" + servedStart,
                                                    "" + imageURL);
                                            menuList.add(cModels);
                                        }

                                    }
                                    mAdapter = new AdapterMenu(menuList, getActivity().getApplicationContext(), RestaurantFragment.this);
                                    recyclerView.setAdapter(mAdapter);
                                }


                            }


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

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    if (error.getMessage().toLowerCase().contains("no address associated with hostname")) {
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Volley.newRequestQueue(getActivity()).add(jsonObjReq);
   }


}

AdapterMenu.java

public class AdapterMenu extends RecyclerView.Adapter<AdapterMenu.MyHolder> {

    List<ModelMenu> menuList;
    Context context;
    Fragment fragment;

    public AdapterMenu(List<ModelMenu> menuList, Context context, Fragment fragment) {
        this.menuList = menuList;
        this.context = context;
        this.fragment = fragment;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.row_menus, viewGroup, false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
        final String title = menuList.get(i).getName();
        final String description = menuList.get(i).getDescription();
        final String price = menuList.get(i).getPrice();
        final String image = menuList.get(i).getImage();
        final String ingredients = menuList.get(i).getIngredients();
        final String restaurantID = menuList.get(i).getRestaurantID();
        final String menuItemID = menuList.get(i).getMenuItemID();


        String notServing;
        if (menuList.get(i).getServedStart().equals("null") && menuList.get(i).getServedEnd().equals("null")) {
            notServing = "";
            myHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.colorWhite));
        } else {
            String startTime = Utils.timeTo12hr(menuList.get(i).getServedStart());
            String endTime = Utils.timeTo12hr(menuList.get(i).getServedEnd());
            notServing = "Only Serving between " + startTime + " - " + endTime;
            myHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.colorGray1));
        }

        myHolder.titleTv.setText(title);
        myHolder.descriptionTv.setText(description);
        myHolder.priceTv.setText(price);
        myHolder.notServingTv.setText(notServing);
        myHolder.addHintTv.setText("Add " + title + " To Order");

        myHolder.optionsTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myHolder.addItemLayout.getVisibility() == View.VISIBLE) {
                    myHolder.addItemLayout.setVisibility(View.GONE);
                    myHolder.optionsTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_down_black, 0);
                } else {
                    myHolder.addItemLayout.setVisibility(View.VISIBLE);
                    myHolder.optionsTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_up_black, 0);
                }
            }
        });


        myHolder.addItemBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences sp = context.getSharedPreferences("OderSP", Context.MODE_PRIVATE);
                int count = sp.getInt("itemCount", 0);

                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("itemCount", count + 1);
                editor.apply();

                onAddField(context, myHolder, title, price);

            }
        });

        myHolder.infoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MenuDetailActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("description", description);
                intent.putExtra("image", image);
                intent.putExtra("ingredients", ingredients);
                intent.putExtra("restaurantID", restaurantID);
                intent.putExtra("menuItemID", menuItemID);
                intent.putExtra("image", image);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });


        try {
            final Bitmap b = BitmapFactory.decodeFile(context.getExternalCacheDir() + "/TopServeImages" + "/" + image);
            if (b == null) {
                ImageDownloader.execute(new Runnable() {
                    @Override
                    public void run() {
                        new ImageDownloader().awsImageDownload(myHolder, image);
                    }
                });
            } else {
                myHolder.iconIv.setImageBitmap(b);
            }
        } catch (Exception e) {
            ImageDownloader.execute(new Runnable() {
                @Override
                public void run() {
                    new ImageDownloader().awsImageDownload(myHolder, image);
                }
            });
        }


    }

    private int itemsCount = 0;

    private void onAddField(final Context context, MyHolder myHolder, final String title, String price) {
        final LinearLayout parentLinearLayout = myHolder.itemView.findViewById(R.id.menu_roLl);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.row_additeminfo, null);
        parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

        final TextView titleTv = rowView.findViewById(R.id.orderInfoTitleTv);
        final TextView priceTv = rowView.findViewById(R.id.orderInfoPrice);
        final ImageButton removeBtn = rowView.findViewById(R.id.orderInfoRemoveBtn);

        itemsCount++;
        EasyDB easyDB = EasyDB.init(context, "ITEMS_DB")
                .setTableName("ITEMS_TABLE")
                .addColumn(new Column("Item_Id", new String[]{"text", "unique"}))
                .addColumn(new Column("Item_Name", new String[]{"text", "not null"}))
                .addColumn(new Column("Item_Price", new String[]{"text", "not null"}))
                .doneTableColumn();
        easyDB.addData("Item_Id", title + (parentLinearLayout.getChildCount() - 1))
                .addData("Item_Name", title)
                .addData("Item_Price", price)
                .doneDataAdding();

        titleTv.setText("Order: " + itemsCount + " " + title);
        priceTv.setText(price);

        SharedPreferences sp = context.getSharedPreferences("OderSP", Context.MODE_PRIVATE);
        itemsCount = sp.getInt("itemCount", 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("itemCount", itemsCount);
        editor.apply();

        removeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDelete(parentLinearLayout, view, title);
            }
        });
    }

    private void onDelete(final LinearLayout parentLinearLayout, final View v, final String title) {

        AlertDialog.Builder builder = new AlertDialog.Builder(v.getRootView().getContext());
        builder.setTitle("Remove this item?");
        builder.setMessage(title);
        builder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                parentLinearLayout.removeView((View) v.getParent());
                itemsCount--;
                SharedPreferences sp = context.getSharedPreferences("OderSP", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("itemCount", itemsCount);
                editor.apply();

                EasyDB easyDB = EasyDB.init(context, "ITEMS_DB")
                        .setTableName("ITEMS_TABLE")
                        .addColumn(new Column("Item_Id", new String[]{"text", "unique"}))
                        .addColumn(new Column("Item_Name", new String[]{"text", "not null"}))
                        .addColumn(new Column("Item_Price", new String[]{"text", "not null"}))
                        .doneTableColumn();
                easyDB.deleteRow("Item_Id", "" + title + (parentLinearLayout.getChildCount()));
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.create().show();
    }

    @Override
    public int getItemCount() {
        return menuList.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        TextView titleTv, priceTv, descriptionTv, notServingTv, addHintTv, optionsTv, orderInfoTitleTv, orderInfoPrice;
        ImageButton infoBtn, orderInfoRemoveBtn;
        ImageView iconIv;
        Button addItemBtn;
        LinearLayout addItemLayout;
        RelativeLayout orderInfoLayout;

        MyHolder(@NonNull View itemView) {
            super(itemView);

            iconIv = itemView.findViewById(R.id.iconIv);
            titleTv = itemView.findViewById(R.id.titleTv);
            priceTv = itemView.findViewById(R.id.priceTv);
            descriptionTv = itemView.findViewById(R.id.descriptionTv);
            notServingTv = itemView.findViewById(R.id.notServingTv);
            addHintTv = itemView.findViewById(R.id.addHintTv);
            optionsTv = itemView.findViewById(R.id.optionsTv);
            orderInfoTitleTv = itemView.findViewById(R.id.orderInfoTitleTv);
            orderInfoPrice = itemView.findViewById(R.id.orderInfoPrice);
            infoBtn = itemView.findViewById(R.id.infoBtn);
            orderInfoRemoveBtn = itemView.findViewById(R.id.orderInfoRemoveBtn);
            addItemBtn = itemView.findViewById(R.id.addItemBtn);
            addItemLayout = itemView.findViewById(R.id.addItemLayout);
            orderInfoLayout = itemView.findViewById(R.id.orderInfoLayout);
        }
    }


}

Have you tried overriding onStop() in your Activities?

onStop() is called when your app is no longer visible to the user (ie pressing Home). You will next receive either onRestart(), onDestroy(), or nothing. This may explain your inconsistent behaviour.

You will likely need to take control and stop any updates to UI elements especially here, and then preserve the state of the UI as the user left it with onSaveInstanceState()

https://developer.android.com/topic/libraries/architecture/saving-states

Here is how I fixed the issue:

First, understand the problem.

  1. In the first activity where you fetch the restaurant list, that is fine.

  2. When the restaurant is clicked, you pass the restaurant id to the RestaurantDetailActivity and do an API request.

  3. In the API request you pass the restaurant id and get the response. The response contains a lost of all the categories of that restaurant and also the list of all the dishes provided by the restaurant in all the categories. This is very important.

  4. At this stage you take only the list of categories in the response and start creating a fragment for each category. You pass the category id to each fragment.

  5. Then each fragment does an API request to the the same API which was called at the activity level (point number 3 above). Each fragment does the same request independently and extracts only the list of menu items that belong to that category. That is a waste of resources.

  6. When a fragment goes out of view , it is destroyed and then recreated when user swipes back to the tab. Every time user comes to a fragment, it loads data again. This repeated loading of data was causing the device to go unresponsive.

Now here is what I did. At step 3, when a string request is done for a particular restaurant and all the menu items are received in response. I create a separate List of menu items for each category at this stage and then pass the list to each fragment. Now each fragment has to just display the list it has received from the activity. Each fragment is not responsible for doing its own string request and parsing it to creating its own list of items. Rather it just received the list from activity and displays it. In this was only one API request is done at activity level. No matter how many time the user switches tabs, there is no extra API request.

public class ModelMenu implements Serializable {

    private String deleted, description, ingredients, inventory, menuItemID, name, paused, price, rating, restaurantID, servedEnd, servedStart, image;

    public ModelMenu() {
    }

    public ModelMenu(String name, String price) {
        this.name = name;
        this.price = price;
    }

    public ModelMenu(String deleted, String description, String ingredients, String inventory, String menuItemID, String name, String paused, String price, String rating, String restaurantID, String servedEnd, String servedStart, String image) {
        this.deleted = deleted;
        this.description = description;
        this.ingredients = ingredients;
        this.inventory = inventory;
        this.menuItemID = menuItemID;
        this.name = name;
        this.paused = paused;
        this.price = price;
        this.rating = rating;
        this.restaurantID = restaurantID;
        this.servedEnd = servedEnd;
        this.servedStart = servedStart;
        this.image = image;
    }

    public String getDeleted() {
        return deleted;
    }

    public void setDeleted(String deleted) {
        this.deleted = deleted;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getIngredients() {
        return ingredients;
    }

    public void setIngredients(String ingredients) {
        this.ingredients = ingredients;
    }

    public String getInventory() {
        return inventory;
    }

    public void setInventory(String inventory) {
        this.inventory = inventory;
    }

    public String getMenuItemID() {
        return menuItemID;
    }

    public void setMenuItemID(String menuItemID) {
        this.menuItemID = menuItemID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPaused() {
        return paused;
    }

    public void setPaused(String paused) {
        this.paused = paused;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getRestaurantID() {
        return restaurantID;
    }

    public void setRestaurantID(String restaurantID) {
        this.restaurantID = restaurantID;
    }

    public String getServedEnd() {
        return servedEnd;
    }

    public void setServedEnd(String servedEnd) {
        this.servedEnd = servedEnd;
    }

    public String getServedStart() {
        return servedStart;
    }

    public void setServedStart(String servedStart) {
        this.servedStart = servedStart;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}







public class RestaurantFragment extends Fragment {

            private String title;
            private int page;
            private String restaurantId;
            private String menuItemCategoryID;

            private AdapterMenu mAdapter;
            private List<ModelMenu> menuList;

            TextView orderTimeTv, changeTimeTv, tenPercentTv, fifteenPercentTv, twentyPercentTv, customTipTv, totalTipTv, subTotalTv, taxTotalTv, totalTv, pickedTimeTv, pickedDateTv, todayTv, cancelTv, itemCountTv;
            ImageView fabCartIv;
            RecyclerView recyclerView;

            public RestaurantFragment() {
                // Required empty public constructor
            }

            // newInstance constructor for creating fragment with arguments
            /*public static RestaurantFragment newInstance(int page, String title, String restID, String menuItemCategoryID) {
                RestaurantFragment fragmentFirst = new RestaurantFragment();
                Bundle args = new Bundle();
                args.putInt("someInt", page);
                args.putString("someTitle", title);
                args.putString("restId", restID);
                args.putString("menuItemCategoryID", menuItemCategoryID);
                fragmentFirst.setArguments(args);
                return fragmentFirst;
            }*/

            public static RestaurantFragment newInstance(int page, String title, String restID, String menuItemCategoryID, List<ModelMenu> menuList) {
                RestaurantFragment fragmentFirst = new RestaurantFragment();
                Bundle args = new Bundle();
                args.putInt("someInt", page);
                args.putString("someTitle", title);
                args.putString("restId", restID);
                args.putString("menuItemCategoryID", menuItemCategoryID);
                args.putSerializable("menuList", (Serializable) menuList);
                fragmentFirst.setArguments(args);
                return fragmentFirst;
            }

            // Store instance variables based on arguments passed
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                page = getArguments().getInt("someInt", 0);
                title = getArguments().getString("someTitle");
                restaurantId = getArguments().getString("restId");
                menuItemCategoryID = getArguments().getString("menuItemCategoryID");
                menuList = (List<ModelMenu>) getArguments().getSerializable("menuList");
            }

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

                recyclerView = view.findViewById(R.id.menuRecyclerView);
                itemCountTv = view.findViewById(R.id.itemCountTv);
                fabCartIv = view.findViewById(R.id.fabCartIv);

                /*if (title.equals("Appetizers")) {
                    loadDataAppetizers();
                } else if (title.equals("Breakfast")) {
                    loadBreakfast();
                } else if (title.equals("Noodle")) {
                    loadNoodle();
                }*/
                loadMenuItems();

                fabCartIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showCartDialog();
                    }
                });

                count();
                return view;
            }

            private void loadMenuItems() {
                //recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
                //Log.i("mytag", "list received with size: " + menuList.size() + ", in tab: " + title);
                mAdapter = new AdapterMenu(menuList, getActivity().getApplicationContext(), RestaurantFragment.this);
                recyclerView.setAdapter(mAdapter);
                /*String token = "auth" + System.currentTimeMillis();
                final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                //show progress dialog
                progressDialog.setMessage("Getting Menu Items...");
                progressDialog.show();*/

                /*Map<String, String> params = new HashMap<>();
                params.put("Token", token);
                params.put("RestaurantID", restaurantId);
                Log.d("TheToken", Utils.getToken() + "" + Utils.getEmail());

                String url = ApiManager.headerUrl + ApiManager.menuItemsUrl;

                JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                        url, new JSONObject(params),
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                //progressDialog.dismiss();
                                Log.d("TheResponse", response.toString());

                                try {
                                    JSONObject joResponse = response.getJSONObject("Response");
                                    JSONArray jaMainMenu = joResponse.getJSONArray("MainMenu");
                                    JSONArray jaMenuItemImages = joResponse.getJSONArray("MenuItemImages");
                                    JSONArray jaMenuCategories = joResponse.getJSONArray("MenuCategories");
                                    JSONArray jaLinkedMenuItems = joResponse.getJSONArray("LinkedMenuItems");
                                    JSONArray jaMenuSidesTitles = joResponse.getJSONArray("MenuSidesTitles");
                                    JSONArray jaMenuSidesLinks = joResponse.getJSONArray("MenuSidesLinks");
                                    JSONArray jaMenuSides = joResponse.getJSONArray("MenuSides");

                                    *//*for (int j = 0; j < jaMenuCategories.length(); j++) {
                                        String menuItemCategoryID = jaMainMenu.getJSONObject(j).getString("MenuItemCategoryID");
                                    }*//*

                                    for (int i = 0; i < jaLinkedMenuItems.length(); i++) {
                                        String menuItemCategoryID1 = jaLinkedMenuItems.getJSONObject(i).getString("MenuItemCategoryID");

                                        if (menuItemCategoryID.equals(menuItemCategoryID1)) {
                                            String menuItemID1 = jaLinkedMenuItems.getJSONObject(i).getString("MenuItemID");
                                            for (int j = 0; j < jaMainMenu.length(); j++) {
                                                String deleted = jaMainMenu.getJSONObject(j).getString("Deleted");
                                                String description = jaMainMenu.getJSONObject(j).getString("Description");
                                                String ingredients = jaMainMenu.getJSONObject(j).getString("Ingredients");
                                                String inventory = jaMainMenu.getJSONObject(j).getString("Inventory");
                                                String menuItemID = jaMainMenu.getJSONObject(j).getString("MenuItemID");
                                                String name = jaMainMenu.getJSONObject(j).getString("Name");
                                                String paused = jaMainMenu.getJSONObject(j).getString("Paused");
                                                String price = jaMainMenu.getJSONObject(j).getString("Price");
                                                String rating = jaMainMenu.getJSONObject(j).getString("Rating");
                                                String restaurantID = jaMainMenu.getJSONObject(j).getString("RestaurantID");
                                                String servedEnd = jaMainMenu.getJSONObject(j).getString("ServedEnd");
                                                String servedStart = jaMainMenu.getJSONObject(j).getString("ServedStart");
                                                String imageURL = jaMenuItemImages.getJSONObject(j).getString("ImageURL");
                                                if (menuItemID1.equals(menuItemID)) {
                                                    ModelMenu cModels = new ModelMenu("" + deleted,
                                                            "" + description,
                                                            "" + ingredients,
                                                            "" + inventory,
                                                            "" + menuItemID,
                                                            "" + name,
                                                            "" + paused,
                                                            "$" + price,
                                                            "" + rating,
                                                            "" + restaurantID,
                                                            "" + servedEnd,
                                                            "" + servedStart,
                                                            "" + imageURL);
                                                    menuList.add(cModels);
                                                }

                                            }
                                            //adapter to be set to recyclerview
                                            mAdapter = new AdapterMenu(menuList, getActivity().getApplicationContext(), RestaurantFragment.this);
                                            recyclerView.setAdapter(mAdapter);
                                        }


                                    }


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

                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //progressDialog.dismiss();
                        try {
                            if (error.getMessage().toLowerCase().contains("no address associated with hostname")) {

                            } else {

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                Volley.newRequestQueue(getActivity()).add(jsonObjReq);*/
            }

            private int tipPercentage = 10;
            private String date = "";

            //used to pass lists in confirm order
            private ArrayList idList = new ArrayList();
            private ArrayList nameList = new ArrayList();
            private ArrayList priceList = new ArrayList();
            int ids = 0;
            List<ModelMenu> menuList1;
            MyAdapters myAdapters;

            @SuppressLint("NewApi")
            private void showCartDialog() {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_cart, null);
                RecyclerView recyclerView = view.findViewById(R.id.menusLayout);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                menuList1 = new ArrayList<>();

                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setView(view);
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        tipPercentage = 10;
                        totalPriceAddRemove = 0.0;
                        idList.clear();
                        nameList.clear();
                        priceList.clear();
                        ids = 0;
                    }
                });
                builder.create().show();

                orderTimeTv = view.findViewById(R.id.orderTimeTv);
                changeTimeTv = view.findViewById(R.id.changeTimeTv);
                tenPercentTv = view.findViewById(R.id.tenPercentTv);
                fifteenPercentTv = view.findViewById(R.id.fifteenPercentTv);
                twentyPercentTv = view.findViewById(R.id.twentyPercentTv);
                customTipTv = view.findViewById(R.id.customTipTv);
                totalTipTv = view.findViewById(R.id.totalTipTv);
                subTotalTv = view.findViewById(R.id.subTotalTv);
                taxTotalTv = view.findViewById(R.id.taxTotalTv);
                totalTv = view.findViewById(R.id.totalTv);
                pickedTimeTv = view.findViewById(R.id.pickedTimeTv);
                pickedDateTv = view.findViewById(R.id.pickedDateTv);
                todayTv = view.findViewById(R.id.todayTv);
                cancelTv = view.findViewById(R.id.cancelTv);
                final Button checkoutBtn = view.findViewById(R.id.checkoutBtn);
                Button doneDTBtn = view.findViewById(R.id.doneDTBtn);
                final TimePicker timePicker = view.findViewById(R.id.timePicker);
                HorizontalCalendar hcCalendar = view.findViewById(R.id.hcCalendar);
                final LinearLayout dateTimePickLayout = view.findViewById(R.id.dateTimePickLayout);
                final RelativeLayout pricesLayout = view.findViewById(R.id.pricesLayout);

                dateTimePickLayout.setVisibility(View.GONE);
                pricesLayout.setVisibility(View.VISIBLE);

                EasyDB easyDB = EasyDB.init(getActivity(), "ITEMS_DB") // "TEST" is the name of the DATABASE
                        .setTableName("ITEMS_TABLE")  // You can ignore this line if you want
                        .addColumn(new Column("Item_Id", "text", "unique"))
                        .addColumn(new Column("Item_Name", "text", "not null"))
                        .addColumn(new Column("Item_Price", "text", "not null"))
                        .doneTableColumn();
                Cursor res = easyDB.getAllData();
                while (res.moveToNext()) {
                    String id = res.getString(1);
                    String name = res.getString(2);
                    String price = res.getString(3);
                    ModelMenu modelMenu = new ModelMenu("" + name, "" + price);
                    menuList1.add(modelMenu);
                    idList.add(ids);
                    nameList.add(name);
                    priceList.add(price);
                    ids++;
                }
                onAddField(getActivity());
                myAdapters = new MyAdapters(getActivity(), menuList1);
                recyclerView.setAdapter(myAdapters);

                timePicker.setIs24HourView(true);

                Calendar calendar = Calendar.getInstance();
                final int hours = calendar.get(Calendar.HOUR_OF_DAY);
                final int minute = calendar.get(Calendar.MINUTE);
                final int year = calendar.get(Calendar.YEAR);
                final int month = calendar.get(Calendar.MONTH) + 1;
                final int day = calendar.get(Calendar.DAY_OF_MONTH);

                date = day + "/" + month + "/" + year;

                pickedTimeTv.setText(hours + ":" + minute);
                pickedDateTv.setText(day + "/" + month + "/" + year);

                timePicker.setHour(hours);
                timePicker.setMinute(minute);

                timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
                    @Override
                    public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                        pickedTimeTv.setText(hour + ":" + minute);
                    }
                });











 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM