Tuesday, January 20, 2015

MyBuddies103: ListView ArrayAdapter Add Update Notify Data Set Changed


.
MyBuddies103: ListView ArrayAdapter Add Update Notify Data Set Changed
We want to change the ListView content in two ways; add new item to the bottom of the list (when the user taps ADD BUDDY button) and change the existing item in the list (when the user taps the list item)
package com.example.MyBuddies;      
       
import android.app.Activity;      
import android.os.Bundle;      
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
       
public class MyBuddies extends Activity      
{      
    Button btnAddBuddy;
    ListView lvwBuddies;
    String[] strBuddies;
    ArrayAdapter adpBuddies;
   
    /** Called when the activity is fit created. */      
    @Override      
    public void onCreate(Bundle savedInstanceState)      
    {      
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.main);
        setBtnAddBuddy();
        setLvwBuddies();
    }      
    private void setBtnAddBuddy(){
        btnAddBuddy=(Button) findViewById(R.id.btn_addbuddy);
       
        //set onlicklistener for button
        btnAddBuddy.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                addBuddy();
            }
        });
       
    }
    private void setLvwBuddies(){
        lvwBuddies = (ListView) findViewById(R.id.lvw_buddies);
       
        //Add new values to array
        strBuddies =new String[] {"Superman","Spiderman","Batman","Ironman","Ultraman", "Pacman", "Roboman"};
       
        //Create ArrayList from strBuddies
        List<String> values = new ArrayList<String>(Arrays.asList(strBuddies));
       
        //Create Adapter to load ArrayList
        adpBuddies = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
       
        //Plug adpBuddies to lvwBuddies
        lvwBuddies.setAdapter(adpBuddies);
       
        //set onclick listener for listview
        lvwBuddies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editBuddy(position, ((TextView) view).getText().toString());
            }
        });
    }
    private void addBuddy(){
        //Toast.makeText(getApplicationContext(),"Add Buddy.",
        //  Toast.LENGTH_SHORT).show();        
        adpBuddies.add("New Buddies");
        adpBuddies.notifyDataSetChanged();
   
 }
    private void editBuddy(int position, String text){
        //Toast.makeText(getApplicationContext(),"Edit Buddy.\nPosition:"+position+"\nText:"+text+"\n",
        //  Toast.LENGTH_SHORT).show();        
        adpBuddies.clear();
       
        //Edit values in array
        for(int i = 0;i<strBuddies.length; i++) {
            if (i!=position) { adpBuddies.add(strBuddies[i]);}
            else {adpBuddies.add(text + " Edited");}
        }
        adpBuddies.notifyDataSetChanged();
    }
}        
OUTCOME.

DOWNLOAD


.

MyBuddies102: ListView ArrayAdapter and OnClick Listener


.
MyBuddies102: ListView ArrayAdapter and OnClick Listener
ListView must implement ArrayAdapter to get data from sources and convert them into view that are placed in a list.

0) Starting Up

1) Delete String Resources

File: res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string name="app_name">MyBuddies</string>  
         <string-array name="buddies_array">
        <item>Superman</item>
        <item>Spiderman</item>
        <item>Batman</item>
        <item>Ironman</item>
        <item>Ultraman</item>
        <item>Pacman</item>
        <item>Roboman</item>
    </string-array>
</resources>  
2) Add String Resources to Controller File (MyBuddies.java)
File: MyBuddies.java
package com.example.MyBuddies;      
       
import android.app.Activity;      
import android.os.Bundle;      
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
       
public class MyBuddies extends Activity      
{      
    Button btnAddBuddy;
    ListView lvwBuddies;
    String[] strBuddies;
    ArrayAdapter adpBuddies;
   
