Saturday 28 February 2015

Time Picker in Android

TimePicker View 

The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.

Using the TimePicker View

1 . Modify the main.xml file located in the res/layout folder by adding the following lines in bold:

 <?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”​>
 
<TimePicker android:id=”@+id/timePicker” 
​​​​android:layout_width=”wrap_content” ​​
​​android:layout_height=”wrap_content” />
 
<Button android:id=”@+id/btnSet” 
​​​​android:layout_width=”wrap_content” 
​​​​android:layout_height=”wrap_content” 
​​​​android:text=”I am all set!” />
 
</LinearLayout>

 2 . Add the following statements in bold to the MainActivity.java file: 

package​ com.emergingandroidtech.TimePicker;
import ​android.app.Activity;
import ​android.os.Bundle;
import android.view.View;
import android.widget.Button; 
import android.widget.TimePicker; 
import android.widget.Toast;
 
public ​class ​MainActivity ​extends ​Activity
​{ 
​​​​TimePicker timePicker; ​
​​​
 ​​​​/**​Called ​when​ the​ activity​ is ​first​ created.​*/ 

​​​​@Override ​​​​public ​void ​onCreate(Bundle​savedInstanceState)​{ 
​​​​​​​​super.onCreate(savedInstanceState); 
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​timePicker = (TimePicker) findViewById(R.id.timePicker); 
​​​​​​​​timePicker.setIs24HourView(true);
​​​​​​​​
//---Button view--- ​​​​
​​​​Button btnOpen = (Button) findViewById(R.id.btnSet); ​
​​​​​​​btnOpen.setOnClickListener(new View.OnClickListener() {
​          public void onClick(View v) 
         { 
       ​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Time selected:” + ​​​​​​​​​​​​​​​​​​​​​​​​​​timePicker.getCurrentHour() + ​​​​​​​​​​​​​​​​​​​​​​​​“:” + timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​
          ​​​​​​​​​​​} ​​​​​​​​
 });
 ​​​​}
}
 
3 . This time, the TimePicker will be displayed in the 24-hour format. Clicking the Button will display the time that you have set in the TimePicker.

How It Works 

The TimePicker displays a standard UI to enable users to set a time. By default, it displays the time in the AM/PM format. If you wish to display the time in the 24-hour format, you can use the  setIs24Hour​View() method. 
To programmatically get the time set by the user, use the getCurrentHour() and getCurrentMinute() methods:
 
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Time​selected:”​+ ​​​​​​​​​​​​​​​​​​​​​​​​​​timePicker.getCurrentHour() + ​​​​​​​​​​​​​​​​​​​​​​​​“:”​+​timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();



Friday 27 February 2015

Shared Preferences in Android

* Basically shared preference in android are used to save the state of an activity or to save the important data within the scope of an application means data will remain saved till the application is installed in the devices. Shared Preference also works as Sessions which are used for the automatic login process.

* A lightweight mechanism known as shared preferences to save small chunks of data.

* Using the SharedPreferences object, however, you save the data you want through the use of key/ value pairs — specify a key for the data you want to save, and then both it and its value will be saved automatically to an XML file for you.


using getSharedpreferences() 

 To see how the SharedPreferences object works, the following Try It Out demonstrates how easy it is to save user data to an XML file, and then retrieve it easily via the same object.
 Saving Data Using the SharedPreferences Object

1-  Add the following statements in bold to the main.xml file:

 <?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”​> 

<SeekBar ​​​​android:id=”@+id/SeekBar01” 
​​​​android:layout_width=”fill_parent” ​​​​
android:layout_height=”wrap_content” />

 <TextView ​​​​android:id=”@+id/TextView01” 
​​​​android:layout_width=”fill_parent” ​​​​
android:layout_height=”wrap_content”
 ​​​​android:text=”@string/hello” /> 

<EditText ​​​​android:id=”@+id/EditText01” 
​​​​android:layout_width=”fill_parent”
 ​​​​android:layout_height=”wrap_content” /> 

<Button ​​​​android:id=”@+id/btnSave”
 ​​​​android:text=”Save” ​​​​
