Category Archives: Uncategorized

Listen to content uri changes

If you have an URI that you want to listen to but no broadcast is available from the content uri (No Broadcast Receiver available), then you can use ContentObserver class for this purpose.

Class:

public class myContentOberser extends ContentObserver{</code>

private String Uri contentUri = "";
private ContentResolver resolver = null;

public myContentObserver(Handler handler){
super(handler);
}

@Override
public void onChange(boolean selfChange){
// Perform what you want to do here.
}

public void startObserve(Context context, Uri uri){
if (resolver == null){
resolver = context.getContentResolver();
}

// Register the required uri to the system
resolver.registerContentObserver(uri, false, this);
}

public void stopObserver(){
if (resolver != null){
resolver.unregisterContentObserver(this);
}
}
}

Advertisements

Customizing listeners in your own class/object

I wanted to listen to a listeners which I implemented in my custom class without defining it on my MAIN class, so I come up with this idea of some sort of inheriting the listener and pass back to my main calling class. For the following example, I will show how to pass the listener (LocationManager.LocationListener) back to the MAIN. This is good if you want to have your custom class which will implements bunch of other listeners.

For example, I have Main and Class A.
Main – Main Class
MyLocationManager – Called from Main Class. Implements LocationManager.LocationListener
MyLocationManagerInterface – Where interface is declared

Main.java

public Main implements MyLocationManagerInterface{
  public MyLocationManager locationManager;

  public void onCreate(){
    locationManager = new MyLocationManager(this);
  }

  @Override
  public void onLocationChanged(Location location) {
    // Code here will be executed once LocationManager.LocationListener is called, even is not declared here.
  }
}

MyLocationManagerInterface.java

public interface MyLocationManagerInterface {
	public void onLocationChanged(Location location);
}

MyLocationManager.java

public MyLocationManager implements LocationListener{
  MyLocationManagerInterface myLocMgrIf;

  public MyLocationManager(MyLocationManagerInterface listener){
    myLocMgrIf = listener; // Init custom listener
    ......
    // Here you init all the LocationManager stuffs and request for updates.
  }

  @Override
  public void onLocationChanged(Location location) {
    myLocMgrIf.onLocationChanged(location); // Here you pass the location to custom interface
  }
}

Create simple JSON data from PHP from mysql query

function was not tested, minor modification will be needed. For this in Java

Example output:
{
“status”:”200″,
“error_message”:””,
“item”:[
{“ID”:”18″, “Name”:”Item A”} ,
{“ID”:”19″, “Name”:”Item B”} ,
{“ID”:”20″, “Name”:”Item C”} ,
{“ID”:”21″, “Name”:”Item D”}
]
}

</pre>
function constructJson($query){
 $json_str = "";
 $row_count = 0;
 if($total=mysql_num_rows($query)){
 $json_str = constructJsonHead().constructJsonStatus(200,"")."[";
 $json_item = "";
 while($data=mysql_fetch_assoc($query)){
 $count = 0;
 if(count($data)>1)
 $json_item .= constructJsonHead();

foreach($data as $key => $value){
 if(count($data)>1)
 $json_item .= "\"$key\":\"$value\"";
 else
 $json_item .= "\"$value\"";

$count++;
 if($count < count($data)) $json_item .= ",\n"; } $row_count++; if(count($data) > 1)
 $json_item .= constructJsonTail()."\n";

if($row_count < $total)
 $json_item .= ",\n";

}
 }else{
 $json_str .= constructJsonHead().constructJsonStatus(201,"No Item")."[]".constructJsonTail();
 }
 return $json_str.$json_item."]".constructJsonTail();
}

function constructJsonStatus($response_code,$msg){
 return "\"status\":\"$response_code\",\"error_message\":\"$msg\",\"item\":";
}

function constructJsonHead(){ return "{";}
function constructJsonTail(){ return "}";}
<pre>

Convert integer array to integer

This is a simple function on how one can convert an integer array (int[]) to integer value

</pre>
public int add(int[] array) {
int len = array.length;
int tmp = 0;
for(int i: array){
tmp += i*((int)Math.pow(10,--len));
}

return tmp;
}
<pre>

Hiding soft keyboard

This is just to show if you need to hide keyboard after you are done with inputting a edittext/autocompletetextview. Just call hideSoftKeyboard() will hide the keyboard.


private EditText searchBar;

private void hideSoftKeyboard(){
 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(searchBar.getWindowToken(), 0);
 }

Android using SharedPreferences

Rather than having to call PreferenceManager.getDefaultSharedPreferences everytime in different activities, and have to keep track of all the keys in your application, it is easier to keep all preferences in one place. For that I create a wrapper class just for my preferences.

PreferencesClass.java