    /** Called when the activity is fit created. */      
    @Override      
    public void onCreate(Bundle savedInstanceState)      
    {      
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.main);
        setBtnAddBuddy();
        setLvwBuddies();
    }  
     
    private void setBtnAddBuddy(){
        btnAddBuddy=(Button) findViewById(R.id.btn_addbuddy);
       
        //set onlicklistener for button
        btnAddBuddy.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                addBuddy();
            }
        });
       
    }
    private void setLvwBuddies(){
        lvwBuddies = (ListView) findViewById(R.id.lvw_buddies);
       
        //Add new values to array
        strBuddies =new String[] {"Superman","Spiderman","Batman","Ironman","Ultraman", "Pacman", "Roboman"};
       
        //Create ArrayList from strBuddies
        List<String> values = new ArrayList<String>(Arrays.asList(strBuddies));
       
        //Create Adapter to load ArrayList
        adpBuddies = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
       
        //Plug adpBuddies to lvwBuddies
        lvwBuddies.setAdapter(adpBuddies);
       
        //set onclick listener for listview
        lvwBuddies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editBuddy(position, ((TextView) view).getText().toString());
            }
        });
    }
    private void addBuddy(){
        Toast.makeText(getApplicationContext(),"Add Buddy.",
                Toast.LENGTH_SHORT).show();        
    }
    private void editBuddy(int position, String text){
        Toast.makeText(getApplicationContext(),"Edit Buddy.\nPosition:"+position+"\nText:"+text+"\n",
                Toast.LENGTH_SHORT).show();        
    }
}        
OUTCOME.

DOWNLOAD


.

MyBuddies101: ListView String Resources


.
MyBuddies101: ListView String Resources
The Android project in this tutorial was written and compiled on the online platformwww.programmr.com 
The reader that follows this tutorial series does not have to install anything except a web browser (preferably Chrome) and registered to www.programmr.com .

1) Create New Android Project

Project Name: MyBuddies
New Project Created.

2) Set minSdk (Optional)

We do this just to get a more recent look of our apps
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.MyBuddies"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MyBuddies"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-sdk android:minSdkVersion="15" />
</manifest>

3) Set the ListView string resources

Add a string array resources under the name buddies_array
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string name="app_name">MyBuddies</string>  
         <string-array name="buddies_array">
        <item>Superman</item>
        <item>Spiderman</item>
        <item>Batman</item>
        <item>Ironman</item>
        <item>Ultraman</item>
        <item>Pacman</item>
        <item>Roboman</item>
    </string-array>
</resources>  

4) Edit Layout File (main.xml)

<?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"    
    >
<Button
    android:id="@+id/btn_addbuddy"
    android:layout_width="fill_parent"    
    android:layout_height="wrap_content"    
    android:text="Add Buddy"    
/>
<ListView    
    android:id="@+id/lvw_buddies"
    android:layout_width="fill_parent"    
    android:layout_height="wrap_content"    
    android:entries="@array/sports_array"
    />    
</LinearLayout>    
     
OUTCOME.
In this exercise, we do not have to edit the Controller File (MyBuddies.java) at all.
Android automatically loads the listview items from the string resources.

DOWNLOAD



.

Friday, January 16, 2015

109-Programmr: Android Camera


.
109-Programmr: Android Camera
Camera is one of the most important part of mobile apps. It allows the user to save personal profile photo or send attachment to accompany their text messages.

0) Starting Up

Continue from the previous tutorial, http://android-steps.blogspot.my/2015/01/108-programmr-android-storage-shared.html or download startup files here.

1) Adding OnClick Event and Responding Action

Edit the XML file (activity_settings.xml) to add onclick event to ImageView and assign it to setPhoto method.
Edit the Java file (Settings.java) to add setPhoto method.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:orientation="vertical"    
    android:layout_width="match_parent"    
    android:layout_height="match_parent"
    android:padding="16dp"
    >    
    <ImageView
        android:id="@+id/ivw_user"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="15dp"
        android:src="@drawable/smiley"
        android:layout_gravity="center_horizontal"
        android:onClick="setPhoto"
        />
    <EditText
        android:id="@+id/etx_user"
        android:layout_width="match_parent"    
        android:layout_height="wrap_content"
        android:hint="Name"
    />    
    <EditText
        android:id="@+id/etx_email"
        android:layout_width="match_parent"    
        android:layout_height="wrap_content"
        android:hint="Email"
    />        
    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"    
        android:layout_height="wrap_content"
        android:text="Save"
        android:onClick="saveSettings"
    />        
       
</LinearLayout>    
File: Settings.java
package com.example.MyAndroid;      
       
