Saturday, December 5, 2015

Android List View with List View Simple Adapter

Android List View with List View Simple Adapter 

Hi dear friend, today we try to create a List View on Android application for anyone who “Have No IDEA ” what is List View  here it is. yes down here..

The ListView


Now for the Code, lts we start from the XML.

The first part is the main Activity XML
__________________________________________________________________
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:fitsSystemWindows="true" tools:openDrawer="start">

    <include layout="@layout/app_bar_employee" android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView android:id="@+id/nav_view"
        android:layout_width="wrap_content" android:layout_height="match_parent"
        android:layout_gravity="start" android:fitsSystemWindows="true"   android:background="@drawable/nav_bar"
        app:headerLayout="@layout/nav_header_employee"  >

        <!--the List View-->
        <include layout="@layout/content_userlistview" />

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

__________________________________________________________________


File Layout/content_userlistview.xml

__________________________________________________________________
<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:paddingBottom="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="65dp"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list_v"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="@color/bluesky"
        android:dividerHeight="1dp"
        android:fadingEdge="horizontal"
        />

</RelativeLayout>


__________________________________________________________________
And the List Layout file Layout/listuser.xml for the layout component of the list

__________________________________________________________________
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingRight="15dp">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_horizontal">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:gravity="left"
            >
            <TextView
                android:id="@+id/Employeename"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14dp"
                android:textStyle="bold"
                android:text="name"
                />
            <TextView
                android:id="@+id/EmailAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="email"
                android:textSize="10dp"
                />


        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="right"
            android:layout_gravity="left">
            <TextView
                android:id="@+id/Sapcode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SAPID"
                />

            <TextView
                android:id="@+id/level"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="level"
                />

        </LinearLayout>
    </LinearLayout>

</LinearLayout>
__________________________________________________________________
Now for the review XML file layout we should have :

MainActivity.XML ;included--> Layout/content_userlistview.xml: add list with simple adapter --> Layout/listuser.xml 

And next, time for the code to populate the data to list view, this is it;

THE CODE
__________________________________________________________________
protected void onPostExecute(String json) {
            pDialog.dismiss();

            try {
                androids new JSONArray(json);
                for(int i = 0i < androids.length()i++) {
                    JSONObject c = androids.getJSONObject(i);

                    employee emp = new employee();
                    emp.setValue(c);
                    HashMap<StringString> map = new HashMap<StringString>();

                    map.put("tEmployeename"emp.getStrEmplName());
                    map.put("tSapcode""SAP :"+emp.getStrSAP_Code());
                    map.put("tlevel""level :"+Integer.toString(emp.getIntLevel()));
//                    map.put("tSectionName", emp.getStrSectionName());
                    map.put("tEmailAddress""e-mail :"+emp.getStrEmail_Address());
               //     TextView SectionName = (TextView)findViewById(R.id.SectionName);
                    oslist.add(map);
                }
                Collections.sort(oslistnew CustomComparator());
                //R.id.list_v  the id of ListView
                list=(ListView)findViewById(R.id.list_v);
                ListAdapter adapter = new SimpleAdapter(Employee.thisoslist,
                        //R.layout.listuser the layout file that contai the List component R.id.Employeename,R.id.Sapcode, R.id.level,R.id.EmailAddress
                        R.layout.listuser,
                        new String[] { "tEmployeename","tSapcode","tlevel","tEmailAddress" }new int[] {
                        R.id.Employeename,R.id.SapcodeR.id.level,R.id.EmailAddress});

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parentView view,
                                            int positionlong id) {
                        Toast.makeText(Employee.this"You Clicked at " oslist.get(+position).get("tEmployeename")Toast.LENGTH_SHORT).show();

                    }
                });


            catch (JSONException e) {
                e.printStackTrace();
            }

        }

__________________________________________________________________



For the explanation of THE CODE

In these example I use the code in onPostExecute procedure where this procedure is part of 

