ListView Doesn't display anymore than 8 ImageViews - java

I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}

Related

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 (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

Lisview inside a Listview not working

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;
}
}

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

sent parameter to adapter in same class android

I have public class StudioDetail (main class) and in StudioDetail I generate private class SendfeedbackKelas like this :
private class SendfeedbackKelas extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariKelas";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
final String idstudio= extras.getString("STUDIO_ID");
#Override
protected String doInBackground(String... params) {
String date = params[0];
Utils.log("params 1:" + date);
// do above Server call here
kelasstudioList = new ArrayList<KelasStudioModel>();
String responseString = null;
final String url_kelas_studio = Constant.URI_BASE_STUDIO + idstudio + "/class" + "?date=" + date + "&token=" + token;
Utils.log("url kelas studio:"+ url_kelas_studio);
try
{
runOnUiThread(new Runnable() {
public void run() {
new JSONAsyncTask().execute(url_kelas_studio);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new ClassSAdapter(context, R.layout.jadwalstudio_info, kelasstudioList);
listview.setAdapter(adapter);
}
});
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
that called ClassSAdapter like this :
private class ClassSAdapter extends ArrayAdapter<KelasStudioModel> {
final Context context = getContext();
ArrayList<KelasStudioModel> kelasstudioList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ClassSAdapter(Context context, int resource, ArrayList<KelasStudioModel> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
kelasstudioList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pesan_kelas);
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
/*studio_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, StudioDetail.class);
startActivity(intent);
}
});*/
dialog.show();
}
};
View.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pelatih);
/*final String url_studio_image = Constant.URI_FRONTEND + "vendor_trainer/20150821052441-tanda-tanya.jpg";
Utils.log("url_studio_image: " + url_studio_image);
new DownloadImageTask((ImageView) dialog.findViewById(R.id.class_image_pelatih)).execute(url_studio_image);*/
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
};
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.kelas = (TextView) v.findViewById(R.id.kelas);
holder.waktu = (TextView) v.findViewById(R.id.waktu);
holder.pelatih = (TextView) v.findViewById(R.id.pelatih);
// set OnClickListeners
holder.kelas.setOnClickListener(listener1);
holder.pelatih.setOnClickListener(listener2);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.promo_1);
holder.kelas.setText(kelasstudioList.get(position).getKelas());
holder.waktu.setText(kelasstudioList.get(position).getWaktu());
holder.pelatih.setText(kelasstudioList.get(position).getPelatih());
// set tags
holder.kelas.setTag(position);
holder.waktu.setTag(position);
holder.pelatih.setTag(position);
return v;
}
private class ViewHolder {
public TextView kelas;
public TextView waktu;
public TextView pelatih;
}
}
I want to sent some parameter like this from class JSONAsyncTask to private class ClassSAdapter on View.OnClickListener listener1 and View.OnClickListener listener2 :
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
How to sent that parameter?
As information here is JSONAsynTask class:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private static final String TAG_CLASSES = "classes";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi classes: " + responseAsText);
JSONObject jsonObj = new JSONObject(responseAsText);
// Getting JSON Array node
JSONArray classes = jsonObj.getJSONArray(TAG_CLASSES);
for(int i=0;i<classes.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = classes.getJSONObject(i);
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
KelasStudioModel actor = new KelasStudioModel();
String starttime = parseDateToHis((String) object.getString("startdate")).toString();
String endtime = parseDateToHis((String) object.getString("enddate")).toString();
actor.setKelas(Html.fromHtml((String) object.getString("masterclass_name")).toString());
actor.setWaktu(starttime + "-" + endtime);
actor.setPelatih(object.getString("trainer_name"));
kelasstudioList.add(actor);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false){
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
}
}
}
listener 1 and listener 2 called different dialog.

accessing specific itemview in listview in button onclick method

