I am running into an issue where I use 2 separate adapters, and 2 seperate GridViews (1 Adapter, for 1 GridView), and am basically removing items from either adapter, and adding it to the other if the item is pressed, and vice versa.
When I press and item in one GridView, the item will be removed from its respective adapter and put into the other GridView and its respective adapter. The issue seems to be with the way the data is being stored (potentially) because when I add the item to the adapter, the icons are totally different from what they should be.
Note: I also noticed that this only happens for the items pressed after the first one is pressed. So the first items data will be added/removed properly. However, I have found that when the item that takes on the first position of the associated adapter, will now have the icon of the previously removed item.
What can I do so ensure that the data stays consistent with the item that is pressed?.
Adapter Class
public class MiscChargeOptionsAdapter extends ArrayAdapter<CarClassSettingDetails> {
private LayoutInflater inflater;
public MiscChargeOptionsAdapter(Context context, List<CarClassSettingDetails> settingList) {
super(context, R.layout.misc_charge_option_layout, R.id.option_grid_option_text, settingList);
inflater = LayoutInflater.from(context);
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CarClassSettingDetails settingsDetails = this.getItem(position);
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.misc_charge_option_layout, null);
vh.optionText = (TextView) convertView.findViewById(R.id.option_grid_option_text);
vh.settingView = (SettingView) convertView.findViewById(R.id.option_grid_option_icon);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.optionText.setText(settingsDetails.getName());
vh.settingView.setIcon(settingsDetails.getIcon());
vh.settingView.setIconSelected(settingsDetails.getIconSelected());
vh.settingView.setViewBackgroundColor(settingsDetails.getViewBackgroundColor());
vh.settingView.setBackgroundColorSelected(settingsDetails.getBackgroundColorSelected());
vh.settingView.setAmountBackgroundColor(settingsDetails.getAmountBackgroundColor());
vh.settingView.setAmountTextColor(settingsDetails.getAmountTextColor());
vh.settingView.setValue(settingsDetails.getValue());
vh.settingView.setIgnoreSetState(true);
vh.settingView.setTag(position);
return convertView;
}
class ViewHolder {
private TextView optionText;
private SettingView settingView;
/* public ViewHolder(TextView optionText, SettingView settingView) {
this.optionText = optionText;
this.settingView = settingView;
}*/
public TextView getOptionText() {
return optionText;
}
public SettingView getSettingView() {
return settingView;
}
}
}
How the adapters are set
selectedAdapter = new CarClassOptionsAdapter(getActivity(), selectedSettingsList);
unselectedAdapter = new CarClassOptionsAdapter(getActivity(), unselectedSettingsList);
gridSelected.setAdapter(selectedAdapter);
gridSelected.setOnItemClickListener(this);
gridUnselected.setAdapter(unselectedAdapter);
gridUnselected.setOnItemClickListener(this);
How I am adding/removing items from the adapters
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (parent.getAdapter() == selectedAdapter) {
//TODO: ADD DIALOGS
unselectedAdapter.add(selectedAdapter.getItem(position));
unselectedAdapter.notifyDataSetChanged();
selectedAdapter.remove(selectedAdapter.getItem(position));
selectedAdapter.notifyDataSetChanged();
} else if (parent.getAdapter() == unselectedAdapter) {
//TODO: ADD DIALOGS
selectedAdapter.add(unselectedAdapter.getItem(position));
selectedAdapter.notifyDataSetChanged();
unselectedAdapter.remove(unselectedAdapter.getItem(position));
unselectedAdapter.notifyDataSetChanged();
}
}
This is how the CarClassSettingDetails class is being populated
private void addMiscChargeSelected(Ws_MiscChargeSelected miscChargeSelected, boolean isSelected) {
try {
CarClassSettingDetails settingDetails = new CarClassSettingDetails(getActivity());
if (miscChargeSelected.getCode() != null && !miscChargeSelected.getCode().equals("")) {
settingDetails.setCode(miscChargeSelected.getCode());
}
if (miscChargeSelected.getName() != null && !miscChargeSelected.getName().equals("")) {
settingDetails.setName(miscChargeSelected.getName());
}
if (miscChargeSelected.getIcon() != null && !miscChargeSelected.getIcon().equals("")) {
Bitmap settingIcon = IconUtils.loadIcon(getActivity(), miscChargeSelected.getIcon());
Bitmap settingIconSelected = IconUtils.loadIcon(getActivity(), miscChargeSelected.getIcon());
settingDetails.setIcon(settingIcon);
settingDetails.setIconSelected(settingIconSelected);
}
if (miscChargeSelected.getValue() != null && !miscChargeSelected.getValue().equals("")) {
settingDetails.setValue(Ws_Value.fromInt(Integer.parseInt(miscChargeSelected.getValue())));
settingDetails.setAmountBackgroundColor(Color.parseColor("#00ffffff"));
settingDetails.setAmountTextColor(Color.parseColor("#ff00428e"));
} else {
settingDetails.setValue(null);
}
settingDetails.setViewBackgroundColor(Color.parseColor("#ffd4d4d4"));
settingDetails.setBackgroundColorSelected(Color.parseColor("#ff616161"));
if (isSelected) {
//TODO: ADD TO TOP ADAPTER
selectedSettingsList.add(settingDetails);
} else {
//TODO: ADD TO BOTTOM ADAPTER
unselectedSettingsList.add(settingDetails);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
Misc Charge Details
public class MiscChargeSettingDetails {
private Context context;
private String code;
private String name;
private String description;
private Bitmap icon = null;
private Bitmap iconSelected = null;
private Ws_Value value = null;
private int amountBackgroundColor, amountTextColor, viewBackgroundColor, backgroundColorSelected;
public MiscChargeSettingDetails(Context context) {
this.context = context;
}
protected Context getContext() {
return context;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public Bitmap getIconSelected() {
return iconSelected;
}
public void setIconSelected(Bitmap iconSelected) {
this.iconSelected = iconSelected;
}
public Ws_Value getValue() {
return value;
}
public void setValue(Ws_Value value) {
this.value = value;
}
public int getAmountBackgroundColor() {
return amountBackgroundColor;
}
public void setAmountBackgroundColor(int amountBackgroundColor) {
this.amountBackgroundColor = amountBackgroundColor;
}
public int getAmountTextColor() {
return amountTextColor;
}
public void setAmountTextColor(int amountTextColor) {
this.amountTextColor = amountTextColor;
}
public int getViewBackgroundColor() {
return viewBackgroundColor;
}
public void setViewBackgroundColor(int viewBackgroundColor) {
this.viewBackgroundColor = viewBackgroundColor;
}
public int getBackgroundColorSelected() {
return backgroundColorSelected;
}
public void setBackgroundColorSelected(int backgroundColorSelected) {
this.backgroundColorSelected = backgroundColorSelected;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Can you show the place where you're populating the list of SettingViews? Is your data model (SettingView) extends View? It is not the best idea to use the view object as model..
Related
I am able to Save the JSON Data to the Realm Database. I have used as the documentation of the Realm, but I am not able to set the data to the GridView. I am using Custom Adapter not the Realm Adapter. The Data are Logged but they are not Displayed to the GridView. How can this the Data be Retrieved and Displayed to the GridView?
PopularDestinationGridDetail this is where JSON data is parsed and saved to database
Realm.init(this);
realm = Realm.getDefaultInstance();
LinearAddTOFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savetoDatabase();
}
});
public void savetoDatabase() {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
RealmDatabasePopularDestination realmDatabasePopularDestination = bgRealm.createObject(RealmDatabasePopularDestination.class);
realmDatabasePopularDestination.setTitle(title);
realmDatabasePopularDestination.setTitle(latitude);
realmDatabasePopularDestination.setTitle(longitude);
realmDatabasePopularDestination.setImage(image);
// Toast.makeText(this, realmDatabasePopularDestination.setLatitude(realmDatabasePopularDestination1.getLatitude()))
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.v("Success",title);
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.e("failed", error.getMessage());
}
});
}
Favourites
public class Favourites extends Fragment {
Realm realm;
GridView gridViewBookmark;
ArrayList<RealmDatabasePopularDestination> destination_bookmark_realm = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Realm.init(getContext());
realm = Realm.getDefaultInstance();
RealmDatabasePopularDestination realmDatabasePopularDestination = new RealmDatabasePopularDestination();
View view = inflater.inflate(R.layout.bookmark_layout_gridview, container, false);
gridViewBookmark = (GridView) view.findViewById(R.id.gridviewBookmark);
destination_bookmark_realm.add(realmDatabasePopularDestination);
getData();
return view;
}
public void getData() {
FavouriteAdapter favouriteAdapter = new FavouriteAdapter(getContext(), destination_bookmark_realm);
gridViewBookmark.setAdapter(favouriteAdapter);
RealmResults<RealmDatabasePopularDestination> result = realm.where(RealmDatabasePopularDestination.class).equalTo("Title","niyash temple").findAll();
result.load();
System.out.println("Result is" + result);
// String output = "";
// for (RealmDatabasePopularDestination realmDatabasePopularDestination : result) {
//
//
// output += realmDatabasePopularDestination.toString();
//
// }
//
// System.out.println("output" + output);
// System.out.println("Total size=" + result.size());
}
}
getter and setter
public class RealmDatabasePopularDestination extends RealmObject {
String Title;
String Latitude;
String Longitude;
String image;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
FavouriteAdapter
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null;
String TAG = "HomeTab_adapter";
public FavouriteAdapter(Context mContext, ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark) {
super();
this.mContext = mContext;
this.clas_realm_bookmark = clas_realm_bookmark;
}
#Override
public int getCount() {
return clas_realm_bookmark.size();
}
#Override
public Object getItem(int position) {
return clas_realm_bookmark.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final FavouriteAdapter.Holder viewHolder;
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.bookmark_grid_list_item, parent, false);
// well set up the ViewHolder
// viewHolder = new ClassScheduleStudentAdapter.Holder();
viewHolder = new FavouriteAdapter.Holder();
// viewHolder.popular_destintion_id = (TextView) convertView.findViewById(R.id.student_profile_subject);
viewHolder.title = (TextView) convertView.findViewById(R.id.festivalName);
viewHolder.imageLogo = (ImageView) convertView.findViewById(R.id.event_festival_main_image);
// Log.d(TAG, "## postion:" + position + " getTeacherName" + class_destination.get(position).getId());
convertView.setTag(viewHolder);
} else {
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
// viewHolder = (ClassScheduleStudentAdapter.Holder) convertView.getTag();
viewHolder = (Holder) convertView.getTag();
}
viewHolder.title.setText(clas_realm_bookmark.get(position).getTitle());
Picasso.with(mContext).load(clas_realm_bookmark.get(position).getImage()).error(R.drawable.close).into(viewHolder.imageLogo);
return convertView;
}
class Holder {
TextView title;
ImageView imageLogo;
}
}
I am not getting any error but they are not set on the ListView.This is the first time using realm, so don't get where I am doing wrong.
Instead of
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null;
You should be using RealmBaseAdapter from realm-android-adapters as specified in the documentation.
you are setting adapter to list view before extracting data from database.
RealmResults<RealmDatabasePopularDestination> result = realm.where(RealmDatabasePopularDestination.class).equalTo("Title","niyash temple").findAll();
result.load();
FavouriteAdapter favouriteAdapter = new FavouriteAdapter(getContext(), destination_bookmark_realm);
gridViewBookmark.setAdapter(favouriteAdapter);
use above code and.
destination_bookmark_realm it should be load with the result you got from databse
I am using a RecyclerView inside a Fragment to display a list of categories ( as shown in the images). When a category is selected, a new Activity starts with a RecyclerView. Each item from the list has a TextView and an icon for favorite ( the star from the top-right corner ). Once the favorite icon is pressed, the TextView will be saved to another Activity called Favorites.
The problem: let's say that I select Category A and I press the favorite button for the first 2 items. Everything looks good, the items are saved to Favorites. If I select Category B, bamm, I find the first 2 items selected...I go to Category C, same thing!
So if I check the favorite button once, it checks for all Adapters, like they're communicating. Why is this happening?
Although the favorite buttons are checked, I can't find the TextView's from Category B or C in the Favorites activity.
The Activity that starts when a category item is selected:
public class CategoriesDetailActivity extends AppCompatActivity {
Adapter0 ca0;
RecyclerView recList;
public CategoriesDetailActivity() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories_detail_activity);
Bundle bundle = this.getIntent().getExtras();
// Bundle bundle = this.getArguments();
bundle.getInt("id");
int position = bundle.getInt("id");
if (bundle.containsKey("id")) {
position = bundle.getInt("id");
} else {
this.finish();
}
recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
switch (position) {
case 0:
ca0 = new Adapter0(this, createList0(99));
recList.setAdapter(ca0);
break;
case 1:
ca0 = new Adapter0(this, createList1(80));
recList.setAdapter(ca0);
break;
...
}
}
private List<BeanSampleList> createList0(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text1[i];
ci.id = i;
result.add(ci);
}
return result;
}
private List<BeanSampleList> createList1(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text2[i];
ci.id = i;
result.add(ci);
}
return result;
}
#Override
public void onResume() {
super.onResume();
if (recList.getAdapter() == ca0) {
ca0.notifyDataSetChanged();
} if (recList.getAdapter() == ca1) {
ca1.notifyDataSetChanged();
} else {
// nothing
}
}
}
The Adapter class:
public class Adapter0 extends RecyclerView.Adapter<Adapter0 .ContactViewHolder> {
private Context context;
List<BeanSampleList> postBeanSampleList;
SharedPreference sharedPreference;
BeanSampleList beanSampleList;
public Adapter0 (Context context, List<BeanSampleList> postBeanSampleList) {
this.context = context;
this.postBeanSampleList = postBeanSampleList;
sharedPreference = new SharedPreference();
}
#Override
public int getItemCount() {
return postBeanSampleList.size();
}
public Object getItem(int position) {
return postBeanSampleList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder,final int i) {
beanSampleList = (BeanSampleList) getItem(i);
holder.vName.setText(beanSampleList.getTitle());
if (checkFavoriteItem(beanSampleList)) {
holder.btnFavourite.setLiked(true);
holder.btnFavourite.setTag("active");
} else {
holder.btnFavourite.setLiked(false);
holder.btnFavourite.setTag("deactive");
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.categories_detail_adapter, viewGroup, false);
return new ContactViewHolder(itemView);
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements OnLikeListener {
protected TextView vName;
protected LikeButton btnFavourite;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.t1);
btnFavourite = (LikeButton) v.findViewById(R.id.favouritesToggle);
btnFavourite.setOnLikeListener(this);
}
#Override
public void liked(LikeButton likeButton) {
final int position = getAdapterPosition();
if (likeButton.getId() == btnFavourite.getId()) {
String tag = btnFavourite.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
sharedPreference.addFavorite(context, postBeanSampleList.get(position));
btnFavourite.setTag("active");
btnFavourite.setLiked(true);
}
Snackbar snackbar = Snackbar
.make(likeButton, "Added to Favorites!", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}
#Override
public void unLiked(LikeButton likeButton) {
final int position = getAdapterPosition();
if (likeButton.getId() == btnFavourite.getId()) {
sharedPreference.removeFavorite(context, postBeanSampleList.get(position));
btnFavourite.setTag("deactive");
btnFavourite.setLiked(false);
Snackbar snackbar = Snackbar
.make(likeButton, "Removed from Favorites!", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}
}
public boolean checkFavoriteItem(BeanSampleList checkProduct) {
boolean check = false;
List<BeanSampleList> favorites = sharedPreference.loadFavorites(context);
if (favorites != null) {
for (BeanSampleList product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
For the past 2 days I've been trying to fix this but I just can't figure out what's causing this. I also tried to use different Adapters for each position but with no success.
public class BeanSampleList {
public int id;
public String title;
public String subTitle;
public String bottomTitle;
public String imageView;
public BeanSampleList() {
super();
}
public BeanSampleList(int id, String title, String subTitle, String bottomTitle, String imageView) {
super();
this.id = id;
this.title = title;
this.subTitle = subTitle;
this.bottomTitle = bottomTitle;
this.imageView = imageView;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitleBottom() {
return bottomTitle;
}
public void setTitleBottom(String bottomTitle) {
this.bottomTitle = bottomTitle;
}
public String getImageView() {
return imageView;
}
public void setImageView(String imageView) {
this.imageView = imageView;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BeanSampleList other = (BeanSampleList) obj;
if (id != other.id)
return false;
return true;
}
}
Thank you so much and sorry for my english.
I think the error is in your id generation for BeanSampleList
private List<BeanSampleList> createList0(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text1[i];
ci.id = i;
result.add(ci);
}
return result;
}
private List<BeanSampleList> createList1(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text2[i];
ci.id = i;
result.add(ci);
}
return result;
}
You need to generate unique id for your BeanSamleList objects in createList* method. As in your current code the objects are the same from the equals method side (their id are from 0 to list_size range).
Or add some unique modifier to compare in equal, like add the position of parent list
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BeanSampleList other = (BeanSampleList) obj;
if (id != other.id)
return false;
if (listId != other.listId)
return false;
return true;
}
You need to find a different way to uniquely identify each BeanSampleList element. Just matching id is not good enough. Perhaps you could also match the titles if you know they will be unique. Or generate unique Ids for each of these elements say by dividing the integer domain in different ranges e.g. 1 to 1000000 is for category 1, 1000001 to 2000000 for category 2 and so on.
I have a adapter with this code:
public class LoadOrders_adapter extends BaseAdapter {
private JSONArray data;
private Context context;
public LoadOrders_adapter(JSONArray data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.length();
}
#Override
public Object getItem(int position) {
try {
return data.get(position);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.loading_orderlist, parent, false);
ImageView product_images=(ImageView) row.findViewById(R.id.product_images);
TextView Total_quantity = (TextView) row.findViewById(R.id.Total_quantity);
TextView order_status=(TextView) row.findViewById(R.id.order_status);
TextView order_date = (TextView) row.findViewById(R.id.order_date);
TextView order_id = (TextView) row.findViewById(R.id.order_id);
TextView product_Name=(TextView) row.findViewById(R.id.product_Name);
try {
JSONObject temp = data.getJSONObject(position);
Picasso.with(context).load(WebConnection.getInstance().resource_url(temp.getString("imgUrl"))).into(product_images);
Total_quantity.setText(temp.getString("Quantity"));
order_date.setText(temp.getString("Date_Sub"));
order_id.setText("#"+temp.getString("Order_ID"));
order_status.setText(temp.getString("Status"));
product_Name.setText(temp.getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
return row;
}
}
And a class called:
public class LoadOrders extends ActionBarActivity implements Top_fragment.Top_fragmentListener {
private JSONArray data = null;
private JSONArray OrderDetails2 = null;
private ListView Normal_Orders_list;
private String previous_activity = "info.sliit.mystyle.Home";
private String title_name = "Your Normal Orders";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_promotional_wear);
Normal_Orders_list = (ListView)findViewById(R.id.Normal_Orders_list);
new BackgroundProcess().execute();
}
class BackgroundProcess extends AsyncTask<Void,Void,Void> {
ProgressDialog progressDialog = new ProgressDialog(LoadOrders.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading data...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
data = WebConnection.getInstance().get_request("Loading_order_rest/orderloading/user_id/12","json");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
BaseAdapter baseAdapter1 = new LoadOrders_adapter(data,LoadOrders.this);
Normal_Orders_list.setAdapter(baseAdapter1);
//Normal_Orders_list.setOnItemClickListener();
}
}
#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_customized_orders,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);
}
#Override
public String get_previous_activity() {
return previous_activity;
}
#Override
public String getTitle_name() {
return title_name;
}
}
I have an activity called Activity_loading_orders which has a list view called Normal_Orders_list and i have another layout called loading_orderlist which has has a RelativeLayout with some Textviews and a button. As you can see in the code the layout loading_orderlist is loaded as an list item into the Normal_Orders_list activity. What i want to do is to remove list items when the button is clicked see image http://i.imgur.com/TYAqd0t.jpg
My Jason taken from postman
<?xml version="1.0" encoding="utf-8"?>
<xml><data><datum><Order_ID>8</Order_ID><Quantity>52</Quantity><Comment>fs</Comment><Date_Sub>2015-08-27</Date_Sub><Date_Del/><Product_ID/><Customer_ID>12</Customer_ID><Status>Accepted</Status><View>Unread</View><Name>T-shirt</Name><imgUrl>\assets\images\projectpics\normalt\Edited_front.jpg</imgUrl></datum><datum><Order_ID>10</Order_ID><Quantity>45</Quantity><Comment>sf</Comment><Date_Sub>2015-08-27</Date_Sub><Date_Del/><Product_ID/><Customer_ID>12</Customer_ID><Status>Accepted</Status><View>Unread</View><Name>T-shirt</Name><imgUrl>\assets\images\projectpics\normalt\Edited_front.jpg</imgUrl></datum></data></xml>
Consider moving the JSON parsing outside of getView(). What you're going to want to do is:
Have a (preferably) List of <ParsedJsonObject> (from parsing the JSON) instead of a JsonArray
On 'cancel' click: delete item at position from the List
After deleting the item from the list, notify your adapter that it's dataset has changed: mListViewAdapter.notifyDataSetChanged();
Please note: I'm afraid you're going to have to change to a custom ArrayAdapter instead of a BaseAdapter. The reason for this is that you are using a JSONArray as the data set for the adapter. It's not a good idea to start messing with the JSON yourself, but you're going to have to remove the item from the dataset one way or another. I recommend you take a look at libraries such as gson or Genson.
Those libraries can deserialize JSON into Java objects for you. So what'd you'd end up doing:
Fetch JSON data
Deserialize JSON data into Java objects, put these objects into a List<ParsedJsonObject>
Create a new ArrayAdapter<ParsedJsonObject>
Pass along the list of ParsedJsonObjects as the dataset for the ArrayAdapter you just created.
getView() won't have to change a lot, just change where the data comes from. getView() lets you know what position you are in, and considering you passed along a List<ParsedJsonObject>, you can just do list.get(position) to return an object containing all the data.
I hope this helped!
All right, so here's what you need to do:
Create new classes: DataModel.java, Data.java, and Datum.java
Put this in them:
DataModel.java:
public class DataModel {
private Data data;
public Data getData ()
{
return data;
}
public void setData (Data data)
{
this.data = data;
}
}
Data.java:
public class Data {
private Datum[] datum;
public Datum[] getDatum ()
{
return datum;
}
public void setDatum (Datum[] datum)
{
this.datum = datum;
}
}
Datum.java:
public class Datum{
private String Name;
private String View;
private String Status;
private String Quantity;
private String Date_Sub;
private String Comment;
private String Customer_ID;
private String Order_ID;
private String imgUrl;
public String getName ()
{
return Name;
}
public void setName (String Name)
{
this.Name = Name;
}
public String getView ()
{
return View;
}
public void setView (String View)
{
this.View = View;
}
public String getStatus ()
{
return Status;
}
public void setStatus (String Status)
{
this.Status = Status;
}
public String getQuantity ()
{
return Quantity;
}
public void setQuantity (String Quantity)
{
this.Quantity = Quantity;
}
public String getDate_Sub ()
{
return Date_Sub;
}
public void setDate_Sub (String Date_Sub)
{
this.Date_Sub = Date_Sub;
}
public String getComment ()
{
return Comment;
}
public void setComment (String Comment)
{
this.Comment = Comment;
}
public String getCustomer_ID ()
{
return Customer_ID;
}
public void setCustomer_ID (String Customer_ID)
{
this.Customer_ID = Customer_ID;
}
public String getOrder_ID ()
{
return Order_ID;
}
public void setOrder_ID (String Order_ID)
{
this.Order_ID = Order_ID;
}
public String getImgUrl ()
{
return imgUrl ;
}
public void setImgUrl (String imgUrl)
{
this.imgUrl = imgUrl;
}
}
And then in your class do Data d = genson.deserialize(jsonString, DataModel.class);
Inside DataModel is a Data instance and inside that is your array of datum's
I am creating a app that requires information that is in an rss file (will eventually be an actual feed but it doesn't exist yet) to be put into a recycler view, with each separate card showing only a snippet of information and when the user clicks onto the card it opens into another activity to show all the info. However I am not sure how to access the local file as I would an actual live feed. Any help would be much appreciated.
My rss file is in xml format and called dummy_RSS.rss.
I have a class to specify the the strings needed
public class EventViewDetails {
private String title;
private String location;
private String locLat;
private String locLong;
private String date;
private String timeStart;
private String timeFinish;
private String desc;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocLat() {
return locLat;
}
public void setLocLat(String locLat) {
this.locLat = locLat;
}
public String getLocLong() {
return locLong;
}
public void setLocLong(String locLong) {
this.locLong = locLong;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeFinish() {
return timeFinish;
}
public void setTimeFinish(String timeFinish) {
this.timeFinish = timeFinish;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
I have a class to parse the data from the feed into the above strings
public class ParseEventDetails {
private String data;
private ArrayList<EventViewDetails> events;
public ParseEventDetails(String xmlData) {
data = xmlData;
events = new ArrayList<EventViewDetails>();
}
public ArrayList<EventViewDetails> getEvents() {
return events;
}
public boolean process() {
boolean operationStatus = true;
EventViewDetails currentEvent = null;
boolean inEntry = false;
String textValue = "";
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(this.data));
int type = xpp.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
if (type == XmlPullParser.START_TAG) {
if (tagName.equalsIgnoreCase("event")) {
inEntry = true;
currentEvent = new EventViewDetails();
}
} else if (type == XmlPullParser.TEXT) {
textValue = xpp.getText();
} else if (type == XmlPullParser.END_TAG) {
if (inEntry) {
if (tagName.equalsIgnoreCase("event")) {
events.add(currentEvent);
inEntry = false;
}
if (tagName.equalsIgnoreCase("title")) {
currentEvent.setTitle(textValue);
} else if (tagName.equalsIgnoreCase("location")) {
currentEvent.setLocation(textValue);
} else if (tagName.equalsIgnoreCase("date")) {
currentEvent.setDate(textValue);
} else if (tagName.equalsIgnoreCase("timestart")) {
currentEvent.setTimeStart(textValue);
} else if (tagName.equalsIgnoreCase("timefinish")) {
currentEvent.setTimeFinish(textValue);
} else if (tagName.equalsIgnoreCase("loclat")) {
currentEvent.setLocLat(textValue);
} else if (tagName.equalsIgnoreCase("loclong")) {
currentEvent.setLocLong(textValue);
} else if (tagName.equalsIgnoreCase("description")) {
currentEvent.setDesc(textValue);
}
}
}
}
type = xpp.next();
} catch (Exception e) {
e.printStackTrace();
operationStatus = false;
}
return operationStatus;
}
}
I have the adapter for the recycler view
public class EventCalenderAdapter extends RecyclerView.Adapter<EventCalenderAdapter.ViewHolder> {
String xmlData;
static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView titleView;
public ViewHolder(CardView card) {
super(card);
cardView = card;
titleView = (TextView) card.findViewById(R.id.text1);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
CardView v = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.event_task, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
final Context context = viewHolder.titleView.getContext();
viewHolder.titleView.setText(xmlData[i]);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((OnEventView) context).eventView(i);
}
});
}
#Override
public int getItemCount() {
return xmlData.length;
}
}
and I have my fragment
public class EventCalenderFragment extends Fragment {
RecyclerView recyclerView;
EventCalenderAdapter adapter;
public EventCalenderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new EventCalenderAdapter();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_event_calender, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
}
As I have said I'm not sure how to access the local file or where to put the initial access.
you must change access configuration in your phpmyadmin configuration to "allow any" and then the url will be something like that : localhost/your_php_project_name/your_php_file
note that the file your_php_file must return xml data or file
I am looking for something like this:
several <ItemTemplate> in one ListView.
But it was in .ASP and above my level.
What I need
Class Vitals: vTime, BP, Heart Rate, Respirations per Minute, etc.
Class Medications: mTime, RxName, RxRoute, RxDose, RxDoseUnit, etc.
Class Procedures: pTime, Intubation, IV insertion, Defibrillation, etc.
Classes Vitals, Medications and Procedures to be based on user input that inject in to a ListView (sorted chronologically). A "Many-to-One" if I may.
I've went through hours of "CustomAdapter & ListView" tutorials, code samples, walkthroughs.
Here is my current code (trashed and scattered) to show that I am actively working towards a solution:
/*
* Created by SwaLayS on 2/19/2015.
*/
public class VitalAdapter extends BaseAdapter {
private ArrayList<VitalItem> vitalData;
private LayoutInflater layoutInflater;
public VitalAdapter(Context acontext, ArrayList<VitalItem> vitalData){
this.vitalData=vitalData;
layoutInflater=LayoutInflater.from(acontext);
}
#Override
public int getCount() {
return vitalData.size();
}
#Override
public Object getItem(int position) {
return vitalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.vital_view_children,null);
holder = new ViewHolder();
}
}
public class VitalView extends RelativeLayout {
private TextView vTimeTV;
// private TextView vPTATV;
private TextView vRateTV;
private TextView vOxySatTV;
private TextView vSysBPTV;
private TextView vDiaBPTV;
private TextView vRespRateTV;
private TextView vRespEffortTV;
//private TextView vMethodBPTV;
public static VitalView inflate(ViewGroup parent){
VitalView vitalView = (VitalView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.vital_view,parent,false);
return vitalView;
}
public VitalView(Context c){
this(c,null);
}
public VitalView(Context context, AttributeSet attrs){
this(context, attrs,0);
}
public VitalView(Context context, AttributeSet attrs, int defStyle){
super(context,attrs,defStyle);
LayoutInflater.from(context).inflate(R.layout.vital_view_children, this,true);
setupChildren();
}
private void setupChildren(){
vTimeTV = (TextView)findViewById(R.id.vTime);
// vPTATV = (TextView)findViewById(R.id.vPTA);
vRateTV = (TextView) findViewById(R.id.vBPM);
vOxySatTV = (TextView) findViewById(R.id.vOsat);
vSysBPTV = (TextView) findViewById(R.id.vSystolic);
vDiaBPTV = (TextView)findViewById(R.id.vDiastolic);
vRespRateTV = (TextView) findViewById(R.id.vRespRate);
vRespEffortTV = (TextView)findViewById(R.id.vRespEffort);
// vMethodBPTV = (TextView)findViewById(R.id.vMethodBP
}
public void setVital(VitalItem vital){
//vTimeTV.setText(vital.get);
}
}
public class VitalItem {
private String vTime;
// private String vPTA;
private String vRate;
private String vOxySat;
private String vSysBP;
private String vDiaBP;
private String vRespRate;
private String vRespEffort;
// private String vMethodBP;
public VitalItem(String Time, String Rate, String OxySat, String SysBP, String DiaBp, RespRate, String RespEffort){
super();
vTime=Time;
// vPTA=PTA;
vRate=Rate;
vOxySat = OxySat;
vSysBP = SysBP;
vDiaBP = DiaBP;
vRespRate = RespRate;
vRespEffort=RespEffort;
//vMethodBP=MethodBP;
}
public String getvTime() {
return vTime;
}
public void setvTime(String vTime) {
this.vTime = vTime;
}
// public String getvPTA() {
// return vPTA;
// }
// public void setvPTA(String vPTA) {
// this.vPTA = vPTA;
// }
public String getvRate() {
return vRate;
}
public void setvRate(String vRate) {
this.vRate = vRate;
}
public String getvOxySat() {
return vOxySat;
}
public void setvOxySat(String vOxySat) {
this.vOxySat = vOxySat;
}
public String getvSysBP() {
return vSysBP;
}
public void setvSysBP(String vSysBP) {
this.vSysBP = vSysBP;
}
public String getvDiaBP() {
return vDiaBP;
}
public void setvDiaBP(String vDiaBP) {
this.vDiaBP = vDiaBP;
}
public String getvRespRate() {
return vRespRate;
}
public void setvRespRate(String vRespRate) {
this.vRespRate = vRespRate;
}
public String getvRespEffort() {
return vRespEffort;
}
public void setvRespEffort(String vRespEffort) {
this.vRespEffort = vRespEffort;
}
// public String getvMethodBP() {
// return vMethodBP;
//}
// public void setvMethodBP(String vMethodBP) {
// this.vMethodBP = vMethodBP;
//
}
}
I'd appreciate any and everything;
I'm working on a NEMSIS . org project;
I may even be searching with the wrong search terms for what I need.
All help is appreciated
have you try the getViewTypeCount() method in adapter,
it can define different itemView for your different data types.
for your case you need to define three layout items .
search some demos,it may help you .