How to refresh the contents of a list view - android

I have made a list view that shows the contents in the database. But if I add data in the database via a different activity then the modified list view is visible only when I close and then start my app.
So how do I refresh my List view so that as soon as the data is entered, it is visible in the list.
I have heard of notifyDataSetChange() but don't know where to put it in my code.
Please help. The TimePickerPop class is the class that adds data to the database.
public class MainActivityFragment2 extends Fragment {
private List<TimeList> TDList = new ArrayList<TimeList>();
public MainActivityFragment2() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
populateTimeList();
}
private void populateTimeList() {
Context ctx = this.getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInformation(db);
cr.moveToFirst();
String TimeH, TimeM, EtimeH, EtimeM;
do {
TimeH = Integer.toString(cr.getInt(1));
TimeM = Integer.toString(cr.getInt(2));
EtimeH = Integer.toString(cr.getInt(3));
EtimeM = Integer.toString(cr.getInt(4));
TDList.add((new TimeList(TimeH + " : " + TimeM, EtimeH + " : " + EtimeM)));
}while (cr.moveToNext());
}
private class MyAdapter extends ArrayAdapter<TimeList> {
public MyAdapter(Context context, List<TimeList> values) {
super(context, R.layout.time_list_item,values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = LayoutInflater.from(getContext());
if( v == null){
v = inflater.inflate(R.layout.time_list_item, parent, false);
}
TimeList currLoc = TDList.get(position);
TextView theTextView = (TextView) v.findViewById(R.id.time_list_item_textview1);
theTextView.setText(currLoc.getTime());
theTextView = (TextView) v.findViewById(R.id.time_list_item_textview2);
theTextView.setText(currLoc.getDuration());
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.time_list_view, container, false);
ListView list = (ListView) rootView.findViewById(R.id.time_list_view);
ArrayAdapter<TimeList> adapter = new MyAdapter(getActivity(),TDList);
list.setAdapter(adapter);
//adapter.notifyDataSetChanged(); // not working
setRetainInstance(true);
ImageButton ib = (ImageButton) rootView.findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivityFragment2.this.getActivity(), TimePickerPopup.class));
}
});
return rootView;
}
}
This is the TimePickerPopup class.
public class TimePickerPopup extends Activity {
Context ctx =this;
private TimePicker time_picker1;
private TimePicker time_picker2;
private ImageButton select_time1;
private ImageButton select_time2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .7+50));
time_picker1 = (TimePicker) findViewById(R.id.timePicker1);
time_picker2 = (TimePicker) findViewById(R.id.timePicker2);
select_time1 = (ImageButton) findViewById(R.id.selectButton1);
select_time2 = (ImageButton) findViewById(R.id.selectButton2);
select_time1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Start time " + time_picker1.getCurrentHour() + " : " + time_picker1.getCurrentMinute(), Toast.LENGTH_SHORT).show();
ScrollView sv1 = (ScrollView) findViewById(R.id.sv);
sv1.fullScroll(View.FOCUS_DOWN);
}
});
select_time2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"End time " + time_picker2.getCurrentHour() + " : " + time_picker2.getCurrentMinute(), Toast.LENGTH_SHORT).show();
DBoperations db = new DBoperations(ctx);
db.putInfo(db, time_picker1.getCurrentHour(), time_picker1.getCurrentMinute(), time_picker2.getCurrentHour(), time_picker2.getCurrentMinute(), 0, 0);
finish();
}
});
}
}

in your adapter create :
public void notifyChange() {
notifyDataSetChanged();
}
and from your activity call :
adapter.notifyChange();

Related

How to update the value of the textview inside the fragment on the click of the button present in the adapter class in android?

I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.

ArrayAdapter<List<Object>> update on TimerTaskUpdate updating an object

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

