2015 in review

The WordPress.com stats helper monkeys prepared a 2015 annual report for my blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 25,000 times in 2015. If it were a concert at Sydney Opera House, it would take about 9 sold-out performances for that many people to see it.

Click here to see the complete report.

Android : Spinner

What to do when you have a list and want user to select one item amongst it. Spinners make this task simpler. When the user clicks on that element they drop down like a list. The user can select one of the items and continuous. Thus they avoid blocking your view and using unnecessary screen space. Spinner is a view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view. So here in this Android Series we learn how to implement these Spinners. So, here I have a example where users has to select his gender and and Android version and click the button which launches a new activity to display the user selections. To switch between we use Intents and to pass the user selections of these spinners to the next activity we use SharedPreferences. To learn how this is done you can refer to my tutorial on Intents and Shared Preferences. If you find this hard then for now just display the user’ s selection in the same activity. So, let’s get on with Spinners. In our xml file we first drag and drop two spinner widgets. Now we need to specify each with the array of items to populate with. This is done by the attribute android:entries=” “. Don’t forget to declare that array in your strings.xml file and specify those elements in that array.


android:entries="@array/Android_Version"

Screenshot_2015-01-02-17-32-41 In the main activity, declare two Spinners, initialise their views. Now we we have to do is to set on item select listener which will identify the item selected by the user.


setOnItemSelectedListener(new CustomOnItemSelectedListener());

The setOnItemSelectedListener() registers a callback to be invoked when an item in this AdapterView has been selected. The CustomOnItemSelectedListener() is an interface implementing OnItemSelectedListener. The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods. The onItemSelected() callback method is invoked when an item in this view has been selected. This callback is invoked only when the newly selected position is different from the previously selected position or if there was no selected item. Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item. The onNothingSelected() callback method is to be invoked when the selection disappears from this view. The selection can disappear for instance when touch is activated or when the adapter becomes empty. The item selected by the user can be retrieved by getSelectedItem() which returns the data corresponding to the currently selected item, or null if there is nothing selected. This can be displayed in a TextView. Screenshot_2015-01-02-17-32-57


//Main Activity
package com.shirish.Intent;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
   Button next;
   Spinner gender,android;
   Editor editor;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     next=(Button) findViewById(R.id.next);
     setTitle("Intent 1");
     gender=(Spinner)findViewById(R.id.gender);
     android=(Spinner)findViewById(R.id.android);
     SharedPreferences pref = getApplicationContext().getSharedPreferences("Options", MODE_PRIVATE);
     editor=pref.edit();
     gender.setOnItemSelectedListener(new CustomOnItemSelectedListener());
     next.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
            String gen=gender.getSelectedItem().toString();
            String and=android.getSelectedItem().toString();
            editor.putString("gender", gen);
            editor.putString("android", and);
            editor.commit();
            Toast.makeText(getApplicationContext(), "Settings saved!",Toast.LENGTH_LONG ).show();
            Intent in=new Intent(MainActivity.this,NextActivity.class);
            startActivity(in);
            //finish();
          }
      });
   }
}

//CustomOnItemSelectedListener Interface
package com.shirish.Intent;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {  }

  @Override
  public void onNothingSelected(AdapterView<?> parent) {  }
}

Download The Source code here: To Download Click Here!

Android : Intents & Shared Preferences

In this example we are particularly going to learn three things. First about Intents and switching between activities, then about Spinners and about Shared Preferences. So, let’s just say you have created an activity like a Menu and whenever user clicks on Menu’s one of the buttons; next activity is loaded, for example Options. So, now, how do you switch between activities and return back to the same. Or how do you transfer and carry user data between activities. Today we answer these questions in our Android Series.

An Intent is a messaging object you can use to request an action from another app component. An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an android.app.Activity, broadcastIntent to send it to any interested BroadcastReceivercomponents, and android.content.Context.startService or android.content.Context.bindService to communicate with a background android.app.Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. So, to create a new Intent :


Intent in=new Intent(MainActivity.this,NextActivity.class);
startActivity(in);

