Intent Service Example.

1.MainActivity.xml

<Button 
    android:id="@+id/btn_start_service"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Service"
    xmlns:android="http://schemas.android.com/apk/res/android" />

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting button click
        findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Creating an intent for sending to service
                Intent intent = new Intent(getApplicationContext(), MyIntentService.class);

                intent.putExtra("id", 101);
                intent.putExtra("msg", "hi");

                //starting service
                startService(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        //register broadcast receiver for the intent MyTaskStatus
        LocalBroadcastManager.getInstance(this).registerReceiver(MyReceiver, new IntentFilter("MyServiceStatus"));
    }


    //Defining broadcast receiver
    private BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String message = intent.getStringExtra("serviceMessage");

            Toast.makeText(MainActivity.this, "Received : " + message, Toast.LENGTH_SHORT).show();
        }
    };


    @Override
    protected void onStop()
    {
        super.onStop();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(MyReceiver);
    }

}

MyIntentService.java

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super(MyIntentService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {


        //retrieving data from the received intent
        int id = intent.getIntExtra("id",0);
        String message = intent.getStringExtra("msg");

        Log.i("Data  ", "id : "+id+" message : "+ message );
        //-----------------------------------------------


        //Do your long running task here


        //------------------------------------------------

        //Broadcasting some data
        Intent myIntent = new Intent("MyServiceStatus");
        myIntent.putExtra("serviceMessage", "Task done");

        // Send broadcast
        LocalBroadcastManager.getInstance(this).sendBroadcast(myIntent);

    }
}

 

Android Custom ListView with Image and Text using Volley With Swap.

1.Declare SwapListView In MainActivity.xml an Import Third Party Liabary.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.spider.listviewapplicationvolley.MainActivity">
    <com.baoyz.swipemenulistview.SwipeMenuListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

2.Import Third Party Liabary.

compile 'com.android.volley:volley:1.0.0'
compile "com.squareup.picasso:picasso:2.4.0"
compile 'com.baoyz.swipemenulistview:library:1.3.0'

i am Using 3 third party liabary in the project .

1)Volley use for Json Parsing.

2)Picasso for image.

3)SwipeListView Item.

3.Create ItemList.xml According json response.

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/image"
        android:text="Image"/>

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/worth"
        android:text="Worth"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/year"
        android:text="Year"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/source"
        android:text="Source"/>
    </LinearLayout>
</LinearLayout>

4.Create MainActivity with Json Parse add item to getter setter.

public class MainActivity extends AppCompatActivity {
    ArrayList<String> arrname = new ArrayList<>();
    ArrayList<String> arrimage = new ArrayList<>();
    ArrayList<String> arrworth = new ArrayList<>();
    ArrayList<String> arrinyear = new ArrayList<>();
    ArrayList<String> arrsource = new ArrayList<>();
  //  ListView listview;
    private Context context;
    private static final String MEMBER_URL ="https://raw.githubusercontent.com/iCodersLab/Custom-ListView-Using-Volley/master/richman.json";
    ArrayList<MemberList> listItems = new ArrayList<MemberList>();
    MemberAdapter memberAdapter;
    private SwipeMenuListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;

        listView=(SwipeMenuListView)findViewById(R.id.listview);

        try {
            StringRequest stringRequest = new StringRequest(Request.Method.GET, MEMBER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            getJsonResponse(response);
                            System.out.println("RESPONSE" + response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                        }
                    });

            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        }
        catch (Exception e)
        {

        }
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                /*SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                        0xCE)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("Open");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);*/

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(125));
                // set a icon
             //   deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };


// set creator
        listView.setMenuCreator(creator);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                Toast.makeText(context, "YES", Toast.LENGTH_SHORT).show();
                listItems.remove(position);
                memberAdapter.notifyDataSetChanged();
                return false;
            }

        });

        memberAdapter = new MemberAdapter(context,listItems);
        listView.setAdapter(memberAdapter);
        //memberAdapter.notifyDataSetChanged();
    }

    private void getJsonResponse(String response)
    {
        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i =0;i<jsonArray.length();i++)
            {
                String name = jsonArray.getJSONObject(i).getString("name").toString();
                  String image =jsonArray.getJSONObject(i).getString("image").toString();
                  String worth=jsonArray.getJSONObject(i).getString("worth").toString();
                  String InYear = jsonArray.getJSONObject(i).getString("InYear").toString();
                  String source = jsonArray.getJSONObject(i).getString("source").toString();
                  arrname.add(name);
                  arrimage.add(image);
                  arrinyear.add(InYear);
                  arrworth.add(worth);
                  arrsource.add(source);
                MemberList memberList = new MemberList();
                memberList.setName(name);
                memberList.setImage(image);
                memberList.setInyear(InYear);
                memberList.setSource(source);
                memberList.setWorth(worth);
                listItems.add(memberList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }
}


Create Model Class.

public class MemberList
{

    String name;
    String image;
    String worth;
    String inyear;
    String source;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getWorth() {
        return worth;
    }

    public void setWorth(String worth) {
        this.worth = worth;
    }

    public String getInyear() {
        return inyear;
    }

    public void setInyear(String inyear) {
        this.inyear = inyear;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }


}

Create Adapter.

public class MemberAdapter extends BaseAdapter
{

    ArrayList<MemberList> itemsList;
    Context context;
    DrawerItemHolder drawerHolder;

    public MemberAdapter(Context context,ArrayList<MemberList> itemsList) {
        this.itemsList = itemsList;
        this.context=context;
    }

    @Override
    public int getCount() {
        return itemsList.size();
    }

    @Override
    public Object getItem(int i) {
        return itemsList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        try {
            if (view == null) {
                LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                drawerHolder = new DrawerItemHolder();
                view = inflater.inflate(R.layout.row_list,
                        viewGroup, false);

                drawerHolder.name = (TextView) view.findViewById(R.id.name);
                drawerHolder.worth = (TextView) view.findViewById(R.id.worth);
                drawerHolder.imgIcon = (ImageView) view.findViewById(R.id.image);
                drawerHolder.inyear = (TextView) view.findViewById(R.id.year);
                drawerHolder.source = (TextView) view.findViewById(R.id.source);


                drawerHolder.name.setText(itemsList.get(i).getName());
                drawerHolder.source.setText(itemsList.get(i).getSource());
                drawerHolder.worth.setText(itemsList.get(i).getWorth());
                drawerHolder.inyear.setText(itemsList.get(i).getInyear());
                Picasso.with(context)
                        .load(itemsList.get(i).getImage())
                        .resize(40, 40)                        // optional
                        .into(drawerHolder.imgIcon);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return view;
    }

    private class DrawerItemHolder
    {
        TextView name;
        TextView source;
        TextView inyear;
        TextView worth;
        ImageView imgIcon;

    }
}

An Last Run The Code.

How to Send Data By Using Interface In Android

1.First Create Interface an Always remember that Interface is Always public.

public interface MyInterface
{
    public void value(String abc);
}


2.then use that interface where you want to use.


String nameValues="Ganesh Divekar";
MyInterface myInterface = (MyInterface)context;
myInterface .value(nameValues);

 

3.then we need to implement we created Interface where you want to needed.

implements MyInterface;

@Override
public void value(String abc) {
    NameValue.setText(abc);
}