import android.app.Activity;      
import android.os.Bundle;      
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.content.SharedPreferences;
public class Settings extends Activity      
{      
    /** Called when the activity is first created. */      
    @Override      
    public void onCreate(Bundle savedInstanceState)      
    {      
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.activity_settings);
        loadSettings();
    }      
    public void saveSettings(View v){
        Toast.makeText(getApplicationContext(), "Saving Data...", Toast.LENGTH_LONG).show();
        SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        EditText etxUser=(EditText) findViewById(R.id.etx_user);
        EditText etxEmail=(EditText) findViewById(R.id.etx_email);
       editor.putString("name",etxUser.getText().toString());
       editor.putString("email",etxEmail.getText().toString());
       editor.commit();
       finish();
    }        
    private void loadSettings(){
        Toast.makeText(getApplicationContext(), "Loading Data...", Toast.LENGTH_LONG).show();
        SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
        EditText etxUser=(EditText) findViewById(R.id.etx_user);
        EditText etxEmail=(EditText) findViewById(R.id.etx_email);
        // If value for key not exist then
        // return second param value - In this case "..."
        etxUser.setText(preferences.getString("name", "..."));
        etxEmail.setText(preferences.getString("email", "..."));        
    }
    public void setPhoto(View v){
        Toast.makeText(getApplicationContext(), "Activating Camera...", Toast.LENGTH_LONG).show();        
    }
}  
OUTCOME.

2) Adding Intent and StartActivityForResult

We use Intent to activate the camera and StartActivityForResult method to obtain image from the camera.
Once the image is available, we assign the image to the ImageView object.
Update the AndroidManifest to allow the apps to use the Camera Hardware.
File: Settings.java
package com.example.MyAndroid;      
       
import android.app.Activity;      
import android.os.Bundle;      
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.content.SharedPreferences;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class Settings extends Activity      
{      
    private static final int IMAGE_CAPTURE = 1; //identifier for startActivityForResult
    /** Called when the activity is first created. */      
    @Override      
    public void onCreate(Bundle savedInstanceState)      
    {      
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.activity_settings);
        loadSettings();
    }      
    public void saveSettings(View v){
        Toast.makeText(getApplicationContext(), "Saving Data...", Toast.LENGTH_LONG).show();
        SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        EditText etxUser=(EditText) findViewById(R.id.etx_user);
        EditText etxEmail=(EditText) findViewById(R.id.etx_email);
       editor.putString("name",etxUser.getText().toString());
       editor.putString("email",etxEmail.getText().toString());
       editor.commit();
       finish();
    }        
    private void loadSettings(){
        Toast.makeText(getApplicationContext(), "Loading Data...", Toast.LENGTH_LONG).show();
        SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
        EditText etxUser=(EditText) findViewById(R.id.etx_user);
        EditText etxEmail=(EditText) findViewById(R.id.etx_email);
        // If value for key not exist then
        // return second param value - In this case "..."
        etxUser.setText(preferences.getString("name", "..."));
        etxEmail.setText(preferences.getString("email", "..."));        
    }
    public void setPhoto(View v){
        Toast.makeText(getApplicationContext(), "Activating Camera...", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, IMAGE_CAPTURE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       if (resultCode == Activity.RESULT_OK) {
           switch (requestCode) {
               case IMAGE_CAPTURE: this.imageFromCamera(resultCode, data);
                   break;
               default:
                   break; }
       }
   }
    private void imageFromCamera(int resultCode, Intent data) {
        ImageView ivwUser=(ImageView) findViewById(R.id.ivw_user);
        ivwUser.setImageBitmap((Bitmap) data.getExtras().get("data"));
    }
}  
File: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.MyAndroid"
      android:versionCode="1"
      android:versionName="1.0">
 <uses-permission android:name="android.permission.CAMERA" />
    <application android:label="MyAndroid" android:icon="@drawable/ic_launcher">
        <activity android:name="MyAndroid"
                  android:label="MyAndroid">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="About"
                  android:label="About">        
        </activity>
        <activity android:name="Settings"
                  android:label="Settings">        
        </activity>        
    </application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
OUTCOME.
We need to use a real device to test the camera.
Bear in mind that at this stage, the captured image is not saved to the apps memory. The next time you come to this page, the image reverts back to Smiley.
We need to add additional codes to the saveSettings and loadSettings method in order to keep the image in the apps memory.
Follow the intermediate tutorial to add Gallery and image storage to this app,
and

DOWNLOAD

FURTHER READING


.