Android ListView Tutorial — February 1, 2016

Android ListView Tutorial

Hey friends, in this post we will make an app using ListView .

When the app starts, a list displays the names of different animals. And whenever the name of the animal is clicked, its image is displayed in another activity.

1.Add Images in the res/drawable folder

You can download the images from google or by this link.

1

2. Create a Class  to store the names and images on Animals

We will add a new class named as Animals where all the information (names and image id of animals) would be stored.

This class is created to separate the information from the activities. Objects of this class would be used in the Activities. 

Let’s say the name of this class in Animals.java.

In this Activity, we will create two variable as Name and imageResourceId.

Make constructor of Animals class

Set getters

Remember to create the toString method as it will be used by the ArrayAdapter in the MainActivity to display the Name variable of the animal object.

The code of the Animals.java class is :-

package com.abhi.listview.listviewtutorial;

/**
 * Created by abhi on 2/1/2016.
 */
public class Animals {

    private String Name;
    private int imageResourceID;        //for image

    //constructor
    private Animals(String Name,int imageResourceID)
    {
        this.Name=Name;
        this.imageResourceID=imageResourceID;
    }

    //getters

    public String getName()
    {
        return Name;
    }

    public String toString()
    {
        return Name;
    }

    public int getImageResourceID()
    {
        return imageResourceID;
    }

    // creating objects of the class

    public static final Animals[] animals= {new Animals("Dog",R.drawable.dog),
                                             new Animals("Cat",R.drawable.cat),
                                            new Animals("Cow",R.drawable.cow)};




}

 

3. Create textView and ListView in the content_main.xml

The content_main.xml code would be as follows. Make sure to ID the ListView as it would be recalled in the MainActivity.java

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.abhi.listview.listviewtutorial.MainActivity"
    tools:showIn="@layout/activity_main">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Animals"
        android:id="@+id/textView"
        android:textSize="@android:dimen/app_icon_size"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

 

4. Add the code in the MainActivity.java to display the listview

To display the Animal’s name in the listview, add the following code to the  Main Activity.java

ArrayAdapter is used here as it is used to bind the arrays to the views. It acts like a bridge between them. It can be used with any subclass of the AdapterView , can be ListView or Spinner.

Animals is the java class we created in the beginning and animals is its object.

Make sure to use setAdapter as it is used to attach the ArrayAdapter to the listView.

 

ListView lv= (ListView) findViewById(R.id.listView);

        ArrayAdapter<Animals> animalsArrayAdapter= new ArrayAdapter<Animals>(this, android.R.layout.simple_list_item_1,Animals.animals);
        lv.setAdapter(animalsArrayAdapter);

 

If you will Run you app now, you will see the name of the Animals displayed in a listview.

5. Adding Clicks in the App for the listview

To create any action on clicks for the listview, we need to use OnItemClickListener and its onItemClick method.

When the name of the animal i.e the item in the listview would be clicked, onItemClick would start an Intent for another activity. Let’s call that activity as SecondActivity.java .

Add the following code in the onCreate method in MainActivity.java to add clicks.

Here we are using putExtra method to send the value “id” which will tell us that which item was clicked. This value is being sent to the SecondActivity by the name “ImageID”

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i= new Intent(MainActivity.this,SecondActivity.class);
                i.putExtra("ImageId",id);
                startActivity(i);
            }
        });

 

6. Create SecondActivity.java

Now if you will play the app, on clicking any animal name in the listview. you will be directed to an to SecondActivity which will show nothing at the moment.

screenshot_2016-02-02-00-14-20

Now to add the Image to the Second Activity’s layout. We need to have  an ImageView in the content_second.xml.

Here is the code of content_second.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.abhi.listview.listviewtutorial.SecondActivity"
    tools:showIn="@layout/activity_second">


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"

        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

 

Add this code to the SecondActivity.java in the onCreate Method

Intent i=getIntent();
        int imageID= (int) i.getLongExtra("ImageId", 0);
        Animals animals= Animals.animals[imageID];

        ImageView imageView= (ImageView) findViewById(R.id.imageView);
        imageView.setImageResource(animals.getImageResourceID());

Here the “ImageId” is recovered back and used to get the Animal object from the array.

and then Image is shown in the imageView using setImageResource method.

Now run the app and you will see the desired output.

 

 

 DOWNLOAD COMPLETE PROJECT

Hope you like this tutorial and get a good understanding about ListView.

 

