2014

Wednesday, December 17, 2014

Creating Shared Preferences in android.....


This article shows how to create SharedPreferences in android.


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class MyPreferences {
    public static boolean putInt(Context activity,String key,int value){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, value);
        editor.commit();                      
        return true;      
    }
 
    public static int getInt(Context activity,String key,int defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        int temp = sharedPreferences.getInt(key, defaultValue);
        return temp;      
    }
 
    public static boolean putString(Context activity, String key, String value)
    {
    SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();                      
        return true;         }
 
    public static String getString(Context activity,String key,String defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        String temp = sharedPreferences.getString(key, defaultValue);
        return temp;      
    }
 
    public static boolean putLong(Context activity, String key, long value)
    {
    SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong(key, value);
        editor.commit();
return true;         }
 
    public static long getLong(Context activity,String key,long defaultValue){
        SharedPreferences sharedPreferences = activity.getSharedPreferences("pref", Activity.MODE_PRIVATE);
        long temp = sharedPreferences.getLong(key, defaultValue);
        return temp;      
    }
 
}

By implementing above code you can easily Create SharedPreferences.

Thursday, December 4, 2014

Creating notification in android.....


This article shows how to create notification in android.


public MyNotification(Context ctx){
super();
this.ctx=ctx;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
long when = System.currentTimeMillis();
Notification.Builder builder = new Notification.Builder(ctx);
notification=builder.getNotification();
notification.when=when;
notification.icon=R.drawable.mp3_icon;
remoteViews=new RemoteViews(ctx.getPackageName(),                        R.layout.service_layout);
notification.contentView = remoteViews;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(5, notification);
}



Wednesday, December 3, 2014

Creating Custom views in a PreferenceActivity in android...



This article shows how to add custom view in PreferenceActivity in android.

Create main.xml, the only necessary view is a ListView, with id: android:id="@android:id/list".

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:weightSum="1">
        <ListView 
            android:id="@android:id/list" 
            android:layout_weight="1"
            android:layout_width="fill_parent"
                android:layout_height="0dp">
        </ListView>
        <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


Create CustomPreferenceActivity.java

public class CustomPreferenceActivity extends PreferenceActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                addPreferencesFromResource(R.xml.settings);
               
                //setup any other views that you have
                TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("View Added");
        }
}

Sunday, September 28, 2014

Handling Looper.prepare() in android.....


This article shows how to handle Looper.prepare() in android.

Show Toast inside Thread by using UiThread.


new Thread() {
        @Override
        public void run() {
               try {
                     // code runs in a thread
                     runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.dismiss();
                            }
                     });
               } catch (final Exception ex) {
                   Log.i("---","Exception in thread");
               }
        }
 }.start();
This will avoid Looper.prepare() in android.

Wednesday, September 3, 2014

Installing & Uninstalling Home Screen Shortcut.....


This Article shows to create installing & uninstalling home screen shortcut.

1- Create method for adding shortcut to home screen(addShortcut()).

private void addShortcut() {
Intent shortcut = new Intent(this, MainActivity.class);
shortcut.setAction(Intent.ACTION_MAIN);
Intent add = new Intent();
add.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
add.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Your Activity Name");
add.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher));
add.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(add);
    }

2- Create method for removing shortcut from home screen(removeShortcut()).

private void removeShortcut() {
Intent shortcut = new Intent(this, MainActivity.class);
shortcut.setAction(Intent.ACTION_MAIN);
Intent add = new Intent();
add.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
add.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Your Activity Name");
add.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
sendBroadcast(add);
    }

3- Add following permissions to Manifest.xml.

<uses-permission        android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission          android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

Thursday, August 14, 2014

Creating SimpleAdapter for ListView in Android.....


This Article shows to create SimpleAdapter for ListView in Android.

1- Create row xml for ListView(row.xml).

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical">
     <TextView android:id="@+id/text1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView android:id="@+id/text2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="1"/>
     <TextView android:id="@+id/text3"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="1"/>
