I have two activities: MainActivity6 (parent) and tool1mode1 (Child)
from the parent activity:
if (tool == 1) {
switch (mode) {
case 1:
intentTool1mode1.putExtra("Type", typekey);
intentTool1mode1.putExtra("Key", Key);
intentTool1mode1.putExtra("Tool", "Tool 1");
intentTool1mode1.putExtra("Mode", "Home");
Toast.makeText(MainActivity6.this, "Type: " + typekey + "\n" + "Key: " + Key + "\n" + "Tool: " + "1" + "\n" + "Mode: " + "Home" + "\n", Toast.LENGTH_LONG).show();
if(key_60.isChecked())
{
String number = "480000";
long val = Long.parseLong(number);
intentTool1mode1.putExtra("Time",val);
startActivityForResult(intentTool1mode1, 1);
}
if(key_90.isChecked())
{
String number = "720000";
long val = Long.parseLong(number);
intentTool1mode1.putExtra("Time",val);
startActivityForResult(intentTool1mode1, 1);
}
break;
And this is the part from the child Activity:
private long START_TIME_IN_MILLIS;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
private CountDownTimer mCountDownTimer;
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
START_TIME_IN_MILLIS = intent.getLongExtra("Time", 0);
newbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startTimer();
}
});
The code below represents both function I used to start and update the counter in the child Activity:
private void startTimer()
{
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
progress++;
pb.setProgress((int)progress*100/(480000/1000));
}
#Override
public void onFinish()
{
progress++;
pb.setProgress(100);
//Vibration
if (Build.VERSION.SDK_INT >= 26)
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(com.example.ticwatch_1.tool1mode1.this,"Done",Toast.LENGTH_SHORT).show();
}
else
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(new long[]{150}, new int[]{VibrationEffect.EFFECT_CLICK},-1));
}
}
}.start();
}
private void updateCountDownText()
{
//time in minutes and seconds
int minutes = (int)(mTimeLeftInMillis/1000)/60;
int seconds = (int)(mTimeLeftInMillis/1000)%60;
//formating the above to appear as String
String timeLeftFormatted = String.format("%02d:%02d",minutes,seconds);
timer.setText(timeLeftFormatted);
}
What I want is to fetch the value from the Parent Activity and to update the value of START_TIME_IN_MILLIS with the value I fetched. So I I want the timer to run for 8 min I'll fetch 480000. What I get instead is the counter is 0 when I start it as in it already finished and didn't start from 8 min or any other value. I don't know what to do and I'm exhausted.
I making a timer in my android app. I have a scenario where I dont need to stop the timer even if the app is closed. If the timer is running and user closes the app and reopen it after sometime. He should see the latest time on the timer. But currently I am not able to show the latest time. I am only able to show the time when the user killed the app. I am storing the time of the timer and when the user open the app I am putting the stored time back to the timer. But I want to show the latest time. Here what I have done till now. I am using chronometer widget.
MainActivity.class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
Chronometer tvTextView;
Button btnStart, btnStop;
private int state = 0; //0 means stop state,1 means play, 2 means pause
SharedPreferences sharedPreferences;
private boolean running = false;
private long pauseOffSet = -1;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.textview);
progressBar = findViewById(R.id.puzzleProgressBar);
btnStart = findViewById(R.id.button1);
btnStop = findViewById(R.id.button2);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
state = sharedPreferences.getInt("state", 0);
tvTextView.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long time = SystemClock.elapsedRealtime() - chronometer.getBase();
pauseOffSet=time;
Log.e(TAG,"pauseOffSet "+pauseOffSet);
if (time >= 79200000) {
tvTextView.setBase(SystemClock.elapsedRealtime());
tvTextView.stop();
running = false;
progressBar.setProgress(0);
} else {
chronometer.setText(setFormat(time));
int convertTime = (int) time;
progressBar.setProgress(convertTime);
}
}
});
if (state == 1) { // its in play mode
running = true;
tvTextView.setBase(SystemClock.elapsedRealtime() - sharedPreferences.getLong("milli", 0));
tvTextView.start();
} else if (state == 2) { //its in pause mode
running = false;
pauseOffSet = sharedPreferences.getLong("milli", -1);
long time = SystemClock.elapsedRealtime() - pauseOffSet;
tvTextView.setBase(time);
int convertTime = (int) pauseOffSet;
progressBar.setProgress(convertTime);
} else {
running = false;
tvTextView.setBase(SystemClock.elapsedRealtime());
}
}
public void onClick(View v) {
if (btnStart == v) {
if (!running) {
if (pauseOffSet != -1) {
pauseOffSet = sharedPreferences.getLong("milli", -1);
}
tvTextView.setBase(SystemClock.elapsedRealtime() - pauseOffSet);
tvTextView.start();
state = 1;
pauseOffSet = 0;
running = true;
}
} else if (btnStop == v) {
if (running) {
tvTextView.stop();
pauseOffSet = SystemClock.elapsedRealtime() - tvTextView.getBase();
state = 2;
running = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putLong("milli", pauseOffSet).commit();
sharedPreferences.edit().putInt("state", state).commit();
}
#Override
protected void onDestroy() {
Log.e(TAG, "onDestroy called, state: " + state);
super.onDestroy();
}
String setFormat(long time) {
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
return hh + ":" + mm + ":" + ss;
}
}
I have a cart that can insert only one product at a time, but now i have to insert more than one product at a time. I use check boxes to select the items.
What do I need to change to allow inserting more than one product into the cart?
This is my Adapter Class :
public class AdapterPrice extends BaseAdapter {
ArrayList<ModelPrice> listPrice;
private Context context;
int selectedPosition = 0;
public AdapterPrice(Context context, ArrayList<ModelPrice> listPrice) {
this.context = context;
this.listPrice = listPrice;
}
#Override
public int getCount() {
return listPrice.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
final AdapterPrice.ViewHolder holder;
if (view == null) {
holder = new AdapterPrice.ViewHolder();
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_packing, null);
holder.txtOffer = view.findViewById(R.id.txtOffer);
holder.txtPrice = view.findViewById(R.id.txtPrice);
holder.txtQty = view.findViewById(R.id.txtQty);
//holder.radioWeight = view.findViewById(R.id.radioWeight);
holder.checkBox = view.findViewById(R.id.checkboxWeight);
holder.icMinus = view.findViewById(R.id.icMinus);
holder.icPlus = view.findViewById(R.id.icPlus);
view.setTag(holder);
} else {
holder = (AdapterPrice.ViewHolder) view.getTag();
}
//holder.radioWeight.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
holder.checkBox.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
double packMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
double offerMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp();
holder.txtPrice.setText("Rs." + UtilMethods.decimalFormater(packMrpd));
holder.txtOffer.setText("Rs." + UtilMethods.decimalFormater(offerMrpd));
holder.txtQty.setText(listPrice.get(position).getQty() + "");
/*holder.radioWeight.setChecked(position == selectedPosition);
holder.radioWeight.setTag(position);*/
holder.checkBox.setChecked(position == selectedPosition);
Log.d("POSITION CB>>>>>>",position+"");
//holder.checkBox.setTag(position);
if (holder.checkBox.isChecked()) {
String forString = "for " + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getWeight()) + "" + listPrice.get(selectedPosition).getUnit();
SpannableString forStr = new SpannableString(forString);
forStr.setSpan(new UnderlineSpan(), 0, forString.length(), 0);
//txtFor.setText(forStr);
//txtOferPrice.setText("Rs." + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getSellMrp()) + "");
double saveMrp = ((double) listPrice.get(position).getQty() * listPrice.get(position).getMrp()) - ((double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp());
txtSAve.setText("Rs." + (UtilMethods.decimalFormater(saveMrp)) + "");
if (saveMrp <= 0) {
offerLayout.setVisibility(View.GONE);
}
mQty = listPrice.get(position).getQty();
mMrp = listPrice.get(position).getMrp();
mSellMrp = listPrice.get(position).getSellMrp();
mweight = listPrice.get(position).getWeight();
mUnit = listPrice.get(position).getUnit();
seletUnit = (1 * selectedPosition);
}
/*holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
notifyDataSetChanged();
}
});*/
holder.icMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
if (cQty > 1) {
cQty = listPrice.get(position).getQty() - 1;
listPrice.get(position).setQty(cQty);
// double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
//holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText("Rs."+saveMrp + "");
}*/
notifyDataSetChanged();
}
}
});
holder.icPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
cQty = listPrice.get(position).getQty() + 1;
listPrice.get(position).setQty(cQty);
//double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
// holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText(saveMrp + "");
}*/
notifyDataSetChanged();
}
});
return view;
}
public class ViewHolder {
private TextView txtPrice, txtQty, txtOffer;
private RadioButton radioWeight;
CheckBox checkBox;
private ImageView icPlus, icMinus;
}
}
this is where i insert item into cart through SQLIte :
private void addToCArt() {
ModelCart mcart = new ModelCart();
mcart.setProductName(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getProductName());
mcart.setPid(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
mcart.setImageUrl(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getImageTag1());
List<String> attrId = new ArrayList<>();
for (ModelPrice mmp : Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()) {
attrId.add(mmp.getWid() + "," + mmp.getWeight() + "," + mmp.getUnit());
}
String aData = TextUtils.join("-", attrId);
mcart.setQty(mQty);
mcart.setWeight(mweight);
mcart.setUnit(mUnit);
mcart.setMrp(mMrp);
mcart.setSellMrp(mSellMrp);
mcart.setAttributeData(aData);
mcart.setSelectUnit(seletUnit);
mcart.setSelecAttrId((Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()).get(seletUnit).getWid());
db.insetCArt(mcart);
/*int isQty = db.isProduct(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
if (isQty != -1 && isQty != 0) {
int tQ = mQty + isQty;
mcart.setQty(tQ);
db.updateCart(mcart);
} else {
db.insetCArt(mcart);
}*/
/*CartFragment orderFrg = new CartFragment();
Bundle args = new Bundle();
orderFrg.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.frmae, orderFrg).addToBackStack(null).commit();
*/
}
The music can play normally but I can't show time of music on my music Player.How can I do?
In main class
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
}
}
private void UpdateseekChange(View v){
if(mMedia.isPlaying()){
SeekBar sb = (SeekBar)v;
mMedia.seekTo(sb.getProgress());
}
This one should work:
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
txtView.post(mUpdateTime);
}
}
private Runnable mUpdateTime = new Runnable() {
public void run() {
int currentDuration;
if (mMedia.isPlaying()) {
currentDuration = mp.getCurrentPosition();
updatePlayer(currentDuration);
txtView.postDelayed(this, 1000);
}else {
txtView.removeCallbacks(this);
}
}
};
private void updatePlayer(int currentDuration){
txtView.setText("" + milliSecondsToTimer((long) currentDuration));
}
/**
* Function to convert milliseconds time to Timer Format
* Hours:Minutes:Seconds
* */
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
You need of course to remove runnable when the track is finished.
Try this code coders :)
//Get duration
long totalDuration = mediaPlayerOBJ.getDuration();
//Get current time
long currentDuration = mediaPlayerOBJ.getCurrentPosition();
textViewCurrentTime.setText(milliSecondsToTimer(currentDuration));
textViewDuration.setText(milliSecondsToTimer(totalDuration));
//Here is function to convert milliseconds to timer
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
It's the all code page of the application media player.How can I do?
In main class
private MediaPlayer mMedia;
private Handler handler = new Handler();
private SeekBar seekBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mMedia != null){
mMedia.release();
}
final TextView txtView = (TextView)findViewById(R.id.textView1);
txtView.setText("Source : music.mp3");
/* Resource in R.
* mMedia = MediaPlayer.create(this, R.raw.music);
* mMedia.start();
*/
/*
* from DataSource
* mMedia = new MediaPlayer();
* mMedia.setDataSource("http://www.thaicreate.com/music/mymusic.mp3");
* mMedia.start();
*
*/
mMedia = MediaPlayer.create(this, R.raw.music);
seekBar = (SeekBar)findViewById(R.id.seekBar1);
seekBar.setMax(mMedia.getDuration());
seekBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
UpdateseekChange(v);
return false;
}
});
final Button btn1 = (Button) findViewById(R.id.button1); // Start
// Start
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
}
}
});
}
private void UpdateseekChange(View v){
if(mMedia.isPlaying()){
SeekBar sb = (SeekBar)v;
mMedia.seekTo(sb.getProgress());
}
}
public void startPlayProgressUpdater() {
seekBar.setProgress(mMedia.getCurrentPosition());
if (mMedia.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mMedia != null && fromUser){
mMedia.seekTo(progress * 1000);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mMedia != null){
mMedia.release();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Ok, if you want to show it with String, use this method.
It gets remaining length(duration) and return the String:
public String convertTime(long value) {
String audioTime;
int dur = (int) value;
int hrs = (dur / 3600000);
int mns = (dur / 60000) % 60000;
int scs = dur % 60000 / 1000;
if (hrs > 0) {
audioTime = String.format("%02d:%02d:%02d", hrs, mns, scs);
} else {
audioTime = String.format("%02d:%02d", mns, scs);
}
return audioTime;
}
I follow tutorials 1 and 2 this tutorial in order to get horizontal listview view using custom HorizontalListView class. Below is my code. Everything works fine, but the problem is that when the application starts, it shows dates from 1, not from current date.
What can I do?
This is my snapshot
public class MyCalendarActivity extends Activity implements
OnClickListener {
private static final String tag = "MyCalendarActivity";
private TextView currentMonth;
private Button selectedDayMonthYearButton;
private ImageView prevMonth;
private ImageView nextMonth;
private HorizontalListView calendarView;
private GridCellAdapter adapter;
private Calendar _calendar;
#SuppressLint("NewApi")
private int month, year;
#SuppressWarnings("unused")
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_calendar_view);
_calendar = Calendar.getInstance(Locale.getDefault());
month = _calendar.get(Calendar.MONTH) + 1;
year = _calendar.get(Calendar.YEAR);
Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
+ year);
selectedDayMonthYearButton = (Button) this
.findViewById(R.id.selectedDayMonthYear);
selectedDayMonthYearButton.setText("Selected: ");
prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
prevMonth.setOnClickListener(this);
currentMonth = (TextView) this.findViewById(R.id.currentMonth);
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
nextMonth.setOnClickListener(this);
// HorizontalListView listview = (HorizontalListView)
findViewById(R.id.listview);
calendarView = (HorizontalListView) this.findViewById(R.id.calendar);
// Initialised
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
/**
*
* #param month
* #param year
*/
private void setGridCellAdapterToDate(int month, int year) {
adapter = new GridCellAdapter(getApplicationContext(),
R.id.calendar_day_gridcell, month, year);
_calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
}
#Override
public void onClick(View v) {
if (v == prevMonth) {
if (month <= 1) {
month = 12;
year--;
} else {
month--;
}
Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
if (v == nextMonth) {
if (month > 11) {
month = 1;
year++;
} else {
month++;
}
Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "
+ month + " Year: " + year);
setGridCellAdapterToDate(month, year);
}
}
#Override
public void onDestroy() {
Log.d(tag, "Destroying View ...");
super.onDestroy();
}
// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener {
private static final String tag = "GridCellAdapter";
private final Context _context;
private final List<String> list;
private static final int DAY_OFFSET = 1;
private final String[] weekdays = new String[] { "Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat" };
private final String[] months = { "January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December" };
private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
private int daysInMonth;
private int currentDayOfMonth;
private int currentWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
"dd-MMM-yyyy");
// Days in Current Month
public GridCellAdapter(Context context, int textViewResourceId,
int month, int year) {
super();
this._context = context;
this.list = new ArrayList<String>();
Log.d(tag, "==> Passed in Date FOR Month: " + month + " "
+ "Year: " + year);
Calendar calendar = Calendar.getInstance();
setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());
// Print Month
printMonth(month, year);
// Find Number of Events
eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
}
private String getMonthAsString(int i) {
return months[i];
}
private String getWeekDayAsString(int i) {
return weekdays[i];
}
private int getNumberOfDaysOfMonth(int i) {
return daysOfMonth[i];
}
public String getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
/**
* Prints Month
*
* #param mm
* #param yy
*/
private void printMonth(int mm, int yy) {
Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
int trailingSpaces = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = mm - 1;
String currentMonthName = getMonthAsString(currentMonth);
daysInMonth = getNumberOfDaysOfMonth(currentMonth);
Log.d(tag, "Current Month: " + " " + currentMonthName + " having "
+ daysInMonth + " days.");
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());
if (currentMonth == 11) {
prevMonth = currentMonth - 1;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 0;
prevYear = yy;
nextYear = yy + 1;
Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else if (currentMonth == 0) {
prevMonth = 11;
prevYear = yy - 1;
nextYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
nextMonth = 1;
Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
} else {
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = yy;
prevYear = yy;
daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"
+ prevMonth + " NextMonth: " + nextMonth
+ " NextYear: " + nextYear);
}
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
trailingSpaces = currentWeekDay;
Log.d(tag, "Week Day:" + currentWeekDay + " is "
+ getWeekDayAsString(currentWeekDay));
Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);
if (cal.isLeapYear(cal.get(Calendar.YEAR)))
if (mm == 2)
++daysInMonth;
else if (mm == 3)
++daysInPrevMonth;
// Trailing Month days
for (int i = 0; i < trailingSpaces; i++) {
Log.d(tag,
"PREV MONTH:= "
+ prevMonth
+ " => "
+
getMonthAsString(prevMonth)
+ " "
+
String.valueOf((daysInPrevMonth
-
trailingSpaces + DAY_OFFSET)
+ i));
list.add(String
.valueOf((daysInPrevMonth - trailingSpaces
+ DAY_OFFSET)
+ i)
+ "-GREY"
+ "-"
+ getMonthAsString(prevMonth)
+ "-"
+ prevYear);
}
// Current Month Days
for (int i = 1; i <= daysInMonth; i++) {
Log.d(currentMonthName, String.valueOf(i) + " "
+ getMonthAsString(currentMonth) + " " +
yy);
if (i == getCurrentDayOfMonth()) {
list.add(String.valueOf(i) + "-BLUE" + "-"
+ getMonthAsString(currentMonth) +
"-" + yy);
} else {
list.add(String.valueOf(i) + "-WHITE" + "-"
+ getMonthAsString(currentMonth) +
"-" + yy);
}
}
// Leading Month days
for (int i = 0; i < list.size() % 7; i++) {
Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
list.add(String.valueOf(i + 1) + "-GREY" + "-"
+ getMonthAsString(nextMonth) + "-" +
nextYear);
}
}
/**
* NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
* ALL entries from a SQLite database for that month. Iterate over the
* List of All entries, and get the dateCreated, which is converted into
* day.
*
* #param year
* #param month
* #return
*/
private HashMap<String, Integer> findNumberOfEventsPerMonth(int year,
int month) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.screen_gridcell, parent,
false);
}
// Get a reference to the Day gridcell
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
gridcell.setOnClickListener(this);
// ACCOUNT FOR SPACING
Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap !=
null)) {
if (eventsPerMonthMap.containsKey(theday)) {
num_events_per_day = (TextView) row
.findViewById(R.id.num_events_per_day);
Integer numEvents = (Integer)
eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
// Set the Day GridCell
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"
+ theyear);
if (day_color[1].equals("GREY")) {
gridcell.setTextColor(getResources()
.getColor(R.color.lightgray));
}
if (day_color[1].equals("WHITE")) {
gridcell.setTextColor(getResources().getColor(
R.color.lightgray02));
}
if (day_color[1].equals("BLUE")) {
gridcell.setTextColor(getResources().getColor(R.color.orrange));
}
return row;
}
#Override
public void onClick(View view) {
String date_month_year = (String) view.getTag();
selectedDayMonthYearButton.setText("Selected: " + date_month_year);
Log.e("Selected date", date_month_year);
try {
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
public int getCurrentDayOfMonth() {
return currentDayOfMonth;
}
private void setCurrentDayOfMonth(int currentDayOfMonth) {
this.currentDayOfMonth = currentDayOfMonth;
}
public void setCurrentWeekDay(int currentWeekDay) {
this.currentWeekDay = currentWeekDay;
}
public int getCurrentWeekDay() {
return currentWeekDay;
}
}
}
public class HorizontalListView extends AdapterView<ListAdapter> {
public boolean mAlwaysOverrideTouch = true;
protected ListAdapter mAdapter;
private int mLeftViewIndex = -1;
private int mRightViewIndex = 0;
protected int mCurrentX;
protected int mNextX;
private int mMaxX = Integer.MAX_VALUE;
private int mDisplayOffset = 0;
protected Scroller mScroller;
private GestureDetector mGesture;
private Queue<View> mRemovedViewQueue = new LinkedList<View>();
private OnItemSelectedListener mOnItemSelected;
private OnItemClickListener mOnItemClicked;
private OnItemLongClickListener mOnItemLongClicked;
private boolean mDataChanged = false;
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private synchronized void initView() {
mLeftViewIndex = -1;
mRightViewIndex = 0;
mDisplayOffset = 0;
mCurrentX = 0;
mNextX = 0;
mMaxX = Integer.MAX_VALUE;
mScroller = new Scroller(getContext());
mGesture = new GestureDetector(getContext(), mOnGesture);
}
#Override
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener
listener) {
mOnItemSelected = listener;
}
#Override
public void setOnItemClickListener(AdapterView.OnItemClickListener listener){
mOnItemClicked = listener;
}
#Override
public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener
listener) {
mOnItemLongClicked = listener;
}
private DataSetObserver mDataObserver = new DataSetObserver() {
#Override
public void onChanged() {
synchronized(HorizontalListView.this){
mDataChanged = true;
}
invalidate();
requestLayout();
}
#Override
public void onInvalidated() {
reset();
invalidate();
requestLayout();
}
};
#Override
public ListAdapter getAdapter() {
return mAdapter;
}
#Override
public View getSelectedView() {
//TODO: implement
return null;
}
#Override
public void setAdapter(ListAdapter adapter) {
if(mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataObserver);
}
mAdapter = adapter;
mAdapter.registerDataSetObserver(mDataObserver);
reset();
}
private synchronized void reset(){
initView();
removeAllViewsInLayout();
requestLayout();
}
#Override
public void setSelection(int position) {
//TODO: implement
}
private void addAndMeasureChild(final View child, int viewPos) {
LayoutParams params = child.getLayoutParams();
if(params == null) {
params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
}
addViewInLayout(child, viewPos, params, true);
child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(),
MeasureSpec.AT_MOST));
}
#Override
protected synchronized void onLayout(boolean changed, int left, int top, int
right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if(mAdapter == null){
return;
}
if(mDataChanged){
int oldCurrentX = mCurrentX;
initView();
removeAllViewsInLayout();
mNextX = oldCurrentX;
mDataChanged = false;
}
if(mScroller.computeScrollOffset()){
int scrollx = mScroller.getCurrX();
mNextX = scrollx;
}
if(mNextX <= 0){
mNextX = 0;
mScroller.forceFinished(true);
}
if(mNextX >= mMaxX) {
mNextX = mMaxX;
mScroller.forceFinished(true);
}
int dx = mCurrentX - mNextX;
removeNonVisibleItems(dx);
fillList(dx);
positionItems(dx);
mCurrentX = mNextX;
if(!mScroller.isFinished()){
post(new Runnable(){
#Override
public void run() {
requestLayout();
}
});
}
}
private void fillList(final int dx) {
int edge = 0;
View child = getChildAt(getChildCount()-1);
if(child != null) {
edge = child.getRight();
}
fillListRight(edge, dx);
edge = 0;
child = getChildAt(0);
if(child != null) {
edge = child.getLeft();
}
fillListLeft(edge, dx);
}
private void fillListRight(int rightEdge, final int dx) {
while(rightEdge + dx < getWidth() && mRightViewIndex <
mAdapter.getCount()) {
View child = mAdapter.getView(mRightViewIndex,
mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, -1);
rightEdge += child.getMeasuredWidth();
if(mRightViewIndex == mAdapter.getCount()-1) {
mMaxX = mCurrentX + rightEdge - getWidth();
}
if (mMaxX < 0) {
mMaxX = 0;
}
mRightViewIndex++;
}
}
private void fillListLeft(int leftEdge, final int dx) {
while(leftEdge + dx > 0 && mLeftViewIndex >= 0) {
View child = mAdapter.getView(mLeftViewIndex,
mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, 0);
leftEdge -= child.getMeasuredWidth();
mLeftViewIndex--;
mDisplayOffset -= child.getMeasuredWidth();
}
}
private void removeNonVisibleItems(final int dx) {
View child = getChildAt(0);
while(child != null && child.getRight() + dx <= 0) {
mDisplayOffset += child.getMeasuredWidth();
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mLeftViewIndex++;
child = getChildAt(0);
}
child = getChildAt(getChildCount()-1);
while(child != null && child.getLeft() + dx >= getWidth()) {
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mRightViewIndex--;
child = getChildAt(getChildCount()-1);
}
}
private void positionItems(final int dx) {
if(getChildCount() > 0){
mDisplayOffset += dx;
int left = mDisplayOffset;
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
int childWidth = child.getMeasuredWidth();
child.layout(left, 0, left + childWidth,
child.getMeasuredHeight());
left += childWidth + child.getPaddingRight();
}
}
}
public synchronized void scrollTo(int x) {
mScroller.startScroll(mNextX, 0, x - mNextX, 0);
requestLayout();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = super.dispatchTouchEvent(ev);
handled |= mGesture.onTouchEvent(ev);
return handled;
}
protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
synchronized(HorizontalListView.this){
mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);
}
requestLayout();
return true;
}
protected boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
return true;
}
private OnGestureListener mOnGesture = new
GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onDown(MotionEvent e) {
return HorizontalListView.this.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return HorizontalListView.this.onFling(e1, e2, velocityX,
velocityY);
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
synchronized(HorizontalListView.this){
mNextX += (int)distanceX;
}
requestLayout();
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if(mOnItemClicked != null){
mOnItemClicked.onItemClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i,
mAdapter.getItemId( mLeftViewIndex + 1 + i ));
}
if(mOnItemSelected != null){
mOnItemSelected.onItemSelected(HorizontalListView.this, child, mLeftViewIndex + 1 +
i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
}
break;
}
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if (mOnItemLongClicked != null) {
mOnItemLongClicked.onItemLongClick(HorizontalListView.this, child, mLeftViewIndex +
1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
}
break;
}
}
}
private boolean isEventWithinView(MotionEvent e, View child) {
Rect viewRect = new Rect();
int[] childPosition = new int[2];
child.getLocationOnScreen(childPosition);
int left = childPosition[0];
int right = left + child.getWidth();
int top = childPosition[1];
int bottom = top + child.getHeight();
viewRect.set(left, top, right, bottom);
return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
}
};
}