class PreferencesClass {
    static String preference_name = "my_preferences";
    static String preference_one = "preference_one";
    static String preference_two = "preference_two";
    static String preference_three = "preference_three";
    private static SharedPreferences getPreference(Context context){
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static int getPreferenceOne(Context context){ return getPreference(context).getInt(preference_one,0); }
    public static int setPreferenceOne(Context context, int value){ getPreference(context).edit().putInt(preference_one, value).commit(); }

public static int getPreferenceTwo(Context context){ return getPreference(context).getString(preference_two,null); }
    public static int setPreferenceTwo(Context context, string value){ getPreference(context).edit().putString(preference_two, value).commit(); }
    public static int getPreferenceThree(Context context){ return getPreference(context).getBoolean(preference_three,false); }
    public static int setPreferenceThree(Context context, boolean value){ getPreference(context).edit().putBoolean(preference_one, value).commit(); }

To use the method simply call the following in your activity

int preference_one = PreferencesClass.getPreferenceOne(getContext());

Check if virtual keyboard is up

As most of you can find in internet, there is no easy way to check if the soft keyboard is shown on the screen. Depending on what you are looking to achieve, for Touch Screen only application, I use the following solution. Might not be the perfect solution for you but it works for me.

As this is TOUCH only application, so I assume soft keyboard will only get triggered by when one of the edit text field got touch. So I set a public variable for the flag, false by default. When user click on either one of the edit text field, touch listener will set the flag to true, and when focused came back to main view, I will set the flag back to false in dispatchTouchEvent method.

Setting the flag

//This is my flag
public boolean isSoftKeyboardDisplayed = false;

Now, set listener for the edit text field

// This is my edit text field box
EditText editText = (EditText)findViewById(R.id.edittext);
editText.setOnTouchListener(new onTouchListener(){
@Override
public void onTouch(View v, MotionEvent event){
// The flag is set to true everytime the edit text is touched.
isSoftKeyboardDisplayed = true;
}
});

Dismiss the soft keyboard by implementing  dispatchTouchEvent to your root view. So when user touch any where other than the edit text field, the soft keyboard dissapear

// This part is to dismiss the softkeyboard when you click anywhere other than the edit text
@Override
public boolean dispatchTouchEvent(MotionEvent event) {

View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
// This is where I set the flag back to false when my soft keyboard is hidden
isSoftKeyboardDisplayed= false;
}
}
return ret;
}

As a result, I just check the isSoftKeyboardDisplayed flag for my keyboard display check.

Using Google Drive as private Git

Setting up local git repo
For Ubuntu Users :

  1. Install grive (sudo apt-get install grive)
  2. Create a folder (treat it as google drive root folder)
  3. Enter “grive -a”
  4. Go to the link returned on shell in browser and get the passkey
  5. Enter passkey
  6. DONE!
  7. Enter “git init –bare”
  8. Create another folder outside of your google drive folder (where your project will be)
  9. CD into the folder on step 8
  10. Enter “git init”
  11. Add files into it and perform an initial push (git add <files> -> git commit -m “<message>” -> git push origin <google drive root folder>)
  12. Just enter “grive” in the folder for pushing/pulling new files from the google drive.

For Windows User:

  1. Install  drive.google.com
  2. Install msysgit
  3. Launch msysgit
  4. Create a folder
  5. Open command prompt into the folder created from step 4
  6. Enter “git init –bare”
  7. Create another folder outside of your google drive folder (where your project will be)
  8. CD into the folder on step 7
  9. Enter “git init”
  10. Add files into it and perform an initial push (git add <files> -> git commit -m “<message>” )
  11. Add your master to remote branch (git remote add origin <google drive project folder>)
  12. Now you are ready to push your first commit (git push origin master)

To clone your code in another machine:
For all users:

  1. Install google drive.
  2. Sync all the files from server (command grive for ubuntu users)
  3. Check if you have the correct files uploaded before
  4. CD to folder where you want your project to be on
  5. Enter “git clone <path to your google drive root folder locally> <your new folder name>”
  6. DONE! you can view your committed files in your new folder

Object oriented PHP

to create a class:

class.php

<?php
class testclass{
private static $obj;
function __construc(){
//do your stuff
}
function method1($arg1,$arg2){
//to use the private variable
self::$obj = something;
}
function method2($arg1,$arg2){
//to use local function
self::method1($arg1,$arg2);
}
}
?>

Now the main file:
main.php

<?php
include_once 'class.php';

//Construct
$class_object = new testclass();

//using method from class
$class_object->method1($arg1,$arg2);
?>

Android create option menu with icon

To put an image/icon on your option menu in Android, simply just set something like the below code in your activity
</pre>
@Override

public boolean onCreateOptionsMenu(Menu menu) {
 menu.add(0, Menu.FIRST, 1, "Export").setIcon(R.drawable.music_playqueue_save_playlist);

return super.onCreateOptionsMenu(menu);

}