Category Archives: Android

[Android] Nice lib to create intuitive demo/instruction message on first app start up

https://github.com/Espiandev/ShowcaseView

Found from this thread on Stackoverflow
http://stackoverflow.com/questions/12013334/how-do-you-create-a-transparent-demo-screen-for-an-android-app

Advertisements

[Instagram] How to get more than 60 images from Instagram service

Hi,

Recently, I have created an app that uses instagram images ,.( I made this app for other guy, so i can not reveal it here ).
The problem is that , Instagram only returned first 60 images per returned pack. So if you have more than 60 images, and you want to get these older images, you must find out some way to deal with that. And here is what I did in my app.

It turned out  Instagram provided us a pagination mechanism to get each 60 images, The first request will return 60 newest images, then you then the oldest id of images returned from previous pack.
Just add token “max_id” with the token’s value is the oldest image id:
For example, this is how I create my JSONObject for request more images.
JSONObject feedJson = executeHttpGet("https://api.instagram.com/v1/users/"
+ userId
+ "/media/recent/"
+ "?access_token="
+ token
+ "&count=" + mediaCount
+ "&max_id=" + mOldestId);

The excuteHttpGet is my private method based on HttpClient and HttpResponse to send get read the response from server.

That’s it.


[ANDROID]HOW TO GET SYSTEM DATE/TIME FORMAT BY LOCALE ?

private java.text.DateFormat mDateFormat;
private java.text.DateFormat mTimeFormat;
//// init values

// onCreate() for e.g

mDateFormat = android.text.format.DateFormat.getDateFormat(this);
mTimeFormat = android.text.format.DateFormat.getDateFormat(this);

// use
dateTimeString = mDateFormat.format(objectX.getTime()) + ” ” + mTimeFormat.format(objectY.getTime());


[ANDROID] Set title of app to be centered

Use this:

((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);


Comment: This will help your app crash in ICS ( >= 4.0)


[ANDROID] FlingGesture Listener

Hi,

Today topic is about Fling Gesture in Android.

As you might notice that, some apps on Android like Music or Photo are implemented Fling gesture, so that if you fling you finger from left to right or from right to left, you will have your songs or images changed.

So, what was happened under the hook?

Let’s dive into these little snippet of code. (This is not my code, I just collect them from somewhere on the internet that I can not remember now, sorry for this, just I think you can try to Google them).

[CODE]

public class FlingGestureDetector extends SimpleOnGestureListener {
public static final int SWIPE_MIN_DISTANCE = 120;
public static final int SWIPE_MAX_OFF_PATH = 250;
public static final int SWIPE_THRESHOLD_VELOCITY = 200;
public onAction mOnL2RAction;
public onAction mOnR2LAction;

public FlingGestureDetector(Context context, View v){
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() – e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() – e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onR2LDoAction();
} else if (e2.getX() – e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onL2RDoAction();
}
} catch (Exception e) {
// nothing
}
return false;
}

public interface onAction{
void doAction();
}

private void onL2RDoAction(){
mOnL2RAction.doAction();
}

private void onR2LDoAction(){
mOnR2LAction.doAction();
}

}

[/CODE]

The main component here is the way to determine that the action of flinging has happened.
By defining the constants of minimum distance and minimum velocity that calculated from 2 points: touching point and releasing point

The demo that uses this snippet of code can be found here
http://www.mediafire.com/?secs6gsy73aw9zo

One SMALL notice when applying the gesture listener on some kinds of view is  that view must be set to be clickable ( clickable = true)


[ANDROID] Prevent Activity from Auto-Rotating

hi,

Today topic is about how to prevent the activity ( not the whole system ) from rotating.

it’s quite simple, using the following lines of code:

private void adjustRotating(boolean isOff) {
if (isOff) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}

Want to turn of rotating, call adjustRotating(true) and to turn it on back to normal, call adjustRotating(false)

No other settings in Manifest or anywhere else.

This is some sample code, you can take it from Mediafire http://www.mediafire.com/?pnx9tqmje8pkf6q

——
References :

http://stackoverflow.com/questions/9941038/it-is-possible-to-lock-the-screen-orientation-of-the-phone-only-when-you-want
——
Just one small problem when you try this snippset of code is that when you disable rotating detection
in your activity, if you’re in landscape mode, this code would turn your phone to default mode ( portrait mode).
So be careful when using this !


Using Dialog in Android.

Android Dialog, wish it was simple as MessageBox in C#. LOL !

In fact, the way to use Dialog in Android is quite simple.

3 essential steps:

Step 1: Declare a Dialog Builder
In my example activity, onStart():
AlertDialog.Builder builder = new AlertDialog.Builder(this);

Step 2: Logic to handle event raised from Dialog.

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
enableLocationSettings();
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
default:
finish();
break;
}

}
};

private void enableLocationSettings() {
Intent locationSettingsIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(locationSettingsIntent);
}

Step 3: Show our dialog with our settings.

builder.setMessage("Do you want to turn on GPS ?")
.setPositiveButton("YES", dialogClickListener)
.setNegativeButton("NO", dialogClickListener).setCancelable(false).show();


You could be familiar with Dialog, usually , there are buttons Yes/Accept/OK… and No/Deny/Cancel ….
These 2 groups of buttons called Positive Button and Negative Button group.
What you have to do is handle event corresponding to these buttons.
You may also see the my setting .setCancelable(false)
This is the answer for the question:

How can I prevent users from pressing back button to cancel dialog ?

Here is example project if you want to investigate more details

http://www.mediafire.com/?k0zcb6vbadblcrz


Weird question mark in Android ?

Tonight , when working on implementing custom list-view in Android, I run into a weird question mark in following code:
android:layout_height="?android:attr/listPreferredItemHeight"
at http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html

It turns out that “?” is to indicate the pre-defined style attribute called “listPreferredItemHeight” located in namespace “android”.

That’s all 🙂

Find the quick answer from stackoverlow here : http://stackoverflow.com/questions/7923221/what-androidattr-listpreferreditemheight-is-doing-and-how


Change appearance of button/imageview/imagebutton in android for different states

“States” here, I mean the press/focus states of control. We have normal state, on-focusing state and pressed-state. ( I used these, and don’t care about others ).
I find an interesting post at http://www.mkyong.com/android/android-imagebutton-selector-example/

Just re-post in my blog for later use.
Step 1 : Add images to resource.
button_normal_green.png – Default image button.
button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
button_pressed_yellow.png – Display when button is pressed.
Step 2: Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “new_button.xml“. This file defined which button state is belong to which image.

Now, you can refer to this button via this Id : @drawable/new_button.

Step 3: Add Button
Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “android:background=”@drawable/new_button”
File : res/layout/main.xml

Step 4: Code the main activity
A normal button with a simple click listener.

File : MyAndroidAppActivity.java



import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MyAndroidAppActivity extends Activity {

Button imageButton;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

addListenerOnButton();

}

public void addListenerOnButton() {

imageButton = (Button) findViewById(R.id.imageButtonSelector);

imageButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Toast.makeText(MyAndroidAppActivity.this,
"ImageButton (selector) is clicked!",
Toast.LENGTH_SHORT).show();

}

});

}

}

Reference :
1/ http://www.mkyong.com/android/android-imagebutton-example/
2/ http://developer.android.com/resources/tutorials/views/hello-formstuff.html

3/ Sample source code can be found here http://www.mediafire.com/?h1gvjdagmkupuiu