The parameters passed to the Intent() are the application context and the component class that is to be used for the intent. To start this intent we use startActivity() which launches the new activity. Although this won’t work until you specify the accepted intent actions and its parent activity name in your Android Manifest file.


<activity
    android:name="com.shirish.Intent.NextActivity"
    android:label="@string/title_activity_next"
    android:parentActivityName="com.shirish.Intent.MainActivity" >
<meta-data
     android:name="android.support.PARENT_ACTIVITY"
     android:value="com.shirish.Intent.MainActivity" />

Screenshot_2015-01-02-17-32-34

Screenshot_2015-01-02-17-32-41

Now you can specify the startActivity(Intent) inside the onClick() to load the next activity on a button click. In this process the next problem you will face is passing the the user data from one activity to the next activity. Say for example it might be the user’s options or score or information. This can be achieved with the SharedPreferences.
It is an interface for accessing and modifying preference data returned by Context.getSharedPreferences. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.
Now first lets create a file to save the data,
SharedPreferences pref = getApplicationContext().getSharedPreferences(“Options”, MODE_PRIVATE);

Screenshot_2015-01-02-17-32-49

In the SharedPreferences we use the getSharedPreferences() to create a file to save the data in a specific mode. The getSharedPreferences() retrieves and hold the contents of the preferences file , returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other’s edits as soon as they are made. The available Operating modes are; 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. The bit MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.

To edit our Shared Preferences file, edit() is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and automatically commit those changes back to the SharedPreferences object. commit() is used to commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This automatically performs the requested modifications, replacing whatever is currently in the SharedPreferences. You can also use apply() if the return value is not your main concern as commit() returns true if your values were successfully committed. clear() is used to mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor. remove(String key) is used to Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit is called.
To insert the data in the file putInt(key,value), putFloat(key,value), putBoolean(key,value), putString(key,value) can be used for their repective datatypes. Similary getInt(key,value), getFloat(key,value), getBoolean(key,value), getString(key,value) can be used to retrieve the data from the file. But be carefull with your keys as the are the only identifiers for your data and obviously the should be unique. To retrieve the data in some other activity you need to re-declare the SharedPreferences object with the same filename and mode.

Screenshot_2015-01-02-17-32-57
Here I have made this example where user selects his gender and Android version from the Spinners and clicks the Button. On button click next activity is loaded where again with a button click user can view his Spinner selections.

//Main Activity
package com.shirish.Intent;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
    Button next;
    Spinner gender,android;
    Editor editor;
  @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     next=(Button) findViewById(R.id.next);
     setTitle("Intent 1");
     gender=(Spinner)findViewById(R.id.gender);
     android=(Spinner)findViewById(R.id.android);
     SharedPreferences pref = getApplicationContext().getSharedPreferences("Options", MODE_PRIVATE);
     editor=pref.edit();
     gender.setOnItemSelectedListener(new CustomOnItemSelectedListener());
     next.setOnClickListener(new OnClickListener(){
       public void onClick(View v){
         String gen=gender.getSelectedItem().toString();
         String and=android.getSelectedItem().toString();
         editor.putString("gender", gen);
         editor.putString("android", and);
         editor.commit();
         Toast.makeText(getApplicationContext(), "Settings saved!",Toast.LENGTH_LONG ).show();
         Intent in=new Intent(MainActivity.this,NextActivity.class);
         startActivity(in);
         }
    });
  }
}
//Next Activity
package com.shirish.Intent;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.SharedPreferences;
import android.os.Bundle;

public class NextActivity extends ActionBarActivity {
   Button show;
   TextView optiondisp;
   SharedPreferences pref;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_next);
    optiondisp=(TextView)findViewById(R.id.spindisplay);
    setTitle("Intent 2");
    show=(Button)findViewById(R.id.show);
    pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE);
    show.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          String gen=pref.getString("gender", "");
          String and=pref.getString("android", "");
          optiondisp.setText("Gender:"+gen+"\nAndroid:"+and);
          }
     });
 }
}

You may see that I have used here Spinner elements. It is a view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view. Read my Spinner tutorial to learn how Spinners are implemented.

Download The Source code here:
To Download Click Here!

Follow

Get every new post delivered to your Inbox.

Join 310 other followers