android:layout_width=”wrap_content” 
​​​​android:layout_height=”wrap_content” /> 

</LinearLayout>

2 . Add the following statements in bold to the MainActivity.java file: 

package ​com.emergingandroidtech.SharedPreferences;
import ​android.app.Activity; 
import ​android.os.Bundle;
import android.content.SharedPreferences; 
import android.view.View;
import android.widget.Button;
import android.widget.EditText; 
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
 
public​ class ​MainActivity ​extends ​Activity​
​​​​private SharedPreferences prefs;
 ​​​​private String prefName = “MyPref”; ​​​​
private EditText editText; ​​​​
private SeekBar seekBar; 
​​​​private Button btn;
​​​​private static final String FONT_SIZE_KEY = “fontsize”;
 ​​​​private static final String TEXT_VALUE_KEY = “textvalue”;
 
​​​​/**​Called​when​the​activity​is​first​created.​*/ 
​​​​@Override ​​​​public​ void ​onCreate(Bundle​savedInstanceState)​
​​​​​​​​super.onCreate(savedInstanceState);
 ​​​​​​​​setContentView(R.layout.main);
​​​​​​​​editText = (EditText) findViewById(R.id.EditText01);
 ​​​​​​​​seekBar = (SeekBar) findViewById(R.id.SeekBar01);
​​​btn = (Button) findViewById(R.id.btnSave);
​​​​​​​​btn.setOnClickListener(new View.OnClickListener() 
{
 ​​​​​​​​​​​​public void onClick(View v) 
{ ​​​​​​​​​​​​​​​​

//---get the SharedPreferences object---
 ​​​​​​​​​​​​​​​​prefs = getSharedPreferences(prefName, MODE_PRIVATE);
 ​​​​​​​​​​​​​​​​SharedPreferences.Editor editor = prefs.edit();
 
​​​​​​​​​​​​​​​​//---save the values in the EditText view to preferences--- ​​​​​​​​​​​​​​​​
editor.putFloat(FONT_SIZE_KEY, editText.getTextSize()); 
​​​​​​​​​​​​​​​​editor.putString(TEXT_VALUE_KEY, editText.getText().toString());
 
​​​​​​​​​​​​​​​​//---saves the values--- 
​​​​​​​​​​​​​​​​editor.commit();
 
​​​​​​​​​​​​​​​​//---display file saved message--- 
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“Font size saved successfully!”, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​}
 ​​​​​​​​});
 
​​​​​​​​//---load the SharedPreferences object--- ​​​​​​​​
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
 
​​​​​​​​//---set the TextView font size to the previously saved values--- 
​​​​​​​​float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12);
 
​​​​​​​​//---init the SeekBar and EditText--- ​​​​​​​​
seekBar.setProgress((int) fontSize); ​​​​​​​​
editText.setText(prefs.getString(TEXT_VALUE_KEY, “”)); ​​​​​​​​editText.setTextSize(seekBar.getProgress());
​​​​​​​​seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
{ ​​​​​​​​​​​​
@Override ​​​​​​​​​​​​public void onStopTrackingTouch(SeekBar seekBar) { ​​​​​​​​​​​​}
​​​​​​​​​​​​@Override ​​​​​​​​​​​​public void onStartTrackingTouch(SeekBar seekBar) { ​​​​​​​​​​​​}
​​​​​​​​​​​​@Override ​​​​​​​​​​​​public void onProgressChanged(SeekBar seekBar, int progress, ​​​​​​​​​​​​​​​​​​​​boolean fromUser) { ​​​​​​​​​​​​​​​​

//---change the font size of the EditText--- ​​​​​​​​​​​​​​​​
editText.setTextSize(progress); ​​​​​​​​​​​​
} ​​​​​​​​
});
 ​​​​}
 }

3 . Enter some text into the EditText view and then change its font size by adjusting the SeekBar view  Click Save.
 
4 .  The application now displays the same text that you entered earlier using the same font size set earlier.

Saturday 14 February 2015

How to dismiss the DialogFragment in Android ?

