Related
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 (i.e. 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);
}
}
}
Here is how I fixed the issue:
First, understand the problem.
In the first activity where you fetch the restaurant list, that is fine.
When the restaurant is clicked, you pass the restaurant id to the RestaurantDetailActivity and do an API request.
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.
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.
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.
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);
}
});
}
Have you tried overriding onStop() in your Activities?
onStop() is called when your app is no longer visible to the user (i.e. 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
I am making an android app that shows weather using OWM 5day 3hour forecast API, The ui consists of EditText to input a city name, a button to initiate the call process, a listview that will display 5 entries (five days) and each day entry includes another listview that displays decription and temperature for every 3 hours in a day,
I am able to see the listview for days but cannot see the nested listview for the hourly data. My classes include : MainActivity, WeatherAdapter to show 3hourly weather, DayAdapter to show day entries, and JsonToWeather data class that extracts data out of the Json response and make an Arraylist of data for only one particular day. I tried to log the error and highlighted the error position by a comment.
MainActivity :
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private String responseJSON = null;
ListView listView;
ArrayList<WeatherData> weatherDataArrayList;
WeatherAdapter weatherAdapter = null;
EditText cityName;
String city = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.dayList);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if(city == null){
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
} else {
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
if(weatherDataArrayList == null){
Log.d(TAG, "onCreate: ArrayList is Still null");
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url){
StringBuilder jsonResult = new StringBuilder();
try{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while(true){
charReader = reader.read(inputBuffer);
if(charReader < 0){
break;
}
if(charReader > 0){
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}catch (MalformedURLException e){
Log.e(TAG, "downloadJSON: URL is Invalid");
}catch (IOException e){
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if(jsonResponse == null){
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse) {
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if(jsonResponse != null){
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
DayAdapter day = new DayAdapter(MainActivity.this,R.layout.layout_day_card,days,weatherDataArrayList);
listView.setAdapter(day);
} else {
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
WeatherAdapter :
public class WeatherAdapter extends ArrayAdapter<WeatherData> {
private static final String TAG = "WeatherAdapter";
private final int layoutResourceID;
private LayoutInflater layoutInflater;
private ArrayList<WeatherData> block;
public WeatherAdapter(#NonNull Context context, int resource, ArrayList<WeatherData> block) {
super(context, resource, block);
this.layoutResourceID = resource;
this.block = block;
this.layoutInflater = LayoutInflater.from(context);
Log.d(TAG, "WeatherAdapter: called constructor");
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null){
convertView = layoutInflater.inflate(layoutResourceID,parent,false);
}
Log.d(TAG, "getView: entered");
WeatherData weatherData = block.get(position);
TextView temp = (TextView) convertView.findViewById(R.id.temperature);
temp.setText(weatherData.getTemp());
TextView shortDesc = (TextView) convertView.findViewById(R.id.descrip);
shortDesc.setText(weatherData.getShortDesc());
return convertView;
}
}
DayAdapter :
public class DayAdapter extends ArrayAdapter<String> {
private static final String TAG = "DayAdapter";
private ArrayList<String> dayBlock;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<WeatherData> dayWeather, fullBlock;
private Context context;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock) {
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.fullBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if(fullBlock == null){
Log.e(TAG, "DayAdapter: full block is null");
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(fullBlock,dateString);
if(fullBlock == null){
Log.d(TAG, "getView: fullblock is null");
}
if(dayWeather == null){
Log.d(TAG, "getView: dayweather array is null");
} else {
Log.d(TAG, "getView: dayweather is not null");
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for(WeatherData data : dayWeather){
if(mint > Float.parseFloat(data.getMinTemp())){
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp())){
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context,R.layout.weather_holder,dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
JsonToWeatherData:
public class JsonToWeatherData {
private static final String TAG = "JsonToWeatherData";
public ArrayList<WeatherData> extractor(String jsonData){
Log.d(TAG, "extractor: in the method");
if(jsonData == null){
return null; // if there is no json data is received
} else {
ArrayList<WeatherData> weatherDataArrayList = new ArrayList<WeatherData>();
Log.d(TAG, "extractor: in the else field");
try{
Log.d(TAG, "extractor: in try block");
JSONObject root = new JSONObject(jsonData);
int count = root.getInt("cnt");
JSONArray wList = root.getJSONArray("list");
for (int i = 0; i < count; ++i){
WeatherData weather = new WeatherData();
JSONObject wBlock = wList.getJSONObject(i);
weather.setDate(wBlock.getString("dt_txt"));
JSONObject mainObj = wBlock.getJSONObject("main");
weather.setTemp(String.valueOf(mainObj.getDouble("temp")));
weather.setMinTemp(String.valueOf(mainObj.getDouble("temp_min")));
weather.setMaxTemp(String.valueOf(mainObj.getDouble("temp_max")));
weather.setHumidity(String.valueOf(mainObj.getInt("humidity")));
JSONArray warray = wBlock.getJSONArray("weather");
JSONObject weatherObj = warray.getJSONObject(0);
weather.setDescription(weatherObj.getString("description"));
weather.setShortDesc(weatherObj.getString("main"));
weather.setIconID(weatherObj.getString("icon"));
weatherDataArrayList.add(weather);
Log.d(TAG, "extractor: temp field is :" + weather.getTemp());
}
}catch (JSONException e){
e.printStackTrace();
}
return weatherDataArrayList;
}
}
public ArrayList<WeatherData> extractByDate(ArrayList<WeatherData> fullList,String date){
ArrayList<WeatherData> dayweatherList = new ArrayList<WeatherData>();
for( WeatherData weather : fullList ){
if( ( weather.getDate().substring(0,9) ).equals(date) ){
dayweatherList.add(weather);
}
}
return dayweatherList;
}
}
What should I do?
Error message : (
08-19 23:11:39.914 12148-12148/com.jugalmistry.apps.fivedaysofweather D/DayAdapter: getView: dayweather is not null
08-19 23:11:39.916 12148-12148/com.jugalmistry.apps.fivedaysofweather D/AndroidRuntime: Shutting down VM
08-19 23:11:39.918 12148-12148/com.jugalmistry.apps.fivedaysofweather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jugalmistry.apps.fivedaysofweather, PID: 12148
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.jugalmistry.apps.fivedaysofweather.DayAdapter.getView(DayAdapter.java:58)
I have attempted to help you with the full code below.
I would also recommend you implement the ViewHolder pattern ViewHolder pattern example for increased performance.
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
EditText cityName;
String city = null;
ListView dayListView;
ArrayList<WeatherData> weatherDataArrayList;
DayAdapter dayAdapter;
//private String responseJSON = null;
//WeatherAdapter weatherAdapter = null; // Creating this adapter within the DayAdapter
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText) findViewById(R.id.cityName);
Button load = (Button) findViewById(R.id.loadButton);
dayListView = (ListView) findViewById(R.id.dayList);
load.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
city = cityName.getText().toString();
Log.d(TAG, "onClick: city is : " + city);
if (city == null)
{
Toast toast = null;
toast.makeText(MainActivity.this,"Please Enter a city before continuing",Toast.LENGTH_LONG);
toast.show();
}
else
{
String url = "http://api.openweathermap.org/data/2.5/forecast?q=" + (city.toLowerCase()) + "&units=metric&appid=8b10912e19fde267f36f6cb785ee7efd";
Log.d(TAG, "onCreate: staring download task");
DownloadJSON downloadJSON = new DownloadJSON();
downloadJSON.execute(url);
Log.d(TAG, "onCreate: after downloadtask");
}
}
});
}
public void SetDayListData(ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
if (dayAdapter == null)
{
dayAdapter = new DayAdapter(MainActivity.this,R.layout.layout_day_card, days, weatherDataArrayList);
dayListView.setAdapter(dayAdapter);
}
else
{
//created a new method "UpdateData" just to update the data in the adapter
dayAdapter.UpdateData(days, weatherDataArrayList);
dayAdapter.notifyDataSetChanged();
}
}
private class DownloadJSON extends AsyncTask<String, Void, String>
{
private static final String TAG = "DownloadJSON";
private String downloadJSON(String url)
{
StringBuilder jsonResult = new StringBuilder();
try
{
URL apiURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
int responseCode = connection.getResponseCode();
Log.d(TAG, "downloadJSON: Response code "+ responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charReader;
char[] inputBuffer = new char[500];
while (true)
{
charReader = reader.read(inputBuffer);
if (charReader < 0)
{
break;
}
if (charReader > 0)
{
jsonResult.append(String.copyValueOf(inputBuffer, 0, charReader));
}
}
reader.close();
return jsonResult.toString();
}
catch (MalformedURLException e)
{
Log.e(TAG, "downloadJSON: URL is Invalid");
}
catch (IOException e)
{
Log.e(TAG, "downloadJSON: IO Error");
}
return null;
}
#Override
protected String doInBackground(String... strings)
{
Log.d(TAG, "doInBackground: url is : " + strings[0]);
String jsonResponse = downloadJSON(strings[0]);
if (jsonResponse == null)
{
Log.e(TAG, "doInBackground: Error downloading");
}
return jsonResponse;
}
#Override
protected void onPostExecute(String jsonResponse)
{
super.onPostExecute(jsonResponse);
Log.d(TAG, "onPostExecute: json received is : " + jsonResponse);
if (jsonResponse != null)
{
JsonToWeatherData jtwd = new JsonToWeatherData();
weatherDataArrayList = jtwd.extractor(jsonResponse);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String date1 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date2 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date3 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date4 = simpleDateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE,1);
String date5 = simpleDateFormat.format(calendar.getTime());
ArrayList<String> days = new ArrayList<>();
days.add(date1);
days.add(date2);
days.add(date3);
days.add(date4);
days.add(date5);
SetDayListData(days, weatherDataArrayList);
}
else
{
Log.d(TAG, "onPostExecute: no json recieved, city is Wrong");
Toast toast = Toast.makeText(MainActivity.this,"Please provide a valid city!",Toast.LENGTH_LONG);
toast.show();
}
}
}
}
public class DayAdapter extends ArrayAdapter<String>
{
private static final String TAG = "DayAdapter";
private Context context;
private LayoutInflater layoutInflater;
private int layoutresourceID;
private ArrayList<String> dayBlock;
private ArrayList<WeatherData> dayWeather, weatherBlock;
JsonToWeatherData json = new JsonToWeatherData();
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
super(context, resource, dayBlock);
this.context = context;
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
layoutInflater = LayoutInflater.from(context);
this.layoutresourceID = resource;
if (weatherBlock == null)
{
Log.e(TAG, "DayAdapter: full block is null");
}
}
#Override
public int getCount()
{
return dayBlock.getSize();
}
public void UpdateData(#NonNull ArrayList<String> dayBlock, ArrayList<WeatherData> weatherBlock)
{
this.dayBlock = dayBlock;
this.weatherBlock = weatherBlock;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
{
convertView = layoutInflater.inflate(layoutresourceID,parent,false);
}
if (weatherBlock == null)
{
Log.d(TAG, "getView: weatherBlock is null");
return convertView;
}
TextView date = (TextView) convertView.findViewById(R.id.date);
TextView minTempFoDay = (TextView) convertView.findViewById(R.id.minTempOfDay);
TextView maxTempFoDay = (TextView) convertView.findViewById(R.id.maxTempOfDay);
ListView weatherHolderListView = (ListView) convertView.findViewById(R.id.wHoldLV);
String dateString = dayBlock.get(position);
dayWeather = json.extractByDate(weatherBlock, dateString);
if (dayWeather == null)
{
Log.d(TAG, "getView: dayweather array is null");
return convertView;
}
if (position > dayWeather.getSize() - 1)
{
Log.d(TAG, "getView: the position is too great for the dayWeather array");
return convertView;
}
String test = dayWeather.get(position).getTemp(); // error occured here
Log.d(TAG, "getView: test string : " + test);
date.setText(dateString);
DecimalFormat df = new DecimalFormat(".##");
float mint = 500, maxt = 0;
String mint1 = "", maxt1 = "";
for (WeatherData data : dayWeather)
{
if (mint > Float.parseFloat(data.getMinTemp()))
{
mint = Float.parseFloat(data.getMinTemp());
mint1 = df.format(mint);
Log.d(TAG, "getView: mint : " + mint);
}
if (maxt > Float.parseFloat(data.getMaxTemp()))
{
maxt = Float.parseFloat(data.getMaxTemp());
maxt1 = df.format(maxt);
}
}
minTempFoDay.setText(mint1);
maxTempFoDay.setText(maxt1);
WeatherAdapter weatherAdapter = new WeatherAdapter(context, R.layout.weather_holder, dayWeather);
weatherHolderListView.setAdapter(weatherAdapter);
return convertView;
}
}
Im using a library to read contacts on Android SDK and ive been trying to adapt the solution for a successful build and proper function. The issue I am running into is that the ArrayList is not being recognized which I'm guessing is a symptom of a small issue (perhaps breakpoints) or related to layout issues. I'm still fairly new with Android so thank you for your help.
The mainactivity.java code is below.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactlist_android_items);
}
public class Android_Contact {
public String android_contact_Name = "";
public String android_contact_TelefonNr = "";
public int android_contact_ID = 0;
public void fp_get_Android_Contacts() {
ArrayList<Android_Contact> arrayList_Android_Contacts = new ArrayList<Android_Contact>();
}
Cursor cursor_Android_Contacts = null;
ContentResolver contentResolver = getContentResolver();
try {
cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
} catch(Exception ex){
Log.e("Error on contact", ex.getMessage());
}
if(cursor_Android_Contacts.getCount()>0) {
while (cursor_Android_Contacts.moveToNext()) {
Android_Contact android_contact = new Android_Contact();
String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
android_contact.android_contact_Name = contact_display_name;
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, null
, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
, new String[]{contact_id}
, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
android_contact.android_contact_TelefonNr = phoneNumber;
}
phoneCursor.close();
}
arrayList_Android_Contacts.add(android_contact);
}
Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayList_Android_Contacts);
listView_Android_Contacts.setAdapter(adapter);
}
}
public class Adapter_for_Android_Contacts extends BaseAdapter {
Context mContext;
List<Android_Contact> mList_Android_Contacts;
public Adapter_for_Android_Contacts(Context mContext, List<Android_Contact> mContact) {
this.mContext = mContext;
this.mList_Android_Contacts = mContact;
}
#Override
public int getCount() {
return mList_Android_Contacts.size();
}
#Override
public Object getItem(int position) {
return mList_Android_Contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(mContext, R.layout.contactlist_android_items, null);
TextView textview_contact_Name = (TextView) view.findViewById(R.id.textview_android_contact_name);
TextView textview_contact_TelefonNr = (TextView) view.findViewById(R.id.textview_android_contact_phoneNr);
textview_contact_Name
.setText(mList_Android_Contacts
.get(position).android_contact_Name);
textview_contact_TelefonNr
.setText(mList_Android_Contacts
.get(position).android_contact_TelefonNr);
view.setTag(mList_Android_Contacts
.get(position).android_contact_Name);
return view;
}
}
}
while (cursor_Android_Contacts.moveToNext()) {
Android_Contact android_contact = new Android_Contact();
String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
android_contact.android_contact_Name = contact_display_name;
//----< get phone number >----
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, null
, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
, new String[]{contact_id}
, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//< set >
android_contact.android_contact_TelefonNr = phoneNumber;
//</ set >
}
phoneCursor.close();
}
//----</ set >----
//----</ get phone number >----
// Add the contact to the ArrayList
arrayList_Android_Contacts.add(android_contact);
}
//----</ #Loop: all Contacts >----
//< show results >
Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayList_Android_Contacts);
listView_Android_Contacts.setAdapter(adapter);
//</ show results >
The problem is that your arrayList_Android_Contacts is not declared in all the scopes you are using it. Putting it as a member of your class will probably do the trick (from a compilation perspective):
public class Android_Contact {
public String android_contact_Name = "";
public String android_contact_TelefonNr = "";
public int android_contact_ID = 0;
private ArrayList<Android_Contact> arrayList_Android_Contacts = new ArrayList<Android_Contact>();
....
}
Another thing you should probably do is to remove or change fp_get_Android_Contacts().
I have a JSON like this
{
"questions": [{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
},
{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
}
]
}
I have added values of lets suppose "Answer_Video_Link" into Arraylist for e.g arraylistAnswerLink so the output will be like[null,null,....so on]
As setting this arraylist in a BaseAdapter,the functionality is want to achieve is:
if(arraylistAnswerLink.get(position).contains(null)){
button.setVisibilty(View.Visible)}
else{
button.setVisibilty(View.Gone)
}
This my json parsing code
jsonInnerArray = jsonInnerObject.getJSONArray("questions");
for (int j = 0; j <= jsonInnerArray.length(); j++) {
jsonArrayObject = jsonInnerArray.getJSONObject(j);
Question_Video_Title = jsonArrayObject.getString("Question_Video_Title");
question_video_playingTime = jsonArrayObject.getString("question_video_playingTime");
String Designation1 = jsonArrayObject.getString("Designation");
full_name = jsonArrayObject.getString("User_name"); Question_Video_Link = jsonArrayObject.getString("Question_Video_Link");
Answer_Video_Link = jsonArrayObject.getString("Answer_Video_Link");
QuestionID = jsonArrayObject.getString("QuestionID");
video_thumbnail=jsonArrayObject.getString("video_thumbnail"); }
am having error of array index out of bound while fetching null at a particular position of the list.
Please check my code
public class UnRepliedFragment_ extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
View rootview;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// ArrayList<Integer> arrayListImage;
ArrayList<Integer> arrayListVideos;
File mediaFile, vPath;
String song_dur_str, st, vst, vst1, orginalName;
String timestamp, advisorID, token;
int VIDEO_CAPTURE = 1000;
ProgressDialog dlg;
SharedPreferences preferences;
ArrayList<String> arrayListName, videoName, singleVideoName, questionLink, arrquestion_video_playingTime, answerLinkEmpty;
String FirstName, durationofVideo, User_name, Question_Video_Title, Question_Video_Link, shorted, cmpsort, question_video_playingTime, path, QuestionID;
int advisor, pos;
private List<Modals> feedsList;
Uri mediaPath;
PutObjectRequest por;
String url = "https://s3-us-west-1.amazonaws.com/talentedge1";
private static AmazonS3Client sS3Client;
Uri fileUri;
static Object Answer_Video_Link;
ArrayList<Object> answerLink;
Object item;
JSONObject jsonObject,innerObject;
JSONArray innerArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_unreplied, container, false);
dlg = new ProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
token = preferences.getString(AppConstant.TOKEN, "");
advisorID = preferences.getString(AppConstant.USERID, "");
arrayListVideos = new ArrayList<>();
feedsList = new ArrayList<>();
arrayListName = new ArrayList<>();
videoName = new ArrayList<>();
questionLink = new ArrayList<>();
arrquestion_video_playingTime = new ArrayList<>();
answerLink = new ArrayList<>();
singleVideoName = new ArrayList<>();
/*
API hit
*/
new Proadvice().execute();
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view_unreplied);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootview;
}
/*
Adapter class
*/
class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
ArrayList<String> videoName;
ArrayList<String> questionLink;
ArrayList<String> arrquestion_video_playingTime;
ArrayList<Object> answerLink;
public MyRecyclerViewAdapter(ArrayList<String> videoName, ArrayList<String> questionLink, ArrayList<Object> answerLink, ArrayList<String> arrquestion_video_playingTime) {
this.videoName = videoName;
this.questionLink = questionLink;
this.answerLink = answerLink;
this.arrquestion_video_playingTime = arrquestion_video_playingTime;
}
#Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.unreplied_list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
holder.txt_it_author.setText(arrayListName.get(position));
holder.textView.setText(arrquestion_video_playingTime.get(position));
holder.txt_it_Title.setText(videoName.get(position));
for (Object value : answerLink) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
#Override
public int getItemCount() {
return videoName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView, txt_it_author, txt_it_Title, share;
RippleView relativeLayout;
LinearLayout imageButtonAnswer;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = (RippleView) itemView.findViewById(R.id.relative_video_it);
relativeLayout.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.img_it_Video);
textView = (TextView) itemView.findViewById(R.id.txt_it_duration);
txt_it_author = (TextView) itemView.findViewById(R.id.txt_it_author);
txt_it_Title = (TextView) itemView.findViewById(R.id.txt_it_Title);
imageButtonAnswer = (LinearLayout) itemView.findViewById(R.id.img_answers);
frameLayout = (FrameLayout) itemView.findViewById(R.id.relative_play_img);
imageButtonAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
int id = v.getId();
switch (id) {
case R.id.relative_play_img:
Intent i = new Intent(getActivity(), Video_ViewAct.class);
i.putExtra("position", "" + position);
i.putExtra("Question_Video_Link", questionLink.get(position));
// i.putExtra("Answer_Video_Link", answerLink.get(position));
startActivity(i);
break;
}
}
}
}
class Proadvice extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return doInLoginProadvice();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dlg.setMessage("Loading.....");
dlg.setCancelable(false);
dlg.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (result.contains("true")) {
updateUIProadvice(result);
}
}
}
private void updateUIProadvice(String result) {
try {
jsonObject = new JSONObject(result);
String message = jsonObject.getString("message");
innerObject = jsonObject.getJSONObject("Object");
innerArray = innerObject.getJSONArray("details");
// Log.e("arr", " " + arr);
for (int i = 0; i <= innerArray.length(); i++) {
JSONObject obj = innerArray.getJSONObject(i);
String advisorID = obj.getString("AdvisorID");
FirstName = obj.getString("FirstName");
String LastName = obj.getString("LastName");
String Email = obj.getString("Email");
String Password = obj.getString("Password");
String Designation = obj.getString("Designation");
String Company = obj.getString("Company");
String Location = obj.getString("Location");
String Description = obj.getString("Description");
String Profile_Pic_Small = obj.getString("Profile_Pic_Small");
String Profile_Pic_Original = obj.getString("Profile_Pic_Original");
String No_Questions = obj.getString("No_Questions");
String No_Answers = obj.getString("No_Answers");
String No_Up_Votes = obj.getString("No_Up_Votes");
String No_Followers = obj.getString("No_Followers");
String IsActive = obj.getString("IsActive");
String Created = obj.getString("Created");
String Modified = obj.getString("Modified");
JSONArray arr1 = innerObject.getJSONArray("questions");
for (int j = 0; j <= arr1.length(); j++) {
JSONObject obj1 = arr1.getJSONObject(j);
Question_Video_Title = obj1.getString("Question_Video_Title");
question_video_playingTime = obj1.getString("question_video_playingTime");
String Designation1 = obj1.getString("Designation");
User_name = obj1.getString("User_name");
Question_Video_Link = obj1.getString("Question_Video_Link");
shorted = Question_Video_Title.replace("=", " ");
cmpsort = shorted.replace("-", " ");
Answer_Video_Link = obj1.get("Answer_Video_Link");
QuestionID = obj1.getString("QuestionID");
videoName.add((cmpsort));
questionLink.add(Question_Video_Link);
answerLink.add(Answer_Video_Link);
arrayListName.add(User_name);
arrquestion_video_playingTime.add(question_video_playingTime);
mAdapter = new MyRecyclerViewAdapter(videoName, questionLink, answerLink, arrquestion_video_playingTime);
mRecyclerView.setAdapter(mAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String doInLoginProadvice() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConstant.getAdvivisorDetail);
httppost.addHeader("APIKEY", "123ABC890567");
httppost.addHeader("Token", token);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("AdvisorID", advisorID));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
Here is the Simple Way to Parse JSON array and easily get Null as well as a value pair . Important Thing Do not use variable name as a capital letter it must be start with lower case.
please find programme and you can modify it according to Your Requirement
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class UnRepliedFragment_ {
//Define this as a global varraible
static Object Advisor_User_ID;
static Object Creator_User_ID;
static Object Question_Video_Title;
static Object playing_time;
static Object Created;
static Object Modified;
static Object question_video_playingTime;
static Object Answer_Video_Title;
static Object Answer_Video_Link;
static Object answer_video_playingtime;
static Object StatusName;
static Object QuestionID;
static ArrayList al;
public void onBindViewHolder() {
for (Object value : al) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
private void updateUIProadvice(String result) {
//Since i have an limited JSON so Accroding to that i did parsing . Dont try with getString just try with Get();//method
try {
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(result);
org.json.simple.JSONArray lang = (org.json.simple.JSONArray) jsonObject.get("questions");
for (int i = 0; i < lang.size(); i++) {
}
Iterator i = lang.iterator();
while (i.hasNext()) {
org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next();
Creator_User_ID = innerObj.get("Creator_User_ID").toString();
Advisor_User_ID = innerObj.get("Advisor_User_ID");
Question_Video_Title = innerObj.get("Question_Video_Title");
playing_time = innerObj.get("playing_time");
Created = innerObj.get("Created");
Modified = innerObj.get("Modified");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
Answer_Video_Link = innerObj.get("Answer_Video_Link");
answer_video_playingtime = innerObj.get("answer_video_playingtime");
StatusName = innerObj.get("StatusName");
QuestionID = innerObj.get("QuestionID");
// Storing data into arrayList
al = new ArrayList();
al.add(Creator_User_ID);
al.add(Advisor_User_ID);
al.add(Question_Video_Title);
al.add(playing_time);
al.add(Created);
al.add(Modified);
al.add(question_video_playingTime);
al.add(Answer_Video_Link);
al.add(Answer_Video_Title);
al.add(answer_video_playingtime);
al.add(QuestionID);
al.add(StatusName);
// First Way to get element one by one
for (Object value : al) {
if (value != null) {
System.out.println("Not Null:" + value);
} else {
System.out.println("Null:" + value);
}
}
//or Second Way
Object valuenext=al.get(0); // Get First Index Value
System.out.println(valuenext);
}
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
I have jsonParse method inside a onCreateView. I have 3 pages in my application. Every time, when I
open a page data created all of the time and I want to check therefore whether there is already something at the current position. Now, my question is what are recommended way to check a certain data already exists in the ArrayList.
Here is my code :
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
public static int pageNumber;
public static int PAGE_NUM = ScheduleMainActivity.NUM_PAGES ;
public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
public int getPageNumber;
private void jsonParseData(int _getPageNumber) {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
// Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
_getPageNumber = getPageNumber;
JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
String getDate = jsonObject.getString("date");
// data.add(new ScheduleItem(getDate));
JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));
for (int i = 0; i < getFirstArray.length(); i++) {
JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
String time = getJSonObj.getString("time");
//Log.e("Time Log",time);
String type = getJSonObj.getString("type");
String title = getJSonObj.getString("title");
int typeId = getJSonObj.getInt("type_id");
data.add(new ScheduleItem(time, title, typeId, getDate));
Log.e("Check Size", String.valueOf(data.size()));
/*
* Get Events
*/
if (typeId == 0) {
JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));
for (int j = 0; j < getEventsArray.length(); j++) {
JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
int typeEventId = getJSonEventobj.getInt("type_id");
if (typeEventId == 1) {
String EventInfo = getJSonEventobj.getString("info");
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
typeEventId, getDate));
} else {
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
getDate));
}
}
}
}
//Log.e("Check Date", String.valueOf(data.get(_getPageNumber).getDate()));
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
getPageNumber = pageNumber;
/**
* JSON Parsing
*/
checker = getPageNumber + 1;
jsonParseData(getPageNumber);
/**
* Set header date
*/
((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
final ListView list = (ListView)rootView.findViewById(R.id.list);
BinderData bindingData = new BinderData(this.getActivity(), data);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (data.get(position).getItemType() == 0
|| data.get(position).getItemType() == 3
|| data.get(position).getItemType() == 2)
return;
Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
ContentExtended.class);
intent.putExtra("title", data.get(position).getTitle());
intent.putExtra("content", data.get(position).getContent());
startActivity(intent);
}
});
ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
if (pageNumber == 0)
ibLeft.setVisibility(View.INVISIBLE);
else
ibLeft.setVisibility(View.VISIBLE);
ibLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() > 0)
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
});
ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
if (pageNumber + 1 == PAGE_NUM)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < PAGE_NUM)
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
});
return rootView;
}
public static Fragment create(int position) {
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
public static Fragment create(int position, ViewPager _pager) {
pageNumber = position;
pager = _pager;
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
}
}
If the objects inside the ArrayList has the equal methods properly overridden and defined you can use the contains method.
Whenever you need to check if your List contains something, you should use Set instead of List. HashSet for example.