__________________________________________________________________
private class JSONParse extends AsyncTask<StringStringString> {

__________________________________________________________________
, yes a AsyncTask.. It’s ok I will give the whole Class after this .

I use JSON data as the source of data that we will populated to ListView,
Like you se in the code.

__________________________________________________________________ 
androids new JSONArray(json);
                for(int i = 0i < androids.length()i++) {
                    JSONObject c = androids.getJSONObject(i);

                    employee emp = new employee();
                    emp.setValue(c);
                    HashMap<StringString> map = new HashMap<StringString>();

                    map.put("tEmployeename"emp.getStrEmplName());
                    map.put("tSapcode""SAP :"+emp.getStrSAP_Code());
                    map.put("tlevel""level :"+Integer.toString(emp.getIntLevel()));
                    map.put("tEmailAddress""e-mail :"+emp.getStrEmail_Address());
                    oslist.add(map);
                }
I populated the json string data to JSONArray the created the list then put it to employee class (I know like a stupid why did I just put it directly to the list, yes you can do that).

Then I declare ListView like :

__________________________________________________________________
list=(ListView)findViewById(R.id.list_v);

__________________________________________________________________
Then create the ListAdapter with 

__________________________________________________________________
ListAdapter adapter = new SimpleAdapter(Employee.thisoslist,
                        R.layout.listuser,
                        new String[] { "tEmployeename","tSapcode","tlevel","tEmailAddress" }new int[] {
                        R.id.Employeename,R.id.SapcodeR.id.level,R.id.EmailAddress});

__________________________________________________________________
The R.layout.Listuser is the file List that will consume our list

Then 
__________________________________________________________________
String[] { "tEmployeename","tSapcode","tlevel","tEmailAddress" }new int[] {
                        R.id.Employeename,R.id.SapcodeR.id.level,R.id.EmailAddress}

__________________________________________________________________
This array of string is the mapping array for the list to mapped to the component id in the file R.id.Listuser so the program know where do have to map the value from the list.

Like my promises here the whole code:
__________________________________________________________________
package com.subhan.loginregister;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.subhan.core.JSONParser;
import com.subhan.core.Singleton;
import com.subhan.model.employee;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

public class Employee extends Activity
        implements NavigationView.OnNavigationItemSelectedListener {
    private static String url = Singleton.getInstance().getUrlws()+"/Section/120p";
    JSONArray androids null;
    ListView list;
    ArrayList<HashMap<StringString>> oslist new ArrayList<HashMap<StringString>>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        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();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                thisdrawertoolbarR.string.navigation_drawer_openR.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        new JSONParse().execute();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.employeemenu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
//        int id = item.getItemId();
//
//        if (id == R.id.nav_camara) {
//            // Handle the camera action
//        } else if (id == R.id.nav_gallery) {
//
//        } else if (id == R.id.nav_slideshow) {
//
//        } else if (id == R.id.nav_manage) {
//
//        } else if (id == R.id.nav_share) {
//
//        } else if (id == R.id.nav_send) {
//
//        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private class JSONParse extends AsyncTask<StringStringString> {
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog new ProgressDialog(Employee.this);
            pDialog.setMessage("Getting data from server...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {
            String a = JSONParser.getJSON(url);
            return a;
        }
        @Override

        protected void onPostExecute(String json) {
            pDialog.dismiss();

            try {
                androids new JSONArray(json);
                for(int i = 0i < androids.length()i++) {
                    JSONObject c = androids.getJSONObject(i);

                    employee emp = new employee();
                    emp.setValue(c);
                    HashMap<StringString> map = new HashMap<StringString>();

                    map.put("tEmployeename"emp.getStrEmplName());
                    map.put("tSapcode""SAP :"+emp.getStrSAP_Code());
                    map.put("tlevel""level :"+Integer.toString(emp.getIntLevel()));
//                    map.put("tSectionName", emp.getStrSectionName());
                    map.put("tEmailAddress""e-mail :"+emp.getStrEmail_Address());
               //     TextView SectionName = (TextView)findViewById(R.id.SectionName);
                    oslist.add(map);
                }
                Collections.sort(oslistnew CustomComparator());
                //R.id.list_v  the id of ListView
                list=(ListView)findViewById(R.id.list_v);
                ListAdapter adapter = new SimpleAdapter(Employee.thisoslist,
                        //R.layout.listuser the layout file that contai the List component R.id.Employeename,R.id.Sapcode, R.id.level,R.id.EmailAddress
                        R.layout.listuser,
                        new String[] { "tEmployeename","tSapcode","tlevel","tEmailAddress" }new int[] {
                        R.id.Employeename,R.id.SapcodeR.id.level,R.id.EmailAddress});

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parentView view,
                                            int positionlong id) {
                        Toast.makeText(Employee.this"You Clicked at " oslist.get(+position).get("tEmployeename")Toast.LENGTH_SHORT).show();

                    }
                });


            catch (JSONException e) {
                e.printStackTrace();
            }

        }
        public class CustomComparator implements Comparator< HashMap<StringString>> {
            @Override
            public int compare( HashMap<StringString> map1,  HashMap<StringString> map2) {
                return map1.get("tEmployeename").compareTo(map2.get("tEmployeename"));
            }
        }

    }



}


okay guys and lads, thank for read and have good trying, I hope it will help 

No comments:

Post a Comment