How to display calendar view in Android? - android

In my application I need to display calendar and some events on it, like on image below.
I've read this topic, but libs described there doesn't fit my needs. I've also found this lib: Extended Calendar View, but it works only on devices with api level 14 or higher while I need to support api level 10.
Maybe someone know some library for solving this problem? Any help will be highly appreciated.

i referred this link to create something like that link
/**
* 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 findNumberOfEventsPerMonth(int year, int month)
{
HashMap map = new HashMap<String, Integer>();
// DateFormat dateFormatter2 = new DateFormat();
//
// String day = dateFormatter2.format("dd", dateCreated).toString();
//
// if (map.containsKey(day))
// {
// Integer val = (Integer) map.get(day) + 1;
// map.put(day, val);
// }
// else
// {
// map.put(day, 1);
// }
return map;
}
In the above code create Hashmap which contains date. and replace if condition with this(Make changes according to ur needs)
if ((mEventsPerMonthMap != null) && (!mEventsPerMonthMap.isEmpty())) {
Set<String> keys = mEventsPerMonthMap.keySet();
for (String key : keys) {
if (key.equals(theday + "/" + monthInNo+ "/" + theyear)
&& mEventsPerMonthMap.containsKey((String.format("%02d", Integer.parseInt(theday)))
+ "/"+ monthInNo+ "/" + theyear)) {
datewiseEventmap.put(theday + "/" + monthInNo+"/" + theyear,
(ArrayList<Appointment>)
mEventsPerMonthMap.get((String.format("%02d",Integer.parseInt(theday)))+ "/" + monthInNo+ "/" + theyear));}}
Changing each grid cell
if (datewiseEventmap != null && datewiseEventmap.size() > 0) {
mNumEvents = (ArrayList<Appointment>) datewiseEventmap
.get(theday + "/" + monthInNo+ "/" + theyear);
eventName.setText(sbf);
eventName.setBackgroundResource(R.drawable.appointment_name_bg);
//gridcell.setBackgroundResource(R.drawable.calender_details_description);
eventCount.setVisibility(View.VISIBLE);
//eventCount.setBackgroundResource(R.drawable.calender_details_description);
if (mNumEvents.size() > 1) {
eventCount.setVisibility(View.VISIBLE);
eventCount.setText("+ " + String.valueOf(mNumEvents.size()));
}

Related

I have 4 textviews which take their values from spinner. If TextView 3 and 4 are blank then I need to copy values from position 1 & 2

I have 4 textviews which take their values from dropdown list (spinner) selected at previous screen.
There can be either 2 or 4 numbers/letters as result of this selection.
The first position will always be a number and the second position will always be a letter. The third position can be a number or blank and the fourth position can be a letter or blank.
If position 3 and position 4 are blank then I need to make them equal to positions 1 & 2 respectively.
String myGrade = intent.getStringExtra("parameter_name_grade");
// above takes value of 'myGrade' from spinner selection at previous screen
String mDisplayGradeNumberEff = (" " + myGrade.charAt(0));
TextView displayGradeNumberEff = (TextView) findViewById(R.id.gradeNumberEffTV);
displayGradeNumberEff.setText(mDisplayGradeNumberEff);
String mDisplayGradeLetterEff = (" " + myGrade.charAt(1));
TextView displayGradeLetterEff = (TextView) findViewById(R.id.gradeLetterEffTV);
displayGradeLetterEff.setText(mDisplayGradeLetterEff);
// above works correctly
// from here down only works when a character is present in both positions
// if positions 3(2) and 4(3) are empty app stops running.
String mDisplayGradeNumberDia = (" " + myGrade.charAt(2));
if (mDisplayGradeNumberDia.isEmpty()) {
mDisplayGradeNumberDia = mDisplayGradeNumberEff;
}
TextView displayGradeNumberDia = (TextView) findViewById(R.id.gradeNumberDiaTV);
displayGradeNumberDia.setText(mDisplayGradeNumberDia);
String mDisplayGradeLetterDia = (" " + myGrade.charAt(3));
if (mDisplayGradeLetterDia.isEmpty()) {
mDisplayGradeLetterDia = mDisplayGradeLetterEff;
}
TextView displayGradeLetterDia = (TextView) findViewById(R.id.gradeLetterDiaTV);
displayGradeLetterDia.setText(mDisplayGradeLetterDia);
}
I Guess you have a array out of bounds exception, please provide Logcat....
Check if "myGrade" has 3/4 Characters, if it does not you can't read them with charAt(3)...
You can check the length of the String with "myGrade.length()"
When I asked this question I was fairly new to the site and didn't understand that I should post back the solution for future reference. Solution below worked so thanks to rocket for your help and sorry for the delay!
int myGradeLength = mGrade.length();
if (myGradeLength != 4) {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(0));
mDisplayGradeLetterDia = ("" + mGrade.charAt(1));
} else {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(2));
mDisplayGradeLetterDia = ("" + mGrade.charAt(3));
}

Dynamic Adding item to list with different list and different adapter

how can I add item to list adapter, but every time I iterate n, it will add to a different list and different adapter, thanks!
//my first code
int n = 1;
while (n != 16) {
Day(n, Fullname);
n +=1 ;
}
//the other one that will add to the list and adapter
private void Day(int n,String Fullname){
String Date = "0" + n + "-" + Month + "-" + Year;
Cursor c = db.GetSpecific(Fullname,Date);
String allowancecount = "";
int intallowancecount = 0;
double totalCom = 0;
while(c.moveToNext()){
String serviceprice = c.getString(4);
String serviceperformedbynumber = c.getString(10);
allowancecount = c.getString(12);
intallowancecount = intallowancecount + Integer.parseInt(allowancecount.trim());
double income = Integer.parseInt(serviceprice.trim())/
Integer.parseInt(serviceperformedbynumber.trim());
totalCom = totalCom + income ;
//here what to do?
String add ="List" + n + ".add(String.valueOf(" + income + "));";
do add;//???????
}
//here what to do?
String Dynamic = "Com" + n + ".setText(String.valueOf(" + totalCom + "))";
do Dynamic ;//?????????
String Dynamicadapter = "Lv" + n + ".setAdapter(adapter" + n + ")";
do Dynamicadapter ;//????????
}
i'm just thinking if this was possible, but if not, i'll do it on the other way i know,open for any suggestions, thanks again.
It isn't possible in Java to assign variable using a variable name. However, there are things that you can use for these types of situations which allow you to almost do this, but everything is created correctly at runtime without the need for dynamic behaviour. For example, you can think about this in terms of using an associative array.
Taken from Wikipedia -https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(mapping)#Java
In Java associative arrays are implemented as "maps"; they are part of
the Java collections framework. Since J2SE 5.0 and the introduction of
generics into Java, collections can have a type specified; for
example, an associative array mapping strings to strings might be
specified
So in light of this, you could use a Map and restructure your code to do the following:
Create your adapter object
Set it's properties (such as setAdapter())
Add it to the map by using i (or whatever you want to use as a key for this)
Access it later on from the map using the key/dynamic 'variable name'
Map<Integer, ArrayAdapter<String>> map = new HashMap<Integer, ArrayAdapter<String>>();
for(int i = 0; i < 10; i++)
{
map.put(i, yourAdapter);
}

FaceRecognition with javacv android

I'm following javacv Face Detection/Recognition code, there is confusion regarding face recognition.. What I'm doing is (Sorry if it sounds stupid but I'm stuck)
1) Detect Face crop it and save it to sdcard and place path in learn.txt file (Learning part)
2) Detect Face crop it and find it in existing faces whether it exists or not, but it always return nearest position even if the face doesn't exist in sample faces..
what I'm doing wrong?
// Method, I'm using to recognize face
public Integer recognizeFace(Bitmap face, Context context) {
Log.i(TAG, "===========================================");
Log.i(TAG, "recognizeFace (single face)");
float[] projectedTestFace;
float confidence = 0.0f;
int nearest = -1; // closest match -- -1 for nothing.
int iNearest;
if (trainPersonNumMat == null) {
return null;
}
Log.i(TAG, "NUMBER OF EIGENS: " + nEigens);
// project the test images onto the PCA subspace
projectedTestFace = new float[nEigens];
// Start timing recognition
long startTime = System.nanoTime();
testFaceImg = bmpToIpl(face);
// saveBmp(face, "blah");
// convert Bitmap it IplImage
//testFaceImg = IplImage.create(face.getWidth(), face.getHeight(),
// IPL_DEPTH_8U, 4);
//face.copyPixelsToBuffer(testFaceImg.getByteBuffer());
// project the test image onto the PCA subspace
cvEigenDecomposite(testFaceImg, // obj
nEigens, // nEigObjs
new PointerPointer(eigenVectArr), // eigInput (Pointer)
0, // ioFlags
null, // userData
pAvgTrainImg, // avg
projectedTestFace); // coeffs
// LOGGER.info("projectedTestFace\n" +
// floatArrayToString(projectedTestFace));
Log.i(TAG, "projectedTestFace\n" + floatArrayToString(projectedTestFace));
final FloatPointer pConfidence = new FloatPointer(confidence);
iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
confidence = pConfidence.get();
// truth = personNumTruthMat.data_i().get(i);
nearest = trainPersonNumMat.data_i().get(iNearest); // result
// get endtime and calculate time recognition process takes
long endTime = System.nanoTime();
long duration = endTime - startTime;
double seconds = (double) duration / 1000000000.0;
Log.i(TAG, "recognition took: " + String.valueOf(seconds));
Log.i(TAG, "nearest = " + nearest + ". Confidence = " + confidence);
Toast.makeText(context, "Nearest: "+nearest+" Confidence: "+confidence, Toast.LENGTH_LONG).show();
//Save the IplImage so we can see what it looks like
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "/sdcard/saved_images/" + nearest + " " + String.valueOf(seconds) + " " + String.valueOf(confidence) + " " + n + ".jpg";
Log.i(TAG, "Saving image as: " + fname);
cvSaveImage(fname, testFaceImg);
return nearest;
} // end of recognizeFace
EDIT The confidence is always negative!
Thanks in advance

How to create programatic bookmark into browser using Android sdk?

I've seen apps doing this, but I don't have a clue where to start. Any hints? Some code snippets will be appreciated.
/**
* Add a bookmark to the database.
*
* #param context
* Context of the calling Activity. This is used to make Toast confirming that the bookmark has been added. If the caller provides null, the Toast will not be shown.
* #param cr
* The ContentResolver being used to add the bookmark to the db.
* #param url
* URL of the website to be bookmarked.
* #param name
* Provided name for the bookmark.
* #param thumbnail
* A thumbnail for the bookmark.
* #param retainIcon
* Whether to retain the page's icon in the icon database. This will usually be <code>true</code> except when bookmarks are added by a settings restore agent.
*/
static void addBookmark(Context context, ContentResolver cr, String url, String name, Bitmap thumbnail, boolean retainIcon) {
final String WHERE_CLAUSE = "url = ? OR url = ? OR url = ? OR url = ?";
final String WHERE_CLAUSE_SECURE = "url = ? OR url = ?";
String[] SELECTION_ARGS;
// Want to append to the beginning of the list
long creationTime = new Date().getTime();
// First we check to see if the user has already visited this
// site. They may have bookmarked it in a different way from
// how it's stored in the database, so allow different combos
// to map to the same url.
boolean secure = false;
String compareString = url;
if (compareString.startsWith("http://")) {
compareString = compareString.substring(7);
} else if (compareString.startsWith("https://")) {
compareString = compareString.substring(8);
secure = true;
}
if (compareString.startsWith("www.")) {
compareString = compareString.substring(4);
}
if (secure) {
SELECTION_ARGS = new String[2];
SELECTION_ARGS[0] = "https://" + compareString;
SELECTION_ARGS[1] = "https://www." + compareString;
} else {
SELECTION_ARGS = new String[4];
SELECTION_ARGS[0] = compareString;
SELECTION_ARGS[1] = "www." + compareString;
SELECTION_ARGS[2] = "http://" + compareString;
SELECTION_ARGS[3] = "http://" + SELECTION_ARGS[1];
}
Cursor cursor = cr.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, secure ? WHERE_CLAUSE_SECURE : WHERE_CLAUSE, SELECTION_ARGS, null);
ContentValues map = new ContentValues();
if (cursor.moveToFirst() && cursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) == 0) {
// This means we have been to this site but not bookmarked
// it, so convert the history item to a bookmark
map.put(Browser.BookmarkColumns.CREATED, creationTime);
map.put(Browser.BookmarkColumns.TITLE, name);
map.put(Browser.BookmarkColumns.BOOKMARK, 1);
// map.put(Browser.BookmarkColumns.THUMBNAIL, bitmapToBytes(thumbnail));
cr.update(Browser.BOOKMARKS_URI, map, "_id = " + cursor.getInt(0), null);
} else {
int count = cursor.getCount();
boolean matchedTitle = false;
for (int i = 0; i < count; i++) {
// One or more bookmarks already exist for this site.
// Check the names of each
cursor.moveToPosition(i);
if (cursor.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX).equals(name)) {
// The old bookmark has the same name.
// Update its creation time.
map.put(Browser.BookmarkColumns.CREATED, creationTime);
cr.update(Browser.BOOKMARKS_URI, map, "_id = " + cursor.getInt(0), null);
matchedTitle = true;
break;
}
}
if (!matchedTitle) {
// Adding a bookmark for a site the user has visited,
// or a new bookmark (with a different name) for a site
// the user has visited
map.put(Browser.BookmarkColumns.TITLE, name);
map.put(Browser.BookmarkColumns.URL, url);
map.put(Browser.BookmarkColumns.CREATED, creationTime);
map.put(Browser.BookmarkColumns.BOOKMARK, 1);
map.put(Browser.BookmarkColumns.DATE, 0);
// map.put(Browser.BookmarkColumns.THUMBNAIL, bitmapToBytes(thumbnail));
int visits = 0;
if (count > 0) {
// The user has already bookmarked, and possibly
// visited this site. However, they are creating
// a new bookmark with the same url but a different
// name. The new bookmark should have the same
// number of visits as the already created bookmark.
visits = cursor.getInt(Browser.HISTORY_PROJECTION_VISITS_INDEX);
}
// Bookmark starts with 3 extra visits so that it will
// bubble up in the most visited and goto search box
map.put(Browser.BookmarkColumns.VISITS, visits + 3);
cr.insert(Browser.BOOKMARKS_URI, map);
}
}
if (retainIcon) {
WebIconDatabase.getInstance().retainIconForPageUrl(url);
}
cursor.close();
}
You can see the OS code here

Android Phrase o-matic

I'd like to port this little program to Android, thing is that im level basic -1 at android, what the program does is that it randomly creates a phrase taken from strings in an array. I know how to make a button to show me an xml from the layout resources but thatjust works with textviews that do not change, Could you please tell me which steps to follow in order to display a randomly generated string taken from the array of strings?
heres the code(head first java):
public class PhraseOMatic
{
public static void main (String[] args)
{
String[] wordListOne = {"24/7", "multi-tier", "30,OOO foot", "B-to-B" , "win-win" , "frontend", "web- based" , "pervasive", "smart", "sixsigma", "critical-path", "dynamic"};
String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outaide-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};
String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "session"};
// find out how many words are in each list
int oneLenqth = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// generate .... random numbers
int randl = (int) (Math.random() * oneLenqth);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
//now build a phrase
String phrase = wordListOne[randl] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
// print out the phrase
System.out.println("What we need is a " + phrase);
}
}

Categories

Resources