Advertisements
Remove Floating Action Button from the Blank Activity — January 31, 2016

Remove Floating Action Button from the Blank Activity

From the beginning of its days, Android has been changing a lot in its concepts.

In the recent time, one of the changes brought by the Material Design is the Floating Action Button. These can only be used with API 21 and above. But the appcompat support library v7 makes most of the Material Design supportable with the APIs before API 21.

1

In the Android Studio, whenever I opt for a Blank Activity, this Floating Action Button also displays in the layout.

The Floating Action button can be removed from the app, if one does not want to use it. After all, this widget is also a part of Layout only.

To remove this widget, Remove the following code from the activity_main.xml file.

 <android.support.design.widget.FloatingActionButton  
 android:id="@+id/fab"  
 android:layout_width="wrap_content"  
 android:layout_height="wrap_content"  
 android:layout_gravity="bottom|end"  
 android:layout_margin="@dimen/fab_margin"  
 android:src="@android:drawable/ic_dialog_email" />  

 

Also delete the unnecessary code from the MainActivity.java

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);  
 fab.setOnClickListener(new View.OnClickListener() {  
   @Override  
   public void onClick(View view) {  
     Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)  
         .setAction("Action", null).show();  
   }  
 });  

 

Now you are good to go without the Floating Action Button. 🙂



 

Control Arduino using Bluetooth with Android App — June 10, 2015

Control Arduino using Bluetooth with Android App

Hello friends, Today we are going to learn about the integration of Bluetooth HC – 06 module with the Arduino Uno. Bluetooth Module HC-06 operates in SLAVE module only. That means it cannot initiate the Bluetooth connection with any other Bluetooth Device. There are other Modules also which can be used.Other popular Bluetooth Module is HC-05 and it operates in both MASTER/SLAVE mode therefore it can initiate the connection when in MASTER mode. In this tutorial,we will use Android App BlueTerm+ to turn off and on the LED on Arduino Uno using Bluetooth Module HC06.

Steps

1.Download the circuit diagram and Arduino sketch from here .       NOTE:- If it is mentioned 3.3V on your module, then do not connect the 5V,instead connect the 3.3V from the Arduino.My module works fine with 5V. 2.The link of the Android app used is https://play.google.com/store/apps/details?id=de.jentsch.blueterm 3.Watch the video

So this is how we can control arduino using bluetooth.Hope you guys like it. Let me know in comments if you like the video or if you have any doubts.:)

Get current location coordinates and city name in Android Application — May 14, 2015

Get current location coordinates and city name in Android Application

Hello friends,

In this blog post I am going to write about how to get the location coordinates in an android app and how to get the city name using those coordinates.

I have tried this app already and its working good.Please enable your gps settings and mobile data before using this app.

Here is the code

MainActivity.Java

