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!

Android : How to Read and Display User Input.

I have been doing Android programming for about a month now and I thought it would be cool to share this experience along with you. So, when I started Android Programming this is the first app example I started with. In here we simply ask the user to enter some data (Name, Email and Password). Then we display that data in a TextView when the user clicks the button. Now if you are totally new to Android and don’t know a thing about Android Programming then you should really check this post out Android Programming Basics .

Let’s get on with the XML (Android UI). For this app we use the LinearLayout (vertical). Then we “Drag n Drop” three EditText for text, email and password input. The we insert Button below them. To display these content insert a TextView below them. In Android it is very important how you place your UI elements in respect to other elements; their sizes and styles. Also keep in mind to put a vertical scrollbars so that your UI elements don’t fall out of the view. This can be done by using a ScrollView or ScrollBars. Also, keep the height and width of the text view to “warp_content” so that it adjusts according to the text.Android: How to Read and Display User Input

Now in our Android codding we declare our package com.shirish.hello .Then we import few necessary packages like app, os, view, widget. Now in our class we declare a Button, three EditText and a TextView. Try hiding most of your code if possible (access specifiers). In our onCreate method we will write most of our operational code. Its method called when the activity is starting. This is where most initialization goes; to inflate the activity’s UI, programmatically interacting with widgets in the UI, etc. Actually this activity has a Bundle parameter.If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Otherwise it is null.We are not gonna use it now to make things simpler.

package com.shirish.hello;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class MainActivity extends Activity {
  private Button b;
  EditText etname,etemail,etpassword;
  TextView tv;

 @Override
 protected void onCreate(Bundle savedInstanceState) { 
   super.onCreate(savedInstanceState); 
   setContentView(R.layout.activity_main);
   b=(Button)findViewById(R.id.click);
   tv=(TextView)findViewById(R.id.display);
   tv.setMovementMethod(new ScrollingMovementMethod())
 
   b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      etname=(EditText)findViewById(R.id.name);
      etemail=(EditText)findViewById(R.id.email);
      etpassword=(EditText)findViewById(R.id.password);
      tv.setText("Your Input: \n"+etname.getText().toString()+"\n"+etemail.getText().toString()+"\n"+etpassword.getText().toString()+"\nEnd.");
        }
     });
   }
}

We now set the content view for the activity from a layout resource and inflate it. Then we define our Button; find and assign its view. A click listener has to be set up on the button to listen the user’s click activity and trigger the action if clicked. In the method onClick which is called when the view is clicked we code the operations to be performed when the button is clicked. In this example we have to read user’s inputs and display the data. (Define the TextViews and EditTexts). To read the data from the user we use getText() method which returns the text in those EditTexts. To display them we need to convert them to String. Using the setText() method we can display the text in the TextView.

Now, try your app on a device see if it works fine. If you notice carefully when you rotate your device your whole activity and view is reloaded and your data is lost. To avoid this onSaveInstanceState(Bundle) is used but we will see that later. Try it with different UI and modifications. Download the source code below :

To Download Click Here!

Follow

Get every new post delivered to your Inbox.

Join 295 other followers