How to call a function of different activity from another activity [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
I want to call the function populateTimeList() in MainFragmentActivity2 class from the onClick function of TimePickerPopup class. How do I do so? these are the codes respectively. I am very new to android, please help!
public class MainActivityFragment2 extends Fragment {
private List<TimeList> TDList = new ArrayList<TimeList>();
public MainActivityFragment2() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void populateTimeList() {
Context ctx = this.getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInformation(db);
cr.moveToFirst();
String TimeH, TimeM, EtimeH, EtimeM;
do {
TimeH = Integer.toString(cr.getInt(1));
TimeM = Integer.toString(cr.getInt(2));
EtimeH = Integer.toString(cr.getInt(3));
EtimeM = Integer.toString(cr.getInt(4));
TDList.add((new TimeList(TimeH + " : " + TimeM, EtimeH + " : " + EtimeM)));
}while (cr.moveToNext());
}
private class MyAdapter extends ArrayAdapter<TimeList> {
public MyAdapter(Context context, List<TimeList> values) {
super(context, R.layout.time_list_item,values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = LayoutInflater.from(getContext());
if( v == null){
v = inflater.inflate(R.layout.time_list_item, parent, false);
}
TimeList currLoc = TDList.get(position);
TextView theTextView = (TextView) v.findViewById(R.id.time_list_item_textview1);
theTextView.setText(currLoc.getTime());
theTextView = (TextView) v.findViewById(R.id.time_list_item_textview2);
theTextView.setText(currLoc.getDuration());
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.time_list_view, container, false);
ListView list = (ListView) rootView.findViewById(R.id.time_list_view);
final ArrayAdapter<TimeList> adapter = new MyAdapter(getActivity(),TDList);
list.setAdapter(adapter);
populateTimeList();
setRetainInstance(true);
ImageButton ib = (ImageButton) rootView.findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivityFragment2.this.getActivity(), TimePickerPopup.class));
}
});
return rootView;
}
}
And
public class TimePickerPopup extends Activity {
private List<TimeList> TDList = new ArrayList<TimeList>();
Context ctx =this;
private TimePicker time_picker1;
private TimePicker time_picker2;
private ImageButton select_time1;
private ImageButton select_time2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .7+50));
time_picker1 = (TimePicker) findViewById(R.id.timePicker1);
time_picker2 = (TimePicker) findViewById(R.id.timePicker2);
select_time1 = (ImageButton) findViewById(R.id.selectButton1);
select_time2 = (ImageButton) findViewById(R.id.selectButton2);
select_time1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Start time " + time_picker1.getCurrentHour() + " : " + time_picker1.getCurrentMinute(), Toast.LENGTH_SHORT).show();
ScrollView sv1 = (ScrollView) findViewById(R.id.sv);
sv1.fullScroll(View.FOCUS_DOWN);
}
});
select_time2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"End time " + time_picker2.getCurrentHour() + " : " + time_picker2.getCurrentMinute(), Toast.LENGTH_SHORT).show();
DBoperations db = new DBoperations(ctx);
db.putInfo(db, time_picker1.getCurrentHour(), time_picker1.getCurrentMinute(), time_picker2.getCurrentHour(), time_picker2.getCurrentMinute(), 0, 0);
finish();
}
});
}
}
Basically, I want the data just entered in the database from the TimePickerPopup class to show up in the ListView (i.e. refresh my list view). Presently it shows the new entered data after I close and then start my app.
In your xml file inside <fragment> tag add this.
android:tag="any_tag"
To get current object of a Fragment do this in java file (add this in your TimePickerPopup.java's onClick(View v) method)
MainActivityFragment2 ma2 = (MainActivityFragment2) getFragmentManager().findFragmentByTag("any_tag");
ma2.populateTimeList();

Android fragment BaseAdapter list view not working

I got problem in show list view using BaseAdapter in Fragment activity.
I did not get any error log but list view is not showing,I don't know how solve this ?
My FragmentActivity class :
public class Fragment_Activity extends FragmentActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Occasion";
private static final String TAB_3_TAG = "Friends";
private FragmentTabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
// Get TabHost Refference
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator(""), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator(""), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator(""), ContactActivity.class, null);
// Set drawable images to tab
tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.ic_action_event);
tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.ic_action_phone);
// Set Tab1 as Default tab and change image
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.ic_action_person);
}
}
My contact activity class:
public class ContactActivity extends Fragment implements OnItemClickListener {
private Gson gson = new Gson();
private List<String> userName = new ArrayList<String>();
private List<String> mobileNumber = new ArrayList<String>();
private ContactDispAdapter contactDispAdapter;
private Button btnAdd;
private Button btnSend;
private ProgressDialog prgDialog;
UserDelegate userDelegate = new UserDelegate();
private Context context;
private HashMap<String, UserMO> userMosMapAll = new HashMap<String, UserMO>();
private ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
private UserMO userMO = new UserMO();
private View V;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
V = inflater.inflate(R.layout.contactslistmain, container, false);
context = getActivity().getApplicationContext();
// in contact page click load button get all contacts from device and
// send to server and return matching user
// remove old values from list
userName.clear();
mobileNumber.clear();
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(getActivity());
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
final String[] mobileNumbers = Utility.getAllContacts(context.getContentResolver());
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getMatchingExistingUserList(mobileNumbers, context);
}
#Override
protected void onPostExecute(String contactList) {
if (contactList != "null") {
Toast.makeText(context, "contact String" + contactList, Toast.LENGTH_LONG).show();
List<UserMO> userMOs = gson.fromJson(contactList, new TypeToken<List<UserMO>>() {
}.getType());
Toast.makeText(context, "total items of userMo" + userMOs.size(), Toast.LENGTH_LONG).show();
for (UserMO userMO : userMOs) {
userName.add(userMO.getUserName());
mobileNumber.add(userMO.getMobileNumber());
userMosMapAll.put(userMO.getMobileNumber(), userMO);
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
prgDialog.dismiss();
Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
ListView contactListView = (ListView) V.findViewById(R.id.contact_List_view);
contactDispAdapter = new ContactDispAdapter();
contactListView.setAdapter(contactDispAdapter);
contactListView.setItemsCanFocus(false);
contactListView.setTextFilterEnabled(true);
contactListView.setOnItemClickListener(contactListView.getOnItemClickListener());
}
}
}.execute(null, null, null);
/*
* btnSend = (Button) V.findViewById(R.id.Btn_Send);
* btnSend.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) { ; for (int i = 0; i <
* mobileNumber.size(); i++) { if
* (contactDispAdapter.mCheckStates.get(i) == true) { if
* (userMosMapAll.containsKey(mobileNumber.get(i).toString())) userMO =
* userMosMapAll.get(mobileNumber.get(i).toString());
* System.out.println("Checked......" + mobileNumber.get(i).toString());
* } else { System.out.println("Not Checked......" +
* mobileNumber.get(i).toString()); } }
*
* Intent chatAct = new Intent(context, ChatActivity.class); // Clears
* History of Activity chatAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
* chatAct.putExtra("userMo", userMO); startActivity(chatAct);
*
* } });
*/
btnAdd = (Button) V.findViewById(R.id.btn_Contact_Add);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
// by default first primary user is current user in sql lite
// user table
final UserMO userMO = dbHelper.getRingeeUserData(1);
System.out.println(".............." + contactDispAdapter.mCheckStates.size());
for (int i = 0; i < mobileNumber.size(); i++) {
if (contactDispAdapter.mCheckStates.get(i) == true) {
if (userMosMapAll.containsKey(mobileNumber.get(i).toString())) {
userMOs.add(userMosMapAll.get(mobileNumber.get(i).toString()));
}
System.out.println("Checked......" + mobileNumber.get(i).toString());
} else {
System.out.println("Not Checked......" + mobileNumber.get(i).toString());
}
}
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.addUserRelationShipMapping(userMOs, Long.toString(userMO.getRingeeUserId()));
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(context, "response is " + response.toString(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
}
});
return V;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
contactDispAdapter.toggle(arg2);
}
// add name and mobile number in adapter to show in contact page
private class ContactDispAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView mobileNumTxtV, userNameTxtV;
CheckBox cb;
ContactDispAdapter() {
mCheckStates = new SparseBooleanArray(userName.size());
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return userName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
// show list values name and mobile number in contact page
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.contactlist, null,false);
userNameTxtV = (TextView) vi.findViewById(R.id.text);
mobileNumTxtV = (TextView) vi.findViewById(R.id.mobile_number);
cb = (CheckBox) vi.findViewById(R.id.check_box);
userNameTxtV.setText(userName.get(position));
mobileNumTxtV.setText(mobileNumber.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
My problem is only not showing list view and i got no error.
Please help me...
Advance thanks..

Android ListView Adapter OnClickListener issue

I created a ListView with a custom layout for each view. I have several onClickListeners within the list view adapter for TextView items within the custom layout. The onClickListeners work within the list view adapter and I can obtain the position of the view, but when I try to make calls within the onClickListeners to methods in my activity, I get the "Cannot make a static reference to a non-static method" errors. So I started converting things to static, which made things work as intended, but I'm sure you all know it's a big mistake, which has finally caught up with me.
How the heck do I access methods in my main activity without making the methods static?? I'm new at this, so please forgive my noobish question. Thanks
partial code listing...
public class main extends Activity {
private ArrayList<DataItem> dataItems;
private DataItemAdapter aa;
private ListView dataListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
dataListView.setItemsCanFocus(true);
populateArray();
}
public void populateArray() {
DataItem newItem = new DataItem(
"2008","Ferrari","F430","Red","ASX772"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2008","Ferrari","F430","Black","TZB123"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2009","Ferrari","F430","Red","MIDAS"
);
dataItems.add(0, newItem);
aa.notifyDataSetChanged();
}
public static void modelInfo(int pos) {
Log.i("modelInfo", "=" + pos);
}
public static void makeInfo(int pos) {
Log.i("makeInfo", "=" + pos);
}
public static void assetInfo(int pos) {
Log.i("assetInfo", "=" + pos);
}
}
public class DataItemAdapter extends ArrayAdapter<DataItem> {
private Activity activity;
private int resource;
private static LayoutInflater inflater=null;
public DataItemAdapter(Activity _activity,int _resource,List<DataItem> _items) {
super(_activity, _resource, _items);
inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resource = _resource;
activity = _activity;
}
public static class ViewHolder {
TextView carYear;
TextView carMake;
TextView carModel;
TextView carColor;
TextView assetTag;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(resource, null);
holder=new ViewHolder();
holder.carYear = (TextView)vi.findViewById(R.id.carYear);
holder.carMake = (TextView)vi.findViewById(R.id.carMake);
holder.carModel = (TextView)vi.findViewById(R.id.carModel);
holder.carColor = (TextView)vi.findViewById(R.id.carColor);
holder.assetTag = (TextView)vi.findViewById(R.id.assetTag);
vi.setTag(holder);
} else {
holder=(ViewHolder)vi.getTag();
}
DataItem item = getItem(position);
holder.carYear.setText(item.getCarYear());
holder.carMake.setText(item.getCarMake());
holder.carModel.setText(item.getCarModel());
holder.carColor.setText(item.getCarColor());
holder.assetTag.setText(item.getAssetTag());
holder.carYear.setTag(position);
holder.assetTag.setTag(position);
final OnClickListener makeListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.makeInfo(pos);
}
};
holder.carMake.setOnClickListener(makeListener);
final OnClickListener modelListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.modelInfo(pos);
}
};
holder.carModel.setOnClickListener(modelListener);
final OnClickListener assetListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
main.assetInfo(pos);
}
};
holder.assetTag.setOnClickListener(assetListener);
return vi;
}
why you dont attach an onItemClickListener to your ListView in your activity, instead of perform ItemClick from each inner view in the ListView
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
//attach a listener to the list view
dataListView.setOnItemClickListener (listener);
dataListView.setItemsCanFocus(true);
and inside your listener on onItemClick method you can access the activity methods.
EDIT 1:
the OnItemClickListener gives to you the following parameters, AdapterView parent, View view, int position, long
your individual TextView is a child of the view parameter and you can access to it getting the childAt... something like this:
OnItemClickListener listener = new OnItemClickListener (){
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
((TextView)view.findViewById(R.id.yourTextViewId)).getText();
//or do your stuff
}
}
EDIT 2:
your main activity, remember, by convention all Class name are capitalized, so main class must be Main class
public class Main extends Activity {
private ArrayList<DataItem> dataItems;
private DataItemAdapter aa;
private ListView dataListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dataListView = (ListView)findViewById(R.id.dataListView);
dataItems = new ArrayList<DataItem>();
int resID = R.layout.dataitem;
aa = new DataItemAdapter(this, resID, dataItems);
dataListView.setAdapter(aa);
dataListView.setItemsCanFocus(true);
populateArray();
}
public void populateArray() {
DataItem newItem = new DataItem(
"2008","Ferrari","F430","Red","ASX772"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2008","Ferrari","F430","Black","TZB123"
);
dataItems.add(0, newItem);
newItem = new DataItem(
"2009","Ferrari","F430","Red","MIDAS"
);
dataItems.add(0, newItem);
aa.notifyDataSetChanged();
}
public void modelInfo(int pos) {
Log.i("modelInfo", "=" + pos);
}
public void makeInfo(int pos) {
Log.i("makeInfo", "=" + pos);
}
public void assetInfo(int pos) {
Log.i("assetInfo", "=" + pos);
}
}
Now, your adapter
public class DataItemAdapter extends ArrayAdapter<DataItem> {
private Activity activity;
private int resource;
private LayoutInflater inflater=null;
public DataItemAdapter(Activity _activity,int _resource,List<DataItem> _items) {
super(_activity, _resource, _items);
inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//i always do this way, but i dont think this is the error
//inflater = LayoutInflater.from(_activity.getBaseContext());
resource = _resource;
activity = _activity;
}
public static class ViewHolder {
TextView carYear;
TextView carMake;
TextView carModel;
TextView carColor;
TextView assetTag;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(resource, null);
holder=new ViewHolder();
holder.carYear = (TextView)vi.findViewById(R.id.carYear);
holder.carMake = (TextView)vi.findViewById(R.id.carMake);
holder.carModel = (TextView)vi.findViewById(R.id.carModel);
holder.carColor = (TextView)vi.findViewById(R.id.carColor);
holder.assetTag = (TextView)vi.findViewById(R.id.assetTag);
vi.setTag(holder);
} else {
holder=(ViewHolder)vi.getTag();
}
DataItem item = getItem(position);
holder.carYear.setText(item.getCarYear());
holder.carMake.setText(item.getCarMake());
holder.carModel.setText(item.getCarModel());
holder.carColor.setText(item.getCarColor());
holder.assetTag.setText(item.getAssetTag());
holder.carYear.setTag(position);
holder.assetTag.setTag(position);
final OnClickListener makeListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.makeInfo(pos);
((Main)activity).makeInfo(pos);
}
};
holder.carMake.setOnClickListener(makeListener);
final OnClickListener modelListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.modelInfo(pos);
((Main)activity).modelInfo(pos);
}
};
holder.carModel.setOnClickListener(modelListener);
final OnClickListener assetListener = new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout)v.getParent();
TextView tv = (TextView)ll.getChildAt(0);
Integer pos = (Integer) tv.getTag();
//main.assetInfo(pos);
((Main)activity).assetInfo(pos);
}
};
holder.assetTag.setOnClickListener(assetListener);
return vi;
}
hope it works :)

Categories

Resources