* There are two ways you can dismiss a dialog fragment.

* The first is to explicitly call the dismiss() method on the dialog fragment in response to a button or some action on the dialog view.

1- Calling dismiss() :

if ( someview.getId() == R.id.btn_dismiss)
{
    //use some callbacks to advise clients
    //of this dialog that it is being dismissed
    //and call dismiss
     dismiss();
     return;
}

* The other way to dismiss a dismiss a dialog fragment is to present another dialog fragment.
The way you dismiss the current dialog and present the new one is slightly different than just dismissing the current dialog.

2- Setting up a dialog for a back stack

 if ( someview.getId() == R.id.btn_invoke_another_dialog )
{
   Activity act = getActivity();
   FragmentManager fm = act.getFragmentManager();
   FragmentTransaction ft = fm.beginTransaction();
   ft.remove(this);

   ft.addToBackStack(null);
   //null represents no name for the back stack transaction

   HelpDialogFragment hdf = HelpDialogFragment.newInstance(R.string.helptext) ;
   hdf.show( ft, "HELP");
   return;
}


Friday 13 February 2015

How to show a Dialog Fragment in Android ?

* Once you have a dialog fragment constructed, you need a fragment transaction to show it.

* Like all other fragments, operations on dialog fragments are conducted through fragment transactions.

* The show() method on a dialog fragment takes a fragment transaction as an input.

* The show() method uses the fragment transaction to add this dialog to the activity and then commits the fragment transaction.

* However, the show() method does not add the transaction to the back stack.

* If you want to do this, you need to add this transaction to the back stack first and then pass it to the show() method.

* The show() method of a dialog fragment has the following signatures:

public int show( FragmentTransaction transaction, String tag)
public int show( FragmentManager manager, String tag)

* The first show() method displays the dialog by adding this fragment to the passed-in transaction with the specified tag. This method then returns the identifier of the commited transaction.

* The second show() method automates getting a transaction from the transaction manager.
This is a shortcut method. However, when you use this second method, you don't have an option to add the transaction to the back stack. If you want that control, you need to use the first  method.
The second method could be used if you wanted to simply display the dialog, and you had no other
reason to work with a fragment transaction at that time.

* A nice thing about a dialog being a fragment is that the underlying fragment manager does the basic state management.

* For example, even if the device rotates when a dialog is being displayed, the dialog is reproduced without you performing any state management.

* The dialog fragment also offers methods to control the frame in which the dialog's view is displayed, such as the title and the appearance of the frame.
 

Thursday 12 February 2015

How to create a Dialog Fragment in Android ?

* A Dialog Fragment being a fragment, the same rules and regulations apply when constructing a dialog fragment.
* The recommended pattern is to use a factory method such as newInstance() as we did before.
* Inside that newInstance() method, you use the default constructor for your dialog fragment, and then you add an arguments bundle that contains your passed-in parameters.
* You don't want to do other work inside this method because you must make sure that what you do here is the same as what Android does when it restores your dialog fragment from a saved state.
* And all that Android does is call the default constructor and re-create the arguments bundle on it.

Overriding onCreateView :

* When you inherit from a dialog fragment, you need to override one of the two methods to provide the view hierarchy for your dialog.
* The first option is to override onCreateView() and return a view.
* The second option is to override onCreateDialog() and return a dialog.

Overriding onCreateView() of a DialogFragment :

MyDialogFragment
{
    ........other functions
    public View onCreateView(LayoutInflator inflator, ViewGroup container, Bundle savedInstanceState)
   {
       //Create a view by inflating desired layout
       View v = inflator.inflate(R.layout.prompt_dialog, container, false);
      
       //you can locate a view and set values
       TextView tv = (TextView)v.findViewById(R.id.promptmessage);
        tv.setText(this.getPrompt());
    
       //you can set callbacks on buttons
       Button dismissBtn = (Button)v.findViewById(R.id.btn_dismiss);
       dismissBtn.satonClickListener(this);

      Button saveBtn = (Button)v.findViewById(R.id.btn_save);
      saveBtn.setonClickListener(this);
      return v;
   }
   .......other functions
}