public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "**";
private static String url_update_bet = "**";
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog tDialog;
private BetDisplayer currentitem;
private HashMap<String, String> userhash = new HashMap<>();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
private HashMap<String, String> useroutcomes = new HashMap<>();
private HashMap<String, String> finalhash = new HashMap<>();
private ArrayList<Map<String, String>> passtocheck = new ArrayList<>();
private HashMap<String, HashMap<String, String>> passtocheckver2 = new HashMap<>();
private String name;
private HashMap<String, String> allopens = new HashMap<>();
JSONParser jsonParser = new JSONParser();
// Creating JSON Parser object
JSONParsers jParser = new JSONParsers();
ArrayList<HashMap<String, String>> bet;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BET = "bet";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_USER = "user";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
name = (getIntent().getExtras().getString("user")).toLowerCase();
Log.d("name", name);
// Hashmap for ListView
bet = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Games. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, Teams));
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
if (a.get(TAG_STATUS).equals("open")) {
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
}
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")){
listwriter.get(p).setStatus("open");
}
else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
new UpdateBetStatus().execute();
}
}
}
Log.d("USEROUTCOMES", useroutcomes.toString());
PopulateList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class UpdateBetStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* *
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(DisplayAllBets.this);
tDialog.setMessage("Loading your bets! Good luck!");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
}
/**
* Creating product
* *
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", currentitem.getId()));
params.add(new BasicNameValuePair("stake", Integer.toString(currentitem.getStake())));
params.add(new BasicNameValuePair("user", name));
params.add(new BasicNameValuePair("returns", Integer.toString(currentitem.getReturns())));
params.add(new BasicNameValuePair("teams", currentitem.getSelections()));
params.add(new BasicNameValuePair("status", currentitem.getStatus()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_bet,
"POST", params);
// check log cat fro response
Log.d("Printing", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* * * *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
private class MyListAdapter extends ArrayAdapter<BetDisplayer> {
public MyListAdapter() {
super(DisplayAllBets.this, R.layout.activity_singletotalbet, listwriter);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.activity_singletotalbet, parent, false);
}
BetDisplayer currentwriter = listwriter.get(position);
Log.d("TESTING", currentwriter.getSelections());
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setTag(Integer.toString(position));
Log.d("TESTING2", currentwriter.getSelections());
String selections = currentwriter.getSelections();
int numberofselections = 0;
for (int i = 0; i < selections.length(); i++) {
if (selections.charAt(i) == '/') {
numberofselections++;
}
}
if (numberofselections == 1) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Single");
} else if (numberofselections == 2) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Double");
} else if (numberofselections == 3) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Treble");
} else {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Accumulator" + "(" + numberofselections + ")");
}
TextView status = (TextView) itemView.findViewById(R.id.status);
status.setText(currentwriter.getStatus());
return itemView;
}
}
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
}
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
I have a populated listview. Each item in the list contains a button and a few TextViews, in the following format.
I created a method which is run when any of the buttons is clicked. What I need it to do is to retrieve that particular itemView at that position in the listview so I can access the TextViews in that itemview. This is my code but it isn't working atm.
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
Assuming your ListView listener starts here.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
You don't have to write
View selItem = (View) list.getItemAtPosition(position);
since you already got reference to the particular View in ListView from the overridden onItemClick method.
So you can skip that line and directly access TextView
TextView status = (TextView) v.findViewById(R.id.status);
Finally the code will be like
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
//Already got reference to View v
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
To catch onListItemClick add listener in PopulateList() method:
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
// Change children of list item here
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
To catch click on button in your list item you need in your adapter's getView() method add click listener to button:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button click
}
});
}
EDIT:
To store data create fields in Activity and setters for it:
private String text1;
private String text2;
public void setText1(String text){
text1 = text;
}
public void setText2(String text){
text2 = text;
}
Then set it in button click listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv1 = (TextView) itemView.findViewById(R.id.textview1_id);
TextView tv2 = (TextView) itemView.findViewById(R.id.textview2_id);
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText1(tv1.getText());
setText2(tv2.getText());
}
});
}

Categories

Resources