Display data on ListView Using ArrayAdapter

14/04/2017   07:52:32 PM
Hello in this android article i will explain how to display data on ListView using ArrayAdapter.Android have inbuilt many classes and subclasses of adapters which useful to display data in ListView,GridView,Spinner.names of some common adapters are BaseAdapter,ArrayAdapter,CursorAdapter,SimpleCursorAdapter
 
What is ArrayAdapter?
It is inbuilt class in android.
It converts an ArrayList of objects into View items loaded into the ListView.
It is used in Listview,Gridview,Spinner.
 
1. Create a new project in android studio
 
2. Add code in activity_main.xml layout 
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>
</RelativeLayout>
 

 

3. Add code in MainActivity.java

package com.simplylearnprogramming.newlistviewarrayadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView lst;
    String[] months={"Janaury","Feb","March","April","May","June","July","August","September","Octomber","November","December"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lst= (ListView) findViewById(R.id.lstvw);
        ArrayAdapter<String> arrayadapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,months);
        lst.setAdapter(arrayadapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView tv= (TextView) view;
        Toast.makeText(MainActivity.this,tv.getText()+"  "+position,Toast.LENGTH_LONG).show();
    }
});
    }
}

 

OUTPUT 

display data on ListView Using ArrayAdapter


Output

                   

Support us by Sharing