</LinearLayout>


2- Create ListActivity(MainActivity.java).

import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;

public class Abc extends ListActivity { 
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> list =
                  new ArrayList<HashMap<String, String>>();

String[] from = new String[] {"Text1", "Text2", "Text3"};

int[] to = new int[] {R.id.text1, R.id.text2, R.id.text3};
for(int i=0; i<3; i++) {
HashMap<String,String> map = new HashMap<String, String>();
//initialize row data
map.put(from[i], "Text" + i);
list.add(map);
}
setListAdapter(new SimpleAdapter(this, list, R.layout.row, from, to));
}
}

Thursday, August 7, 2014

Creating ListActivity & BaseAdapter in Android.....


This article shows to create ListActivity & BaseAdapter in Android.

1- Create BaseAdapter for ListActivity(MyAdapter.java).

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
private Activity activity;
private String[] str;
public MyAdapter(Activity c, String[] str)
{
this.activity = c;
this.str = str;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return (str.length);
}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return str[arg0];
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
TextView txtView;
if(arg1 == null)
{
        txtView= new TextView(activity);
txtView.setPadding(15,15,15,15);
}
else
txtView= (TextView) arg1;
txtView.setText(str[arg0].toString());
txtView.setTextSize(20);
return txtView;
}
}

2- Create ListActivity(MainActivity.java).

import android.app.ListActivity;
import android.os.Bundle;

public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new MyAdapter(this, new String[]{"Android", "PHP", "ASP.NET", "iPhone"}));
}
}

Wednesday, August 6, 2014

Creating animated dialog in android…..


This article shows you to create animated dialog in android.

1- Create anim folder inside resoures(res).

2- Create xml for slide in dialog(slide_in.xml) in anim.

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromYDelta="100%p"
    android:toYDelta="0%p" />

3- Create xml for slide out dialog(slide_out.xml) in anim.


<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromYDelta="0%p"
    android:toYDelta="100%p" />

4- Create style for animation in styles.xml.

<style name="DialogAnimation">
        <item name="android:windowEnterAnimation">@anim/slide_in</item>
        <item name="android:windowExitAnimation">@anim/slide_out</item>
</style>

<style name="AnimatedDialogTheme" parent="@android:style/Theme.Panel">
        <item name="android:windowAnimationStyle">@style/DialogAnimation</item>
</style>

5- In Java file initialize dialog as-

//Use try catch to avoid Exception in lower api devices
try {
dialog = new Dialog(this, R.style.AnimatedDialogTheme);
} catch(Exception ex) {
dialog = new Dialog(this);
}

Tuesday, August 5, 2014

Creating custom toast using xml.....


This article shows you to create custom toast in android.

1- Create xml for Toast(toast.xml).

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:padding="8dp"
              android:background="@drawable/image"
              >    
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text=""
              android:textColor="#000"
              android:textSize="20sp"
              />   
</LinearLayout>

2- Create Activity Class(MainActivity.java).

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private TextView textview;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showCustomToast("Hey! I'm Toast.");
}
});
}

protected void showCustomToast(String msg) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup)                                         findViewById(R.id.toast_layout_root));
textview = (TextView) layout.findViewById(R.id.text);
textview.setText("" + text);
Toast toast = new Toast(this);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);/* Replace (0,0) to corresponding (x,y) to set position of toast.*/
toast.setView(layout);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
}

Creating custom dialog using xml.....


This tutorial show you how to create a custom dialog in Android.
          1-  Create activity & custom dialog layout xml file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press me!" />

</LinearLayout>


custom_dialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hey! I'm Dialog."
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <Button
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press Me!" />


</LinearLayout>


2-  Create Activity Class.

MainActivity.java

package com.example.customdialog;

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


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showCustomDialog();
}
});
}

protected void showCustomDialog() {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(this);
dialog.setTitle("Custom Dialog");
dialog.setContentView(R.layout.custom_dialog);
Button button = (Button) dialog.findViewById(R.id.but);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}

}