I'm using a view pager with a sliding panel inside, so when my panel is expanded it creates a request of users and instantiates viewholders to show them in the list view, the problem is that they get instantiated on wherever they want, how I can tell in what fragment it should be instantiated.
Here is my code:
#Override
public void onPanelAnchored(View panel) {
final View cView = panel;
EndpointInterface Service = ServiceAuthGenerator.createService(EndpointInterface.class);
currentID = sharedpreferences.getInt("CURRENTID", 0);
Call<List<Ride>> call = Service.getPassengers(currentRide);
call.enqueue(new Callback<List<Ride>>() {
#Override
public void onResponse(Response<List<Ride>> response, Retrofit retrofit) {
if (response.isSuccess() && !response.body().isEmpty()) {
dialogx.dismiss();
ArrayList<String> myUsersName = new ArrayList<>();
ArrayList<String> myUsersLastName = new ArrayList<>();
ArrayList<String> myUsersMapDirection = new ArrayList<>();
ArrayList<Integer> myUsersID = new ArrayList<>();
ArrayList<Boolean> myUsersRole = new ArrayList<>();
for (int i = 0; i < response.body().size(); i++) {
myUsersRole.add(response.body().get(i).getRole());
myUsersName.add(response.body().get(i).getUser().getFirst_name());
myUsersLastName.add(response.body().get(i).getUser().getLast_name());
myUsersMapDirection.add(getAdress(new LatLng(response.body().get(i).getOrigin_lat(), response.body().get(i).getOrigin_lng())));
myUsersID.add(response.body().get(i).getId());
currentName = myUsersName.get(i) + " " + myUsersLastName.get(i);
mMap.addMarker(new MarkerOptions().snippet(getAdress(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng()))).position(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng())).title(response.body().get(Integer.valueOf(i)).getUser().getFirst_name()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
ListAdapter userAdapter = new CustomAdapterRequest(MainMenu.this, myUsersName, myUsersLastName, myUsersMapDirection, myUsersID, myUsersRole, currentRide);
ListView userListView = (ListView) cView.findViewById(R.id.listViewUserRequest);
userListView.setAdapter(userAdapter);
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
}
});
}
Also, here is my adapter code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myViewHolder holder = null;
if (row == null) {
LayoutInflater customInflater = (LayoutInflater) contexto.getSystemService(contexto.LAYOUT_INFLATER_SERVICE);
row = customInflater.inflate(R.layout.custom_row_request, parent, false);
holder = new myViewHolder(row);
row.setTag(holder);
} else {
holder = (myViewHolder) row.getTag();
}
String singleNameItem = itemName.get(position);
String singleLastNameItem = itemLastName.get(position);
String singleDir = itemDirection.get(position);
Integer singleID = itemIDs.get(position);
Boolean singleRole = itemRoles.get(position);
holder.tv_name.setText(singleNameItem + " " + singleLastNameItem);
holder.tv_Direction.setText(singleDir);
holder.im_profilepic.setImageResource(R.mipmap.profile_photo3);
return row;
}
And my holder class.
class myViewHolder {
TextView tv_name;
TextView tv_Direction;
ImageView im_profilepic;
myViewHolder(View v) {
tv_name = (TextView) v.findViewById(R.id.nameText);
tv_Direction = (TextView) v.findViewById(R.id.originText);
im_profilepic = (ImageView) v.findViewById(R.id.ivImage);
}
}
This is the Fragment class
public class fragment1 extends Fragment {
public fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (CardView) inflater.inflate(R.layout.layout1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setTextDestination(String origin, String Destination, Long Date, String estimatedTime, boolean singleRole) {
TextView tv_Destination = (TextView) getView().findViewById(R.id.TextDestination);
TextView tv_origin = (TextView) getView().findViewById(R.id.TextOrigin);
TextView tv_Date = (TextView) getView().findViewById(R.id.textDatePager);
TextView tv_EstimatedTiem = (TextView) getView().findViewById(R.id.estimatedTimeRoute);
ImageView iv_roleType = (ImageView) getView().findViewById(R.id.ImgView_roleTypeLayout1);
tv_Destination.setText(Destination);
tv_origin.setText(origin);
iv_roleType.setImageResource(singleRole ? R.mipmap.steerorange3 : R.mipmap.handorange3);
tv_EstimatedTiem.setText(estimatedTime);
java.util.Date date = new Date(Date * 1000L);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getDefault());
String formatted = format.format(date);
tv_Date.setText(formatted);
}
}
I created a list of fragment1 which is mu fragment class and added it to a list, then depending on how many items on the list I have is the number of instances I get, my set text function works correctly but I don't know how to do that with the list view!
Thanks! :D
moved the method that added the list view to the fragment that was instantiated.
Related
I am watching the monitor on Android and I notice that the memory keeps increasing when you scroll down and up.
I am using an Adaper. It's supposed to reuse the views, but it seems that it doesn't work.
As you can see in the images below the memory starts at 9.94 MB and I could increase it at 25.82 MB just by scrolling down and up.
You can see the code that I use.
public class ListMainFragment
extends Fragment
implements LoaderManager.LoaderCallbacks<List<Earthquake>> {
public ListMainFragment() {
// Required empty public constructor
}
ListView listView;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.fragment_mainlist, container, false);
final ArrayList<Earthquake> earthquake =
(ArrayList<Earthquake>) new EarthquakeController(new EarthquakesJson()).getListOfEarthquakes();
listView = (ListView)viewRoot.findViewById(R.id.list_view);
EarthquakeAdapter noteAdapter = new EarthquakeAdapter(getActivity(), earthquake);
listView.setAdapter(noteAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//final String mensaje = notas.get(position).getMag();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(earthquake.get(0).getMapURL()));
Log.w("ListView", "Se despliega la siguente URL " + earthquake.get(0).getMapURL());
startActivity(intent);
}
});
return viewRoot;
}
}
The Adapter:
public class EarthquakeAdapter extends ArrayAdapter <Earthquake> {
public EarthquakeAdapter(Context context, ArrayList<Earthquake> notas) {
super(context, 0, notas);
}
private static final String LOCATION_SEPARATOR = " of";
View view;
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
*/
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
Log.w("AppList", "converView es null");
}
Earthquake note = getItem(position);
Date dateObject = new Date(note.getTimeInMilliseconds());
TextView locationOffset = (TextView)convertView.findViewById(R.id.listItem_tv_locationOffset);
TextView place = (TextView)convertView.findViewById(R.id.listItem_tv_place);
TextView date = (TextView)convertView.findViewById(R.id.lisItem_tv_date);
TextView time = (TextView)convertView.findViewById(R.id.lisItem_tv_time);
TextView mag = (TextView) convertView.findViewById(R.id.listItem_tv_mag);
GradientDrawable magnitudCicle = (GradientDrawable) mag.getBackground();
magnitudCicle.setColor(getMagnitudColor(note.getMag()));
String str_locationOffset, str_place;
if (note.getPlace().contains(LOCATION_SEPARATOR)) {
String [] locations = note.getPlace().split(LOCATION_SEPARATOR);
str_locationOffset = locations[0];
str_place = locations[1];
}
else {
str_place = note.getPlace();
str_locationOffset = getContext().getString(R.string.near_the);
}
mag.setText( new DecimalFormat("0.0").format(note.getMag()));
date.setText(formatDate(dateObject));
place.setText(str_place);
time.setText(formatTime(dateObject));
locationOffset.setText(str_locationOffset);
/* final String mensaje = title.getText().toString();
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),mensaje,Toast.LENGTH_SHORT).show();
}
});*/
return convertView;
}
}
You should use Recycler View for better performance.
From: https://developer.android.com/training/material/lists-cards.html
I used GridView to display images of types of batteries. When user clicks any image, the features of that particular battery will get print on next page. The images and features are fetching from the server. The problem is the first battery image is displaying when I opened the GridView, but the other battery images are displaying in that GridView only after I scroll the screen two to three times. But I want to display all the images once I opened the GridView.
private void getDatasFromIntent() {
alHM = new ArrayList<>();
Intent intent = getIntent();
String typeResp = intent.getStringExtra("IMG_S");
try {
JSONObject jsonObject = new JSONObject(typeResp);
JSONArray jsonArray = jsonObject.getJSONArray("process");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hm = new HashMap<>();
JSONObject bat_json = jsonArray.getJSONObject(i);
String battery_featues_id = bat_json.getString("battery_featues_id");
String battery = bat_json.getString("battery_type");
String battery_image = bat_json.getString("battery_image");
battery_image = battery_image.replace("\\", "");
hm.put("battery_featues_id", battery_featues_id);
hm.put("battery_type", battery);
hm.put("battery_image", battery_image);
alHM.add(hm);
}
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this, alHM);
// Set custom adapter to gridview
GridView gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(SampleBatteryList.this, "a: " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GridviewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> list;
private final SampleBatteryList activity;
public GridviewAdapter(SampleBatteryList sampleBatteryList,
ArrayList<HashMap<String, String>> alHM) {
this.activity = sampleBatteryList;
this.list = alHM;
Log.d("VOLLY", "ADP :" + alHM);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class ViewHolder {
public ImageView imgViewFlag;
public TextView txtViewTitle;
public Button button;
ViewHolder view;
}
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
}
here you are using view holder class but after initialization part and assign value part are in if and else so value not showing.
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
change to
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
}else{
view = (ViewHolder) contentView.getTag();
}
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
return contentView;
}
I am new to Android and I am trying to do this. I have an ArrayAdapter, a Fragment using this adapter and a class that runs a timer task every 15 mins to hit an api and update my cached superobject. This superobject contains a field list. Also, I am using a calendar to filter from this list and my fragment displays the filtered list. So when i click on a date on calendar, SampleObjects with that creation date will be shown in the fragment. I want to force update this list whenever my timer task updates the superobject. Is it possible and if so, how?
public class ScheduleAdapter extends ArrayAdapter<SampleObject> {
private List<SampleObject> objects;
public void setObjects(List<SampleObject> objects) {
this.objects = objects;
}
public ScheduleAdapter(Context context, List<SampleObject> objects) {
super(context, R.layout.schedule_list_item, R.id.schedule_list_layout, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(getContext()).inflate(R.layout.schedule_list_item, parent, false);
ViewHolder holder = new ViewHolder(row);
row.setTag(holder);
final SampleObject sam = objects.get(position);
if (row == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
row = inflater.inflate(R.layout.schedule_list_item, parent, false);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.customerView.setText(sampleObject.getStatus());
holder.addressView.setText(cleaningJob.getShortenedAddress());
holder.timingView.setText(sampleObject.getFormattedStartTime() + "-" + cleaningJob.getFormattedEndTime());
holder.iconView.setImageResource(R.drawable.ic_clear);
return row;
}
public static class ViewHolder {
public final ImageView iconView;
public final TextView customerView;
public final TextView addressView;
public final TextView timingView;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
customerView = (TextView) view.findViewById(R.id.list_item_customer_textview);
addressView = (TextView) view.findViewById(R.id.list_item_address_textview);
timingView = (TextView) view.findViewById(R.id.list_item_timing_textview);
}
}
}
}
public class ScheduleFragment extends Fragment {
private static final String LOG_TAG = "ScheduleFragment";
private ScheduleAdapter mScheduleAdapter;
public static final String ARGS_CLEANING_JOB_ID = "id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
Date requestedDate = null;
if (args != null) {
int day = args.getInt("date");
int month = args.getInt("month");
int year = args.getInt("year");
requestedDate = BasicUtility.constructDate(day, month, year);
}
List<SampleObject> sampleObjs = Collections.EMPTY_LIST;
if (requestedDate != null) {
List<SampleObject> sampleObjsFromController = ScheduleController.getSampleObjByDate(requestedDate);
if (CollectionUtils.isNotEmpty(sampleObjsFromController)) {
sampleObjs = sampleObjsFromController;
}
}
mScheduleAdapter =
new ScheduleAdapter(getActivity(), sampleObjs);
View scheduleListView = inflater.inflate(R.layout.schedule_list_fragment, container, false);
ListView listView = (ListView) scheduleListView.findViewById(R.id.schedule_list);
listView.setAdapter(mScheduleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
SampleObject job = mScheduleAdapter.getItem(position);
Bundle bundle = new Bundle();
bundle.putString(ARGS_CLEANING_JOB_ID, job.getUniqueIdentifier());
Intent intent = new Intent(getActivity(), DetailActivity.class).putExtras(bundle);
startActivity(intent);
}
});
return scheduleListView;
}
}
public class CalendarFragment extends Fragment {
private static final String LOG_TAG = "CalendarFragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calendar_view, container, false);
CalendarView calendarView = (CalendarView) rootView.findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
Log.d(LOG_TAG, "Showing item for date " + i + "::" + i1+ "::" + i2);
Bundle args = new Bundle();
Fragment frag = new ScheduleFragment();
frag.setArguments(args);
args.putInt("date", i2);
args.putInt("month", i1 + 1);
args.putInt("year", i);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.schedule_list_container,frag, MainActivity.SCHEDULEFRAGMENT_TAG)
.commit();
}
});
return rootView;
}
}
public class ScheduleController {
private static Map<String, List<String>> sampleObjsByDate = new HashMap<>();
private static final String LOG_TAG = "ScheduleController";
static {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Log.i(LOG_TAG, "updating schedule...");
populateSchedule();
}
};
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 15*60*1000);
}
public static void populateSchedule() {
//populate SuperObject here
}
public static List<SampleObject> getCleaningJobByDate(Date date) {
//filter list here
}
I should not have used a timerTask in the first place. I am using the IntentService now with AlarmManager and ResultReceiver and it worked like a charm. If someone else is looking for the same funcitonality, follow the tutorial https://guides.codepath.com/android/Starting-Background-Services
I am working on a grocery list app and having trouble refreshing the list view after adding a new item. After I add a new item in the database the ListView is not refreshed. If I go in the item details page and then come back to main activity the onCreate is called again and it refreshes it correctly.
If I call the refresh method in the addItemToDb() (on button clicked) method it duplicates my items but does not add them to the database.
Has anyone had this problem before???
Here is the code:
The list view adapter
public class ItemListViewAdapter extends ArrayAdapter<ItemModel> {
Activity activity;
int layoutResource;
ArrayList<ItemModel> itemModelArrayList = new ArrayList<>();
public ItemListViewAdapter(Activity act, int resource, ArrayList<ItemModel> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
itemModelArrayList = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return itemModelArrayList.size();
}
#Override
public ItemModel getItem(int position) {
return itemModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null || (row.getTag()) == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.hItemName = (TextView) row.findViewById(R.id.custom_row_productName);
holder.hItemPrice = (TextView) row.findViewById(R.id.custom_row_productPrice);
holder.hItemType = (TextView) row.findViewById(R.id.custom_row_productType);
holder.hCheckBox = (CheckBox) row.findViewById(R.id.custom_row_checkBox);
holder.hItemEdit = (ImageView) row.findViewById(R.id.custom_row_edit);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.hModel = getItem(position);
holder.hItemName.setText(holder.hModel.getItemName());
holder.hItemPrice.setText(String.valueOf(holder.hModel.getItemPrice()));
holder.hItemType.setText(holder.hModel.getItemType());
holder.hItemEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemID = holder.hModel.getItemId();
String itemName = holder.hModel.getItemName();
String itemPrice = String.valueOf(holder.hModel.getItemPrice());
String itemType = holder.hModel.getItemType();
String itemDate = holder.hModel.getItemDate();
Intent intent = new Intent(activity, ItemDetail.class);
intent.putExtra("id", itemID);
intent.putExtra("product", itemName);
intent.putExtra("price", itemPrice);
intent.putExtra("type", itemType);
intent.putExtra("date", itemDate);
startActivity(activity, intent, null);
}
});
return row;
}
public class ViewHolder {
ItemModel hModel;
TextView hItemName;
TextView hItemPrice;
TextView hItemType;
TextView hItemDate;
CheckBox hCheckBox;
ImageView hItemEdit;
}
}
And main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(getApplicationContext());
itemNameText = (EditText) findViewById(R.id.activity_main_productName);
itemPriceText = (EditText) findViewById(R.id.activity_main_productPrice);
itemTypeSpinner = (Spinner) findViewById(R.id.activity_main_spinner);
addButton = (Button) findViewById(R.id.activity_main_addButton);
saveListButton = (FloatingActionButton) findViewById(R.id.activity_main_fab);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.productTypes, R.layout.spinner_item);
itemTypeSpinner.setAdapter(spinnerAdapter);
//USE BUTTONS
addButton.setOnClickListener(this);
saveListButton.setOnClickListener(this);
//LIST_VIEW
listView = (ListView) findViewById(R.id.activity_main_listView);
//calling methods
refreshData();
}
public void refreshData() {
modelArrayListContainer.clear();
//GET ITEMS FROM DB
ArrayList<ItemModel> modelArrayListFromDB = dbHandler.getAllItems();
for (int i = 0; i < modelArrayListFromDB.size(); i++) {
int ditemID = modelArrayListFromDB.get(i).getItemId();
String dItemName = modelArrayListFromDB.get(i).getItemName();
double dItemPrice = modelArrayListFromDB.get(i).getItemPrice();
String dItemType = modelArrayListFromDB.get(i).getItemType();
String dItemDate = modelArrayListFromDB.get(i).getItemDate();
ItemModel newModel = new ItemModel();
newModel.setItemId(ditemID);
newModel.setItemName(dItemName);
newModel.setItemPrice((int) dItemPrice);
newModel.setItemType(dItemType);
newModel.setItemDate(dItemDate);
modelArrayListContainer.add(newModel);
}
//setup Adapter
itemListViewAdapter = new ItemListViewAdapter(MainActivity.this, R.layout.custom_product_layout_activity_main, modelArrayListContainer);
listView.setAdapter(itemListViewAdapter);
itemListViewAdapter.notifyDataSetChanged();
}
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
}
}
You need to call refreshData() in your addItemToDb function like:
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
refreshData();
}
But if you need to update data automatically from database, you need to use CursorAdaptor and use Content Providers
UPDATE
Also change your getAllItems() function in dbhandler and include the following statement in the first line of the function:
modelArrayList.clear();
I'm using Volley and GSON to parse a remote JSON. Here is my Fragment that does it:
public class LatestFragment extends ListFragment implements OnScrollListener {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
arrItemList = new ArrayList<ItemListModel>();
va = new LatestAdapter(getActivity(), arrItemList);
lv = getListView();
setListAdapter(va);
lv.setOnScrollListener(this);
loadItemList(1);
}
private void loadItemList(int page) {
mRequestQueue = Volley.newRequestQueue(getActivity());
GsonRequest<LatestContainer> myReq = new GsonRequest<LatestContainer>(
Method.GET, url, LatestContainer.class,
createMyReqSuccessListener(), createMyReqErrorListener());
mRequestQueue.add(myReq);
}
private Response.Listener<LatestContainer> createMyReqSuccessListener() {
return new Response.Listener<LatestContainer>() {
#Override
public void onResponse(LatestContainer response) {
try {
for (int i = 0; i < response.getResults().size(); i++) {
ItemListModel ilm = new ItemListModel();
ilm.setCategory(response.getResults().get(i).getCategory());
ilm.setItem_id(response.getResults().get(i).getItem_id());
ilm.setName(response.getResults().get(i).getName());
ilm.setPrice(response.getResults().get(i).getPrice());
ilm.setUser_id(response.getResults().get(i).getUser_id());
arrItemList.add(ilm);
}
LatestAdapter
public class LatestAdapter extends BaseAdapter {
public LatestAdapter(Context context, ArrayList<ItemListModel> items) {
this.arrItemList = items;
this.context = context;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
lf = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
vh = new ViewHolder();
view = lf.inflate(R.layout.row_latest_listview, null);
vh.tvName = (TextView) view.findViewById(R.id.txtItemName);
vh.tvCategory = (TextView) view.findViewById(R.id.txtCategory);
vh.tvPrice = (TextView) view.findViewById(R.id.txtPrice);
vh.tvThumbnail = (ImageView) view.findViewById(R.id.imgPhoto);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
ItemListModel nm = arrItemList.get(i);
vh.tvCategory.setText(nm.getCategory());
vh.tvPrice.setText("RM " + nm.getPrice());
vh.tvName.setText(nm.getName());
return view;
}
However, after I run the code, the listview doesn't seem to be populated. But the parsing is successful. I can see the parsed string in the logcat. So deserialization is not an issue here. What did I do wrong now?
Make sure you call va.notifyDataSetChanged() after modifying the adapter's dataset.