1:  package devicelocation.abhi.com.newgetuserlocation;  
2:    
3:  import android.content.Context;  
4:  import android.location.Address;  
5:  import android.location.Criteria;  
6:  import android.location.Geocoder;  
7:  import android.location.Location;  
8:  import android.location.LocationManager;  
9:  import android.support.v7.app.ActionBarActivity;  
10:  import android.os.Bundle;  
11:  import android.util.Log;  
12:  import android.view.Menu;  
13:  import android.view.MenuItem;  
14:  import android.view.View;  
15:  import android.widget.Button;  
16:  import android.widget.TextView;  
17:  import android.widget.Toast;  
18:    
19:  import java.io.IOException;  
20:  import java.util.List;  
21:  import java.util.Locale;  
22:    
23:    
24:  public class MainActivity extends ActionBarActivity {  
25:    
26:    
27:    String cityname;  
28:    
29:    TextView latTextView;  
30:    TextView longTextView;  
31:    TextView locTextView;  
32:    @Override  
33:    protected void onCreate(Bundle savedInstanceState) {  
34:      super.onCreate(savedInstanceState);  
35:      setContentView(R.layout.activity_main);  
36:      latTextView=(TextView)findViewById(R.id.LattextView);  
37:      longTextView=(TextView)findViewById(R.id.LongtextView);  
38:      locTextView=(TextView)findViewById(R.id.LocationtextView);  
39:    
40:    
41:      //TO get the location,manifest file is added with 2 permissions  
42:      //Location Manager is used to figure out which location provider needs to be used.  
43:      LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);  
44:    
45:    
46:      //Best location provider is decided by the criteria  
47:      Criteria criteria=new Criteria();  
48:      //location manager will take the best location from the criteria  
49:      locationManager.getBestProvider(criteria, true);  
50:    
51:      //nce you know the name of the LocationProvider, you can call getLastKnownPosition() to find out where you were recently.  
52:      Location location=locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria,true));  
53:    
54:      Geocoder gcd=new Geocoder(getBaseContext(), Locale.getDefault());  
55:      latTextView.setText(String.valueOf(location.getLatitude()));  
56:      longTextView.setText(String.valueOf(location.getLongitude()));  
57:      Log.d("Tag","1");  
58:      List<Address> addresses;  
59:    
60:        try {  
61:          addresses=gcd.getFromLocation(location.getLatitude(),location.getLongitude(),1);  
62:          if(addresses.size()>0)  
63:    
64:          {  
65:            //while(locTextView.getText().toString()=="Location") {  
66:              cityname = addresses.get(0).getLocality().toString();  
67:              locTextView.setText(cityname);  
68:            // }  
69:          }  
70:    
71:        } catch (IOException e) {  
72:          e.printStackTrace();  
73:    
74:        }  
75:    
76:    
77:      }  
78:    
79:    
80:    
81:    
82:    @Override  
83:    public boolean onCreateOptionsMenu(Menu menu) {  
84:      // Inflate the menu; this adds items to the action bar if it is present.  
85:      getMenuInflater().inflate(R.menu.menu_main, menu);  
86:      return true;  
87:    }  
88:    
89:    @Override  
90:    public boolean onOptionsItemSelected(MenuItem item) {  
91:      // Handle action bar item clicks here. The action bar will  
92:      // automatically handle clicks on the Home/Up button, so long  
93:      // as you specify a parent activity in AndroidManifest.xml.  
94:      int id = item.getItemId();  
95:    
96:      //noinspection SimplifiableIfStatement  
97:      if (id == R.id.action_settings) {  
98:        return true;  
99:      }  
100:    
101:      return super.onOptionsItemSelected(item);  
102:    }  
103:  }  
104:    

activity_main.xml

1:  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2:    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"  
3:    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"  
4:    android:paddingRight="@dimen/activity_horizontal_margin"  
5:    android:paddingTop="@dimen/activity_vertical_margin"  
6:    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"  
7:    android:orientation="vertical"  
8:    android:weightSum="1">  
9:    
10:    <TextView  
11:      android:layout_width="match_parent"  
12:      android:layout_height="wrap_content"  
13:      android:textAppearance="?android:attr/textAppearanceLarge"  
14:      android:text="Large Text"  
15:      android:id="@+id/LattextView"  
16:    
17:      android:padding="20dp"/>  
18:    
19:    <TextView  
20:      android:layout_width="wrap_content"  
21:      android:layout_height="wrap_content"  
22:      android:textAppearance="?android:attr/textAppearanceLarge"  
23:      android:text="Large Text"  
24:      android:id="@+id/LongtextView"  
25:      android:padding="20dp"/>  
26:    
27:    <TextView  
28:      android:padding="20dp"  
29:      android:layout_width="match_parent"  
30:      android:layout_height="wrap_content"  
31:      android:textAppearance="?android:attr/textAppearanceLarge"  
32:      android:text="Location"  
33:      android:id="@+id/LocationtextView"  
34:      android:layout_centerVertical="true"  
35:      android:layout_alignParentLeft="true"  
36:      android:layout_alignParentStart="true" />  
37:    
38:    
39:    
40:  </LinearLayout>  
41:    

AndroidManifest.xml 

1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
3:    package="devicelocation.abhi.com.newgetuserlocation" >  
4:    
5:    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  
6:    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
7:    <application  
8:      android:allowBackup="true"  
9:      android:icon="@mipmap/ic_launcher"  
10:      android:label="@string/app_name"  
11:      android:theme="@style/AppTheme" >  
12:      <activity  
13:        android:name=".MainActivity"  
14:        android:label="@string/app_name" >  
15:        <intent-filter>  
16:          <action android:name="android.intent.action.MAIN" />  
17:    
18:          <category android:name="android.intent.category.LAUNCHER" />  
19:        </intent-filter>  
20:      </activity>  
21:    </application>  
22:    
23:  </manifest>  
24:    

You can also download the full source code here.

https://drive.google.com/file/d/0B2Y9-jpvsfOBYzRrdTNFSEpZbjA/view?usp=sharing

Cheers!

Please comment if you have any thoughts or any query related to the post.