Overriding onCreateDialog :

As an alternate to supplying a view in onCreateView(), you can override onCreateDialog() and supply a dialog instance.

Overriding onCreateDialog() of a DialogFragment :

MyDialogFragment
{
         ...........other functions
      @Override
      public Dialog onCreateDialog(Bundle icicle)
     {
           AlertDialog.Builder b = new AlertDialog.Builder(getActivity())
             .setTitle("My Dialog Title")
             .setPositiveButton("OK",this)
             .setNegativeButton("Cancel", this)
             .setMessage(this.getMessage());
          return b.create();
     }
        ........other functions
}

* In this example, you use the alert dialog builder to create a dialog object to return.
* This works well for simple dialogs.
* The first option of overriding onCreateView() is equally easy and provides much more flexibility.


Tuesday 10 February 2015

What is DialogFragment in Android ?

* Dialog-related functionality uses a class called DialogFragment.

* A DialogFragment is derived from the class Fragment and behaves much like a fragment.

* You will then use the DialogFragment as the base class for your dialogs.

* Once you have a derived dialog from this class such as

public class MyDialogFragment extends DialogFragment { ..... }

you can then show this dialog fragment MyDialogFragment as a dialog using a fragment transaction.

Showing a Dialog Fragment :

SomeActivity
{
   //......other activity functions

         public void showDialog()
         {
             //construct MyDialogFragment
             MyDialogFragment mdf = MyDialogFragment.newInstance( arg1, arg2 );
             FragmentManager fm = getFragmentManager();
             FragmentTransaction ft = fm.beginTransaction();
             mdf.show( ft, "my-dialog-tag");
         }
         //.....other activity functions
}

Steps to show a dialog fragment are as follows :
  1.   Create a dialog fragment.
  2. Get a fragment transaction.
  3. Show the dialog using the fragment transaction from step 2.


Monday 9 February 2015

How to use Dialogs in Android ?

* Dialogs in Android are asynchronous, which provides flexibility.

* However, if you are accustomed to a programming framework where dialogs are primarily synchronous ( such as Microsoft Windows, or JavaScript dialogs in web pages ), you might find asynchronous dialogs a bit unintuitive.

* With a synchronous dialog, the line of code after the dialog is shown does not run until the dialog has been dismissed.

* This means the next line of code could interrogate which button was pressed, or what text was typed into the dialog.

* In Android however, dialogs are asynchronous. As soon as the dialog has been shown, the next line of code runs, even though the user hasn't touched the dialog yet.

* Your application has deal with this fact by implementing callbacks from the dialog, to allow the application to be notified of user interaction with the dialog.

* This also means your application has the ability to dismiss the dialog from code, which is powerful.

* If the dialog is displaying a busy message because your application is doing something, as soon as your application has completed that task, it can dismiss the dialog from code.
 

Sunday 8 February 2015

What do you understand by Dialogs in Android ?

* The Android SDK offers extensive support for dialogs.

* A dialog is a smaller window that pops up in front of the current window to show an urgent message, to prompt the user for a piece of input, or to show some sort of status like the progress of a download.

* The user is generally expected to interact with the dialog and then return to the window underneath to continue with the application.

* Technically, Android allows a dialog fragment to also be embedded within an activity's layout.

* Dialogs that are explicitly supported in Android include the alert, prompt, pick-list, single-choice, multiple-choice, progress, time-picker, and date-picker dialogs. (This list could vary depending on the Android release.)

* Android also supports custom dialogs for other needs.

* It's important to note that Android 3.0 added dialogs based on fragments.

* The expectation from Google is that developers will only use fragment dialogs, even in the versions of Android before 3.0. This can be done with the fragment-compatibility library.




Friday 6 February 2015

About Responding to configuration change of device in Android .

* When an application is running on a device, and the device's configuration changes ( for e.g. is rotated 90 degrees ), your application needs to respond accordingly.

* For example, switching from portrait to landscape mode means the screen went from being tall and narrow to being short and wide.

