Sunday, May 30, 2010

Different ways for Notifying Users in Android

The 3 main different ways to notify an user are,

Dialog
Toast
Notification

Dialog

For notifying users with dialog, We will create an object of dialog. In this, I am removing the title using requestWindowFeature(Window.FEATURE_NO_TITLE) and adding a layout to the dialog to it using addContentView().

Toast

Second one is toast, that will flash and will display for a predefined period either as, Toast.LENGTH_SHORT or Toast.LENGTH_LONG.

Notification

Third one is notification, to notify user, about any background activity is started.

The complete sample programs is,

 
public class NotifyUser extends Activity {

LayoutParams panelParams, compParams, tvParams;
LinearLayout popupGrid;
LinearLayout buttonLayout;
TextView tv;
Button b1, b2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayDialog();
displayToast();
displayNotification();
}

public void displayDialog() {
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().getAttributes().width = 250;
popupGrid = new LinearLayout(this);
buttonLayout = new LinearLayout(this);
tv = new TextView(this);
b1 = new Button(this);
b2 = new Button(this);
panelParams = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
panelParams.width = 250;
compParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
tvParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
popupGrid.setOrientation(LinearLayout.VERTICAL);
tv.setText("Are you sure?");
b1.setWidth(100);
b2.setWidth(100);
b1.setText("Yes");
b2.setText("No");
tvParams.setMargins(80, 0, 0, 0);
panelParams.setMargins(20, 0, 0, 0);
popupGrid.addView(tv, tvParams);
buttonLayout.addView(b1, compParams);
buttonLayout.addView(b2, compParams);
popupGrid.addView(buttonLayout, panelParams);
dialog.addContentView(popupGrid, panelParams);
dialog.show();
}

public void displayToast() {
Toast.makeText(this, "Sorry, please try again", Toast.LENGTH_SHORT)
.show();
}

public void displayNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Nithin";
CharSequence message = "Crazy About Android...";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(this, from, message, contentIntent);
nm.notify(1, notif);
}
}



In notification, itself different forms are there. - when we click on the notification, it will take us to a new activity. For this, in pendingIntent, for the intent object, specify the acitivity, that we want to go.


PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, SampleActivity.class), 0);


Another form is, we can customize the notification layout using custom expanded view. For this create a layout in XML and use remoteView to use the XML. Use remoteView methods to set ImageView and TextView. The XML is,


android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dp"
>
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000"
/>




The complete method is,


public void displayNotificationWithExandedView() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.icon,
"Crazy About Android...", System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(getPackageName(),
R.layout.notify_layout);
contentView.setImageViewResource(R.id.image, R.drawable.icon);
contentView.setTextViewText(R.id.text,
"Hello, this message is in a custom expanded view");
notif.contentView = contentView;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, SampleActivity.class), 0);
notif.contentIntent = contentIntent;
nm.notify(1, notif);
}



The screenshots are,







Saturday, May 29, 2010

Data Storage in Android

The storage system in Android are mainly divided into 3 types.

Database(sqlite)
File
SharedPreference

Database is already explained in my older post and you can see here

Files

Android can save files directly to the device internal storage. These files are private to the application and will be removed if you uninstall the application.

We can create a file using openFileOutput() with parameters as file name and the operating mode. Similarly, we can open the file using openFileInput() passing the parameter as the fileName. One thing, that we need to remeber is, give the file name with extension. In this example I am creating a text(.txt) file.

The complete code is,

  
public class ReadNWriteFile extends Activity {

final String TEST_STRING = new String("Hello Android");
final String FILE_NAME = "SAMPLEFILE.txt";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
fileCreate();
tv.setText(readFile());
setContentView(tv);
}

private void fileCreate() {
try {
OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(TEST_STRING);
osw.close();
} catch (Exception e) {
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}

private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
}


SharedPreferences

SharedPreference is another persistent storage mechanism in Android. In this, we can store the data in key-value pairs. One drawback is it allows only primitive data types and String. We can get an object of shared preference using getSharedPreferences(). One thing, we need to remember is after writing anything to sharedPreference, we need to do commit(). Then only new values will be reflected. We can write values into sharedPreference using put() methods like putInt(), putString() etc and can retrieve the values from sharedPreference using get() methods as getInt(), getString() etc.

A sample program is,


public class DataStorage extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();

boolean dataFromPrefBool = pref.getBoolean("keyBoolean", false);
float dataFromPrefflaot = pref.getFloat("keyFloat", 0.0f);
int dataFromPrefInt = pref.getInt("keyInt", 0);
long dataFromPrefLong = pref.getLong("keyLong", 0);
String dataFromPrefString = pref.getString("keyString", null);
}
}


In the put(), we are passing key and value and in get(), we are passing key and the default value if the key is not present in the sharedPreference.

Tuesday, May 18, 2010

Scrolling of TextView

Code Snippet for scrolling textview is

TextView tv;
tv.setMovementMethod(ScrollingMovementMethod.getInstance());

TabActivity in Android

Tabs can be created in Android, in a number of ways. I am going to create using Java only. I don't want to use xml and I want my tab content should be dynamic. So, I am implementing Tabs through TabHost.TabContentFactory. This interface has an abstract method called createTabContent() and it will return a View.

Another interesting fact , I came to know is, Tabs can be created without TabActivity too. Thats a new information for me. I came to know this through a discussion in Android Developers google group. If you are interested you can see the complete discussion here

The complete code for this is,


public class SampleTab extends Activity implements TabHost.TabContentFactory {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TabHost tabHost = new TabHost(SampleTab.this);
TabWidget tabW = new TabWidget(this);
FrameLayout frame = new FrameLayout(this);
frame.setId(android.R.id.tabcontent);
tabW.addView(frame);
tabW.setId(android.R.id.tabs);
tabHost.addView(tabW);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("Tab1").setIndicator("Tab1")
.setContent(this));
tabHost.addTab(tabHost.newTabSpec("Tab2").setIndicator("Tab2")
.setContent(this));
setContentView(tabHost);
}

public View createTabContent(String tag) {
TextView tv = new TextView(SampleTab.this);
tv.setText("This is from : " + tag);
return tv;
}
}


Happy Coding

Androidians