* The UI elements (buttons, text, lists, and so on) will need to be rearranged, resized, or even removed to accommodate the new configuration.

* In android, a configuration change causes the current activity to go away and be recreated.

* The application itself keeps on running, but it has the opportunity to change how the activity is displayed in response to the configuration change.

* Be aware that configuration changes can take on many forms, not just device rotation.

* If a device is connected to a dock, that's also a configuration change.So is changing the language of the device.

* Whatever the new configuration is, as long as you've designed your activity for that configuration,
android takes care of most everything to transition to it, giving the user a seamless experience.


Wednesday 4 February 2015

What are the Predicates of Alarms, Pending intents and the Alarm Manager in Android ?

  1. Pending intents are intents that are kept in a pool and reused.You cannot new a pending intent.You really locate a pending intent with an option to reuse, update, and so on.
  2. An intent is uniquely distinguished by its action, data URI, and category.The detalis of the uniqueness are specified in the filterEquals() API of the intent class.
  3. A pending intent is furthur qualified (in addition to the base intent it depended on) by the request code.
  4. Alarms and pending intents(even intents, for that matter) are not independent.A given pending intent cannot be used for multiple alarms.The last alarm will override the previous alarms.
  5. Alarms are not persistent across boots.Whatever alarms you have set through the alarm manager will be lost when the device reboots.
  6. You will need to persist alarm parameters yourself if you would like to retain them beyond device reboots.You will need to listen to broadcast boot events and time-change events to reset these alarms as needed.
  7. The implication of the intent-based cancel API is that, when you use or persist alarms, you will also need to persist intents so that those alarms can be cancelled at a later time when needed.

Tuesday 3 February 2015

About Persistence of Alarms in Android ?

* Alarms are not persisted across device reboots.

* This means you will need to persist the alarm settings and pending intents in a persistent store and reregister them based on device reboot broadcast messages, and possibly time-change messages
( e.g., android.intent.action.BOOT_COMPLETED, ACTION_TIME_CHANGED, ACTION_TIMEZONE_CHANGED).

Monday 2 February 2015

How to Cancel an Alarm in Android ?

Cancelling a Repeating Alarm :

public void cancelRepeatingAlarm()
{
      // Get an intent that was originally used to invoke TestReceiver class
      Intent intent = new Intent(this.mContext, TestReceiver.class);
     
      // To Cancel, extra is not necessary to be filled in
      // Intent.putExtra("message", "Repeating Alarm");
     
      PendingIntent pi = this.getDistinctPendingIntent(intent, 2);

      // Cancel the alarm !
      AlarmManager am =    
     (AlarmManager)
     this.mContext.getSystemService(Context.ALARM_SERVICE);
      am.cancel(pi);

}

* To cancel an alarm, we have to construct a pending intent first and then pass it to the alarm manager as an argument to the cancel () method.

How to set a Repeating Alarm ?

I already discussed how to set a simple one-time alarm in previous posts. So let's now consider how we can set an alarm that goes of repeatedly.

Setting a Repeating Alarm :

public void sendRepeatingAlarm()
{
     Calendar cal = Utils.getTimeAfterInSecs(30);
     String s = Utils.getDateTimeString(cal);
    
     // Get an intent to invoke the receiver
     Intent intent = new Intent (this.mContext, TestReceiver.class);
     intent.putExtra("message", "Repeating Alarm");

     PendingIntent pi = this.getDistinctPendingIntent(intent, 2);
     // Schedule the alarm !
     AlarmManager am =
     (AlarmManager)
                            this.mContext.getSystemService(Context.ALARM_SERVICE);

     am.setRepeating(AlarmManager.RTC_WAKEUP,
                             cal.getTimeInMillis(),
                             5*1000,  // 5 secs repeat
                             pi);
}

protected PendingIntent getDistinctPendingIntent(Intent intent, int requestId)
{
     PendingIntent pi =
           PendingIntent.getBroadcast(
                         mContext,  //context, or activity
                         requestId,  // request id
                         intent,       // intent to be delivered
                         0);
    return pi;
}