Preparing Your In-app Billing Application in Android Studio.

Before you can start using the In-app Billing service, you’ll need to add the library that contains the In-app Billing Version 3 API to your Android project. You also need to setting the permissions for your application to communicate with Google Play. In addition, you’ll need to establish a connection between your application and Google Play. You should also verify that the In-app Billing API version that you are using in your application is supported by Google Play.

Download the Sample Application

In this training class, you will use a reference implementation for the In-app Billing Version 3 API called the TrivialDrive sample application. The sample includes convenience classes to quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app Billing requests from the main thread of your application.

To download the sample application:

  1. Open the Android SDK Manager.
  2. In the SDK Manager, expand the Extras section.
  3. Select Google Play Billing Library. Make sure to select the download for In-app Billing Version 3 or above.
  4. Click Install to complete the download.

The sample files will be installed to /your/sdk/location/extras/google/play_billing/in-app-billing-v03.

Add Your Application to the Developer Console

The Google Play Developer Console is where you publish your In-app Billing application and manage the various digital goods that are available for purchase from your application. When you create a new application entry in the Developer Console, it automatically generates a public license key for your application. You will need this key to establish a trusted connection from your application to the Google Play servers. You only need to generate this key once per application, and don’t need to repeat these steps when you update the APK file for your application.

To add your application to the Developer Console:

  1. Go to the Google Play Developer Console site and log in. You will need to register for a new developer account, if you have not registered previously. To sell in-app items, you also need to have a Google Checkout Merchantaccount.
  2. Click on Try the new design to access the preview version of the Developer Console, if you are not already logged on to that version.
  3. In the All Applications tab, add a new application entry.
    1. Click Add new application.
    2. Enter a name for your new In-app Billing application.
    3. Click Prepare Store Listing.
  4. In the Services & APIs tab, find and make a note of the public license key that Google Play generated for your application. This is a Base64 string that you will need to include in your application code later.

Your application should now appear in the list of applications in Developer Console.

Add the In-app Billing Library

To use the In-app Billing Version 3 features, you must add the IInAppBillingService.aidl file to your Android project. This Android Interface Definition Language (AIDL) file defines the interface to the Google Play service.

You can find the IInAppBillingService.aidl file in the provided sample app. Depending on whether you are creating a new application or modifying an existing application, follow the instructions below to add the In-app Billing Library to your project.

New Project

To add the In-app Billing Version 3 library to your new In-app Billing project:

  1. Copy the TrivialDrive sample files into your Android project.
  2. Modify the package name in the files you copied to use the package name for your project. In Eclipse, you can use this shortcut: right-click the package name, then select Refactor > Rename.
  3. Open the AndroidManifest.xml file and update the package attribute value to use the package name for your project.
  4. Fix import statements as needed so that your project compiles correctly. In Eclipse, you can use this shortcut: press Ctrl+Shift+O in each file showing errors.
  5. Modify the sample to create your own application. Remember to copy the Base64 public license key for your application from the Developer Console over to your MainActivity.java.

Existing Project

To add the In-app Billing Version 3 library to your existing In-app Billing project:

  1. Copy the IInAppBillingService.aidl file to your Android project.
    • If you are using Eclipse: Import the IInAppBillingService.aidl file into your /src directory.
    • If you are developing in a non-Eclipse environment: Create the following directory /src/com/android/vending/billing and copy the IInAppBillingService.aidl file into this directory.
  2. Build your application. You should see a generated file named IInAppBillingService.java in the /gendirectory of your project.
  3. Add the helper classes from the /util directory of the TrivialDrive sample to your project. Remember to change the package name declarations in those files accordingly so that your project compiles correctly.

Your project should now contain the In-app Billing Version 3 library.

Set the Billing Permission


Your app needs to have permission to communicate request and response messages to the Google Play’s billing service. To give your app the necessary permission, add this line in your AndroidManifest.xml manifest file:

<uses-permission android:name="com.android.vending.BILLING" />

Initiate a Connection with Google Play


You must bind your Activity to Google Play’s In-app Billing service to send In-app Billing requests to Google Play from your application. The convenience classes provided in the sample handles the binding to the In-app Billing service, so you don’t have to manage the network connection directly.

To set up synchronous communication with Google Play, create an IabHelper instance in your activity’s onCreate method. In the constructor, pass in the Context for the activity, along with a string containing the public license key that was generated earlier by the Google Play Developer Console.

Security Recommendation: It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file.

IabHelper mHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
   // ...
   String base64EncodedPublicKey;
   
   // compute your public key and store it in base64EncodedPublicKey
   mHelper = new IabHelper(this, base64EncodedPublicKey);
}

Next, perform the service binding by calling the startSetup method on the IabHelper instance that you created. Pass the method an OnIabSetupFinishedListener instance, which is called once the IabHelpercompletes the asynchronous setup operation. As part of the setup process, the IabHelper also checks if the In-app Billing Version 3 API is supported by Google Play. If the API version is not supported, or if an error occured while establishing the service binding, the listener is notified and passed an IabResult object with the error message.

mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
   public void onIabSetupFinished(IabResult result) {
      if (!result.isSuccess()) {
         // Oh noes, there was a problem.
         Log.d(TAG, "Problem setting up In-app Billing: " + result);
      }            
         // Hooray, IAB is fully set up!  
   }
});

If the setup completed successfully, you can now use the mHelper reference to communicate with the Google Play service. When your application is launched, it is a good practice to query Google Play to find out what in-app items are owned by a user. This is covered further in the Query Purchased Items section.

Important: Remember to unbind from the In-app Billing service when you are done with your activity. If you don’t unbind, the open service connection could cause your device’s performance to degrade. To unbind and free your system resources, call the IabHelper‘s dispose method when your Activity gets destroyed.

@Override
public void onDestroy() {
   if (mHelper != null) mHelper.dispose();
   mHelper = null;
}

Android — RecyclerView and Volley

Re usability of code is the need of the hour. RecyclerView that was introduced by google helps us populate data in custom lists.

Google’s card UI enforces recycler view. It is relatively simple once you get a hang of it.

Volley is an HTTP library that makes the process of fetching JSONs faster and with minimal or no memory leaks.

You can watch the video for a brief on Volley.

We add the following to the build.gradle file of the app

dependencies {
compile 'com.android.support:appcompat-v7:23.4.0'
compile "com.android.support:recyclerview-v7:23.0.1"
compile 'com.android.volley:volley:1.0.0'
}

Now in the res file of the main activity or the file you want to populate the recycler view add the following

<android.support.v7.widget.RecyclerView
    android:id="@+id/my_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

Then we create a model class for an object that can encompass the datas we get from json

Let’s say we need each card to display a picture and a text of a movie.

We create a model class called DoctorList.

public class DoctorList {

    String DoctorName;
    String Rating;
    String Qualification;
    String Experience;
    String Specialization;

    public String getDoctorName() {
        return DoctorName;
    }

    public void setDoctorName(String doctorName) {
        DoctorName = doctorName;
    }

    public String getRating() {
        return Rating;
    }

    public void setRating(String rating) {
        Rating = rating;
    }

    public String getQualification() {
        return Qualification;
    }

    public void setQualification(String qualification) {
        Qualification = qualification;
    }

    public String getExperience() {
        return Experience;
    }

    public void setExperience(String experience) {
        Experience = experience;
    }

    public String getSpecialization() {
        return Specialization;
    }

    public void setSpecialization(String specialization) {
        Specialization = specialization;
    }

}

In DoctorListViewAdapter.java  we add the following:-

public class DoctorListViewAdapter extends RecyclerView.Adapter<DoctorListViewAdapter.ViewHolder> {

    Context context;
    RecyclerViewItemClickInterface recyclerViewItemClickInterface;
    callnowInterface anInterface;
    List<DoctorList> doctorList;
    public DoctorListViewAdapter(List<DoctorList> doctorList, Context context)
    {
        super();
        this.doctorList=doctorList;
        this.context = context;
        recyclerViewItemClickInterface =(RecyclerViewItemClickInterface) context;
        anInterface =(callnowInterface)context;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctor_list, parent, false);
        ViewHolder viewHolder= new ViewHolder(v);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position)
    {
        DoctorList doctorList1 =  doctorList.get(position);

        holder.Doctorname.setText(doctorList1.getDoctorName());
        holder.Qulifications.setText(doctorList1.getQualification());
        holder.recyclerid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = doctorList.get(position).getDoctorName();
                String experince = doctorList.get(position).getExperience();
                String qualification = doctorList.get(position).getQualification();
                String rating = doctorList.get(position).getRating();
                String specialization = doctorList.get(position).getSpecialization();
                Intent intent = new Intent(context, DoctorProfileActivitty.class);
                intent.putExtra("name",name);
                intent.putExtra("experince",experince);
                intent.putExtra("qualification",qualification);
                intent.putExtra("rating",rating);
                intent.putExtra("specialization",specialization);
                context.startActivity(intent);
            }
        });
        holder.bookappntment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                String name = doctorList.get(position).getDoctorName();
                String experince = doctorList.get(position).getExperience();
                String qualification = doctorList.get(position).getQualification();
                String rating = doctorList.get(position).getRating();
                String specialization = doctorList.get(position).getSpecialization();
                Intent intent = new Intent(context, BookAppoimnetActivity.class);
                intent.putExtra("name",name);
                intent.putExtra("experince",experince);
                intent.putExtra("qualification",qualification);
                intent.putExtra("rating",rating);
                intent.putExtra("specialization",specialization);
                context.startActivity(intent);
                //recyclerViewItemClickInterface.itemClick(doctorList.get(position));
            }
        });
        holder.callnow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                anInterface.itemClickk(doctorList.get(position));
            }
        });

    }
    @Override
    public int getItemCount() {
        return doctorList.size();
    }
     class ViewHolder extends RecyclerView.ViewHolder
     {
         public LinearLayout recyclerid;
         public TextView Doctorname;
         public TextView Qulifications;
         public TextView experince;
         public TextView bookappntment;
         public TextView callnow;

         public ViewHolder(View itemView)
         {
             super(itemView);
             Doctorname = (TextView) itemView.findViewById(R.id.personName) ;
             Qulifications = (TextView) itemView.findViewById(R.id.qulification) ;
             bookappntment=(TextView)itemView.findViewById(R.id.bookappntment);
             callnow=(TextView)itemView.findViewById(R.id.call);
             recyclerid=(LinearLayout)itemView.findViewById(R.id.recyclerid);


             /*experince = (TextView) itemView.findViewById(R.id.textView6) ;
             Specialization = (TextView) itemView.findViewById(R.id.textView8) ;
             Rating = (TextView) itemView.findViewById(R.id.textView8) ;*/
         }
     }
}

 

rowlistview.xml:

<?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="wrap_content"
    android:id="@+id/recyclerid"
    android:background="@color/transparent2"
    android:gravity="center_vertical"
    android:orientation="vertical">

    <LinearLayout
        android:padding="4dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:weightSum="5">

        <LinearLayout
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imgPerson"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/usericon" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/personName"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/margin10"
                android:gravity="center_vertical"
                android:text="Person"
                android:textColor="@color/black"
                android:textSize="16dp"
                android:textStyle="normal" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/margin10"
                android:gravity="center_vertical"
                android:text="MBBS"
                android:id="@+id/qulification"
                android:layout_marginTop="3dp"
                android:textColor="@color/black"
                android:textSize="14dp"
                />
            <TextView
                android:id="@+id/userid"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/margin10"
                android:gravity="center_vertical"
                android:text="6 Year Exp."
                android:visibility="gone"
                android:textColor="@color/black"
                android:textSize="14dp"
                android:textStyle="normal" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
           android:layout_marginTop="17dp"
            >
            <!-- <CheckBox
                 android:id="@+id/cbSelectedItem"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_marginRight="@dimen/margin5"
                 android:button="@drawable/check_box"
                 android:focusable="false"
                 android:visibility="visible" />-->


            <ImageView
                android:visibility="gone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/margin10"
                android:gravity="center_horizontal"
                android:src="@drawable/ic_keyboard_arrow_right_black_24dp" />

        </LinearLayout>
    </LinearLayout>
    <View
        android:layout_width="fill_parent"
        android:layout_height="@dimen/margin0.5"
        android:layout_marginLeft="@dimen/margin10"

        android:layout_marginRight="@dimen/margin10"
        android:background="@color/white2"
        android:visibility="gone" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_height="wrap_content"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Call now"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:paddingTop="2dp"
            android:paddingBottom="2dp"
            android:layout_marginRight="23dp"
            android:textSize="14dp"
            android:textStyle="bold"

            android:background="@drawable/borderview"
            android:textColor="@color/heading_theme_light"
            android:id="@+id/call" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Book Appointment"
            android:textSize="14dp"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:paddingTop="2dp"
            android:paddingBottom="2dp"
            android:background="@drawable/borderview"
            android:id="@+id/bookappntment"
            android:textColor="@color/heading_theme_light"
            android:textStyle="bold"
             />

    </LinearLayout>
    <View
        android:layout_width="fill_parent"
        android:layout_height="4dp"
/>

</LinearLayout>

 

*)DoctorListActivity.java

public class DoctorListActivity extends Activity implements RecyclerViewItemClickInterface,callnowInterface {

    private static final String DoctorList_URL ="http://ada.tecboot.com/api/WebAPI/GetDoctor";
    RecyclerView recyclerView;
    RecyclerView.LayoutManager recyclerViewlayoutManager;
    RecyclerView.Adapter recyclerViewadapter;
    List<DoctorList> doctorList;
    private LinearLayout llBack;
    Context context;
     Dialog dialog;
    TextView txtAddPeople;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_list);
        try {
            llBack = (LinearLayout) findViewById(R.id.llBack);
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                    overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
                }
            });
            txtAddPeople=(TextView)findViewById(R.id.txtAddPeople);
            txtAddPeople.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Collections.sort(doctorList, new Comparator<DoctorList>() {
                        @Override
                        public int compare(DoctorList lhs, DoctorList rhs) {
                            // TODO Auto-generated method stub

                            String f1 = lhs.getDoctorName();
                            String f2 = rhs.getDoctorName();
                            recyclerViewadapter.notifyDataSetChanged();
                            return f1.compareTo(f2);



                        }
                    });

                }
            });
            dialog = new Dialog (this);
            doctorListApiCall();
            doctorList = new ArrayList<>();
            recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
            recyclerView.setHasFixedSize(true);

            recyclerViewlayoutManager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(recyclerViewlayoutManager);
            DividerItemDecoration divider = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
            divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.my_custom_divider));
            recyclerView.addItemDecoration(divider);
            recyclerViewadapter = new DoctorListViewAdapter(doctorList, this);
            recyclerView.setAdapter(recyclerViewadapter);
        }catch (Exception e)
        {

        }
    }
    @Override
    public void itemClick(Object object) {
        Intent intent = new Intent(DoctorListActivity.this,BookAppoimnetActivity.class);
        startActivity(intent);
    }

    @Override
    public void itemClickk(Object object) {
                showDeleteDialog();
    }

    private void showDeleteDialog()
    {
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.calldialog);

        TextView text = (TextView) dialog.findViewById(R.id.txtMsg);
        Button okButton = (Button) dialog.findViewById(R.id.btnOk);
        Button cancleButton = (Button) dialog.findViewById(R.id.btnCancel);
       // final EditText edittext_tv = (EditText) dialog.findViewById(R.id.editText);

        okButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    private void doctorListApiCall()
    {
        try {
            dialog.requestWindowFeature (Window.FEATURE_NO_TITLE);
            dialog.setContentView (R.layout.custom_progress_dialog_trans);
            dialog.getWindow ().setBackgroundDrawableResource (android.R.color.transparent);
            dialog.show ();
            StringRequest stringRequest = new StringRequest(Request.Method.POST, DoctorList_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response)
                        {
                            getJsonResponse(response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error)
                        {
                            Toast.makeText(DoctorListActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                        }
                    }) {
                @Override
                protected Map<String, String> getParams()
                {

                    Map<String, String> params = new HashMap<String, String>();
                    params.put("DisplayType", "Grid");
                    return params;
                }
            };

            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);


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

    }

    private void getJsonResponse(String response)
    {
        try {
            dialog.dismiss();
            JSONArray jsonArray = new JSONArray(response);
            for(int i = 0;i<jsonArray.length();i++)
            {
                DoctorList doctorList1 = new DoctorList();
                String strDoctorName = jsonArray.getJSONObject(i).getString("DoctorName");
                String strRating = jsonArray.getJSONObject(i).getString("Rating");
                String strSpecialization = jsonArray.getJSONObject(i).getString("Specialization");
                String strExperience = jsonArray.getJSONObject(i).getString("Experience");
                String  strQualification = jsonArray.getJSONObject(i).getString("Qualification");
                doctorList1.setDoctorName(strDoctorName);
                doctorList1.setRating(strRating);
                doctorList1.setExperience(strExperience);
                doctorList1.setSpecialization(strSpecialization);
                doctorList1.setQualification(strQualification);
                doctorList.add(doctorList1);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        recyclerViewadapter.notifyDataSetChanged();
    }
}

Interface:

1)
public interface callnowInterface {
    public void itemClickk(Object object);
}
2)
public interface RecyclerViewItemClickInterface {
    public void itemClick(Object object);
}

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

 

 


Getting started with Android and Kotlin.

Why Kotlin for Android Development?

 

Kotlin is a great fit for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions:

  • Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system.
  • Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. With Kotlin’s support for inline functions, code using lambdas often runs even faster than the same code written in Java.
  • Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application. This includes annotation processing, so databinding and Dagger work too.
  • Footprint: Kotlin has a very compact runtime library, which can be further reduced through the use of ProGuard. In a real Application, the Kotlin runtime adds only a few hundred methods and less than 100K to the size of the .apk file.
  • Compilation Time: Kotlin supports efficient incremental compilation, so while there’s some additional overhead for clean builds, Faster Than Java.
  • Learning Curve: For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter included in the Kotlin plugin helps with the first steps. Kotlin koans offer a guide through the key features of the language with a series of interactive exercises.
  • From Java To Kotlin

  • Java

    System.out.print("Ganesh Divekar");
    Kotlin
    print("Ganesh Divekar")
    

    Java

    String name = "Ganesh Divekar";
    

    Kotlin

    var name = "Ganesh Divekar"
    

    Java

    String otherName;
    otherName = null;

    Kotlin

    var otherName : String?
    otherName = null

    Java

    if(text != null){
      int length = text.length();
    }

    Kotlin

    text?.let {
        val length = text.length
    }

    Java

    String firstName = "Ganesh";
    String lastName = "Divekar";
    String message = "My name is: " + firstName + " " + lastName;

    Kotlin

    val firstName = "Ganesh"
    val lastName = "Divekar"
    val message = "My name is: $firstName $lastName"

    Java

    String text = "First Line\n" +
                  "Second Line\n" +
                  "Third Line";

    Kotlin

    val text = """
            |First Line
            |Second Line
            |Third Line
            """.trimMargin()

    Java

    String text = x > 5 ? "x > 5" : "x <= 5";

    Kotlin

    val text = if (x > 5)
                  "x > 5"
               else "x <= 5"

    Java

    if(object instanceof Car){
    }
    Car car = (Car) object;

    Kotlin

    if (object is Car) {
    }
    var car = object as Car

    Java

    if(object instanceof Car){
       Car car = (Car) object;
    }

    Kotlin

    if (object is Car) {
       var car = object // smart casting
    }

    Java

    if(score >= 0 && score <= 300 ){}

    Kotlin

    if (score in 0..300) { }

    Java

    int score = // some score;
    String grade;
    switch (score) {
    	case 10:
    	case 9:
    		grade = "Excellent";
    		break;
    	case 8:
    	case 7:
    	case 6:
    		grade = "Good";
    		break;
    	case 5:
    	case 4:
    		grade = "Ok";
    		break;
    	case 3:
    	case 2:
    	case 1:
    		grade = "Fail";
    		break;
    	default:
    	    grade = "Fail";				
    }

    Kotlin

    var score = // some score
    var grade = when (score) {
    	9, 10 -> "Excellent" 
    	in 6..8 -> "Good"
    	4, 5 -> "Ok"
    	in 1..3 -> "Fail"
    	else -> "Fail"
    }

    Java

    for (int i = 1; i <= 10 ; i++) { }
    
    for (int i = 1; i < 10 ; i++) { }
    
    for (int i = 10; i >= 0 ; i--) { }
    
    for (int i = 1; i <= 10 ; i+=2) { }
    
    for (int i = 10; i >= 0 ; i-=2) { }
    
    for (String item : collection) { }
    
    for (Map.Entry<String, String> entry: map.entrySet()) { }

    Kotlin

    for (i in 1..10) { }
    
    for (i in 1 until 10) { }
    
    for (i in 10 downTo 0) { }
    
    for (i in 1..10 step 2) {}
    
    for (i in 10 downTo 1 step 2) {}
    
    for (item in collection) {}
    
    for ((key, value) in map) {}

    Java

    final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);
    
    final Map<Integer, String> keyValue = new HashMap<Integer, String>();
    map.put(1, "Ganesh");
    map.put(2, "Divekar");
    map.put(3, "Insider");
    
    // Java 9
    final List<Integer> listOfNumber = List.of(1, 2, 3, 4);
    
    final Map<Integer, String> keyValue = Map.of(1, "Ganesh",
                                                 2, "Divekar",
                                                 3, "Insider");

    Kotlin

    val listOfNumber = listOf(1, 2, 3, 4)
    val keyValue = mapOf(1 to "Ganesh",
                         2 to "Divekar",
                         3 to "Insider")

    Java

    // Java 7 and below
    for (Car car : cars) {
      System.out.println(car.speed);
    }
    
    // Java 8+
    cars.forEach(car -> System.out.println(car.speed));
    
    // Java 7 and below
    for (Car car : cars) {
      if(car.speed > 100) {
        System.out.println(car.speed);
      }
    }
    
    // Java 8+
    cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

    Kotlin

    cars.forEach {
        println(it.speed)
    }
    
    cars.filter  { it.speed > 100 }
          .forEach { println(it.speed)}

    Java

    void doSomething() {
       // logic here
    }

    Kotlin

    fun doSomething() {
       // logic here
    }

    Java

    void doSomething(int... numbers) {
       // logic here
    }

    Kotlin

    fun doSomething(vararg numbers: Int) {
       // logic here
    }

    Java

    int getScore() {
       // logic here
       return score;
    }

    Kotlin

    fun getScore(): Int {
       // logic here
       return score
    }
    
    // as a single-expression function
    
    fun getScore(): Int = score

    Java

    int getScore(int value) {
        // logic here
        return 2 * value;
    }

    Kotlin

    fun getScore(value: Int): Int {
       // logic here
       return 2 * value
    }
    
    // as a single-expression function
    
    fun getScore(value: Int): Int = 2 * value

    Java

    public class Utils {
    
        private Utils() { 
          // This utility class is not publicly instantiable 
        }
        
        public static int getScore(int value) {
            return 2 * value;
        }
        
    }

    Kotlin

    class Utils private constructor() {
    
        companion object {
        
            fun getScore(value: Int): Int {
                return 2 * value
            }
            
        }
    }
    
    // other way is also there
    
    object Utils {
    
        fun getScore(value: Int): Int {
            return 2 * value
        }
    
    }

    Java

    public class Developer {
    
        private String name;
        private int age;
    
        public Developer(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Developer developer = (Developer) o;
    
            if (age != developer.age) return false;
            return name != null ? name.equals(developer.name) : developer.name == null;
    
        }
    
        @Override
        public int hashCode() {
            int result = name != null ? name.hashCode() : 0;
            result = 31 * result + age;
            return result;
        }
    
        @Override
        public String toString() {
            return "Developer{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    Kotlin

    data class Developer(var name: String, var age: Int)
    

    Java

    public class Utils {
    
        private Utils() { 
          // This utility class is not publicly instantiable 
        }
        
        public static int triple(int value) {
            return 3 * value;
        }
        
    }
    
    int result = Utils.triple(3);
    

    Kotlin

    fun Int.triple(): Int {
      return this * 3
    }
    
    var result = 3.triple()

    The very first thing you need to do is add Kotlin support to your Android Studio installation.

    Before we get started, make sure you’re running the most recent, stable version of Android Studio, as you’re more likely to encounter bugs with the Kotlin plugin on experimental versions of Android Studio. It’s also worth opening the SDK Manager and checking whether updates are available for any of the packages you’ve installed.

    Once you’re confident that your development environment is up to date, you’re ready to install the Kotlin plugin. Launch Android Studio and you should see the Welcome to Android Studio window—if this window doesn’t appear, then close Android Studio completely and relaunch it.

    Give the Configure icon a click, and then select Plugins from the subsequent dropdown.

    Open Android Studios Configure  Plugins menu

    Click the Install JetBrains plugins… button.

    Install the Kotlin for Android Studio plugin

    Select Kotlin from the menu, and then click the green Install button. You’ll need to restart your IDE before the Kotlin plugin becomes active, so either click the Restart Android Studio button that appears or restart your IDE manually.

    At this point, your IDE can understand and run Kotlin code, but you’ll still need to configure Kotlin every time you want to use it in a new project. Let’s create a new project and configure that project to use Kotlin now. Create a new project with the settings of your choice, but for the sake of simplicity, select Empty Activity when prompted.

    Thanks to the Kotlin plugin, configuring a project to use Kotlin couldn’t be simpler: just select Tools from the Android Studio toolbar, followed by Kotlin and Configure Kotlin in Project.

    Select Android Studios Tools  Kotlin  Configure Kotlin in Project option

    This opens a popup where you can choose to configure Kotlin for:

    • all modules
    • all modules containing Kotlin files
    • or a single, named module

    Since I’m only going to use Kotlin code in my project, I opted for All modules. You can also choose which version of Kotlin you want to use—typically, this will be the latest version.

    Alternatively, you can configure Kotlin by selecting Help from the Android Studio menu bar, followed by Find Action… In the Find Action bar, start typing Configure Kotlin in Project, and then select this option when it appears.

    The Configure Kotlin in Project option makes a number of tweaks to your project’s build.gradle files, so let’s take a closer look at how these files have changed. Open your project-level build.gradle file—it should look something like this:

  •  

    Now, let’s take a look at your module-level build.gradle file:

  •  

    Finally, sync your changes either by clicking Sync Now from the popup that appears or by clicking the Sync Project with Gradle Files icon in Android Studio’s toolbar.

    One feature of the Kotlin plugin that’s particularly useful for Kotlin newcomers is its ability to convert any Java source file to Kotlin, while maintaining full runtime compatibility.

    Being able to see exactly how any Java file would translate into Kotlin is ideal for helping you learn the language, but it can also come in useful throughout your Kotlin journey—if you’re ever struggling to work out how to write something in Kotlin, you can always write it in Java and then use this feature to convert that code into Kotlin.

    Let’s convert our project’s MainActivity file into a Kotlin source file. There are two ways of invoking the Kotlin plugin’s Convert Java File to Kotlin File action, so either:

    • Select your MainActivity file, and then select Code from Android Studio’s menu bar, followed by Convert Java File to Kotlin File.
    Convert your existing Java file into a Kotlin file by selecting Code  Convert Java File to Kotlin File
    • Or select Help from the Android Studio menu bar, followed by Find Action. In the subsequent popup, start typing Convert Java file to Kotlin file and then select this option when it appears. Note, you can also launch the Find Action popup with a keyboard shortcut: if you’re on a Mac, press the Command-Shift-A keys, and if you’re on Windows or Linux then press Control-Shift-A.

    Just be aware that, depending on the complexity of your code, the conversion may not always be 100% accurate, so you should always check your converted code for errors.

    Your newly-converted MainActivity should look something like this:

  •  

    You’ll also notice that the file’s extension has changed, transforming from MainActivity.java to MainActivity.kt.

    This may be a simple Activity, but these few lines illustrate some key characteristics of the Kotlin syntax. Since this is our first look at some actual Kotlin code, let’s pick this class apart line by line.

    In Kotlin, you declare classes using the keyword class, exactly like in Java. However, in Kotlin, classes (and methods) are public and final by default, so you can create a class simply by writing class MainActivity.

    When it comes to extending a class, you replace Java’s extends with a colon, and then attach the name of the parent class. So in the first line of our MainActivity.kt file, we’re creating a public, final class called MainActivity that extends AppCompatActivity:

  •  

    The Java equivalent would be:

  •  

    If you do want to override a class or method, then you’ll need to explicitly declare it as open or abstract.

    In Kotlin, functions are defined using the fun keyword, followed by the function name and the parameters in brackets. In Kotlin, the function’s name comes before its type:

  •  

    This is the opposite of Java, where type comes before name:

  •  

    Note that we’re not specifying that this method is final, as in Kotlin all methods are final by default.

    The rest of this Activity looks pretty similar to Java. However, these few lines do illustrate another key characteristic of Kotlin:

  •  

    In Kotlin you don’t need to finish your lines with semicolons, hence the absence of colons in the above snippet. You can add colons if you really want to, but your code will be cleaner and easier to read without them.

    Now that we’ve deciphered our MainActivity.kt file, let’s move it to its proper home. Since the Kotlin plugin went to the trouble of adding a src/main/kotlin declaration to our build.gradle file, let’s actually create this directory. This step isn’t mandatory, but keeping your Kotlin files in a dedicated directory will make for a much cleaner project.

    In Android Studio’s Project Explorer, Control-click your project’s Main directory and select New from the menu that appears, followed by Directory. Name this directory kotlin and then click OK.

    Create a dedicated Kotlin directory

    If you’re struggling to spot your project’s main directory, then open the little dropdown in the upper-left of the Project Explorer and select Project. You should now have no problems spotting that elusive src/main directory.

    Open Android Studios Project Explorer menu and select Project

    Once you’ve created a dedicated Kotlin directory, drag your MainActivity.kt file into it. Just be sure to retain your MainActivity.kt file’s existing package name so that your project still runs.

    Also, if you’re only going to use Kotlin in this project, then you may want to delete the Java directory, rather than cluttering up your project with empty and unnecessary directories.

    Since Kotlin compiles to bytecode, an application that’s written in Kotlin feels exactly the same as an application that’s written in Java, so try installing this app on your Android device or a compatible AVD—it should feel as if nothing has changed.

    If you continue working with Kotlin in your project, then sooner or later you’re going to need to start creating new Kotlin files rather than simply converting existing Java ones.

    To create a Kotlin file, Control-click your app/src/main/kotlin directory and select New > Kotlin Activity.

    Create a new Kotlin Activity by selecting your Kotlin directory and clicking New  Kotlin Activity

    Give your class a name and select class from the dropdown menu. Your new class should look something like this:

    At this point, your Activity is empty. To get to the point where you can start adding some real functionality, you’ll need to complete a few steps. Firstly, add the import statements you want to use. The only difference between import statements in Kotlin and import statements in Java is that you don’t need to finish each line with a semicolon. For example:

  •  

    You’ll then need to specify the class you’re extending, using the same format we saw in our MainActivity.kt file:

    Next, you need to override the Activity’s onCreate method:

    You can now add whatever functionality you want to this Activity (and in the next section, I’ll show you how to use Kotlin extensions to manipulate UI widgets, so this may be a good place to start), but one last bit of setup you need to complete is declaring your Kotlin Activity in your Manifest. This follows exactly the same formula as declaring a new Java Activity, for example:

  •  

    Now that we’ve mastered the basics, let’s take a closer look at what Kotlin is really capable of—starting with a feature that can really cut the amount of boilerplate code you need to write.

    In Android, every time you want to work with any View in an Activity, you need to use the findViewByIdmethod to obtain a reference to that View. This makes findViewById one of the most important, but also one of the most frustrating bits of code that you’ll find yourself writing over and over, and over again in your Android projects. The findViewById method is a huge source of potential bugs, and if you’re working with multiple UI elements in the same Activity, then all those findViewByIds can really clutter up your code, making it difficult to read.

    While there are a number of libraries, such as Butter Knife, that aim to remove the need for findViewByIds, these libraries still require you to annotate the fields for each View, which can lead to mistakes and still feels like a lot of effort that would be better invested in other areas of your project.

    The Kotlin Android Extensions plugin (which has recently been incorporated into the standard Kotlin plugin) promises to make findViewById a thing of the past, offering you the benefits of the aforementioned libraries without the drawback of having to write any additional code or ship an additional runtime.

    You can use Kotlin extensions to import View references into your source files. At this point the Kotlin plugin will create a set of “synthetic properties” that enable you to work with these views as though they were part of your activity—crucially, this means you no longer have to use findViewById to locate each Viewbefore you can work with it.

    To use extensions, you’ll need to enable the Kotlin Android Extensions plugin in each module, so open your module-level build.gradle file and add the following:

  •  

    Sync these changes by clicking the Sync Now popup.

    You can then import the references to a single View, using the following format:

  •  

    For example, if your acitivity_main.xml file contained a TextView with the ID textView1, then you’d import the reference to this view by adding the following to your Activity:

  •  

    You’d then be able to access textView1 within this activity using its ID alone—and without a findViewById in sight!

    Let’s take a look at extensions in action, by adding a TextView to our activity_main.xml file, importing it into our MainActivity.kt file, and using extensions to set the TextView’s text programmatically.

    Start by creating your TextView:

  •  

    You can then import the TextView into your MainActivity.kt, and set its text using its ID only:

  •  

    Note, if you want to work with multiple widgets from the same layout file, then you can import the entire contents of a layout file in one fell swoop, using the following formula:

    For example, if you wanted to import all the widgets from your activity_main.xml file, then you’d add the following to your Activity:

  •  

update ui from background service in android using Broadcast Receiver.

The first thing that needs to be done is to create a string called BROADCAST_ACTION, this is simply a string that identifies what kind of action is taking place. Most of the time, it’s common to use the package name with the kind of action added to the end, so we’ll do that here. The next step is to create a handler that will be used to broadcast our data every 5 seconds. It’s better to use a Timer instead of Handler.

In onCreate, I’ve created a Intent and passed the BROADCAST_ACTION to the constructor of the intent. Notice that the Intent was defined as a global variable above. The intent will be called repeatedly in the Timer below and there is no reason to create a new intent every 5 seconds, so I’ll create it once here.

MainActivity.Java

public class MainActivity extends AppCompatActivity {
    TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview=(TextView)findViewById(R.id.textview);
    }
    @Override
    protected void onStart() {
        super.onStart();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyService.MY_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
        //Start our own service
        Intent intent = new Intent(MainActivity.this,
                com.apps.broadcastrapp.MyService.class);
        startService(intent);
        super.onStart();
    }
    /*@Override
    protected void onStop() {
        // TODO Auto-generated method stub
        unregisterReceiver(myReceiver);
        super.onStop();
    }*/
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int datapassed = intent.getIntExtra("DATAPASSED", 0);
            String s = intent.getAction().toString();
            String s1 = intent.getStringExtra("DATAPASSED");
            textview.setText(s1);
            Toast.makeText(context,
                    "Triggered by Service!\n"
                            + "Data passed: " + String.valueOf(s1),
                    Toast.LENGTH_LONG).show();
        }
    };
}

MyService.java class

public class MyService extends Service {

    final static String MY_ACTION = "MY_ACTION";
    private static Context context;
    private Timer timer;
    public  String Data;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        MyThread myThread = new MyThread();
        myThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    public class MyThread extends Thread{

        @Override
        public void run() {
            // TODO Auto-generated method stub

            try {
                int delay = 1000; // delay for 1 sec.
                int period = 12 * 1000; // repeat every 120 sec.
                timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    public void run() {
                        Calendar c = Calendar.getInstance();
                        Data = String.valueOf((c.get(Calendar.MILLISECOND)));
                        Intent intent = new Intent();
                        intent.setAction(MY_ACTION);
                        intent.putExtra("DATAPASSED", Data);
                        sendBroadcast(intent);
                    }
                }, delay, period);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            stopSelf();
        }

    }

}

Android Upload Image using Android Upload Service Using Volley.

1.Create XML View it Contains 2 button upload & Choose an Image view to set 
  selected image to image view an after that upload button to upload on server.

 
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="15dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="15dp"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/image"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose"
        android:id="@+id/choose"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload"
        android:id="@+id/upload"/>

</LinearLayout>

How It Works?

Image to Base64 String

  • First convert the image into bitmap.
  • Then compress bitmap to ByteArrayOutputStream.
  • Convert ByteArrayOutputStream to byte array.
  • Finally convert byte array to base64 string.

Base64 String to Image

  • Convert the base64 string to byte array.
  • Now convert byte array to bitmap
  • 2)Java file for XML biniding.
  • public class MainActivity extends AppCompatActivity {
    
        Button choose,upload;
        ImageView image;
        int PICK_IMAGE_REQUEST = 111;
        String URL ="Your API";
        Bitmap bitmap;
        ProgressDialog progressDialog;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            choose=(Button)findViewById(R.id.choose);
            upload=(Button)findViewById(R.id.upload);
            image=(ImageView)findViewById(R.id.image);
            choose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_PICK);
                    startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
                }
            });
            upload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                sendImageToServer();
                }
            });
    
        }
    
        private void sendImageToServer()
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    
            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response)
                        {
                            getJsonResponse(response);
                            //  Toast.makeText(ReaderActivity.this, response, Toast.LENGTH_LONG).show();
                            System.out.println("RESPONSE"+response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error)
                        {
                            Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                        }
                    }) {
                @Override
                protected Map<String, String> getParams()
                {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Comment", "Report");
                    params.put("FileName",imageString);
                    params.put("FileType", "Profile");
                    params.put("ReportType","IncidentType");
                    params.put("SenderId","57");
                    return params;
                }
            };
    
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        }
    
        private void getJsonResponse(String response)
        {
            try {
                JSONArray jsonArray = new JSONArray(response);
                String resultCode = jsonArray.getJSONObject(0).getString("ResultCode");
                if(resultCode.equals("OK"))
                {
    
                    Toast.makeText(this, "Image Uploaded Successfully....!!!!", Toast.LENGTH_SHORT).show();
                }else
                {
                    Toast.makeText(this, "Please try Again.....!!!!", Toast.LENGTH_SHORT).show();
    
                }
    
    
            }
    
            catch (JSONException e)
            {
                e.printStackTrace();
            }
    
        }
    
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();
                try {
                    //getting image from gallery
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    //Setting image to ImageView
                    image.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

How to Prase Response According to the Key.

try {
    JSONArray jsonArray = new JSONArray(response);
    String resultCode = jsonArray.getJSONObject(0).getString("ResultCode");
    if(resultCode.equals("OK"))
    {
        Toast.makeText(this, "Attendance Marked Successfully", Toast.LENGTH_SHORT).show();
    }else if(resultCode.equals("Error"))
    {
        String strErrorMessage = jsonArray.getJSONObject(0).getString("Message");
        Toast.makeText(this, strErrorMessage, Toast.LENGTH_SHORT).show();

    }


}

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

Posting Data on server Using Volley Android This Tutorial let us know how to post data using volley. Here i will be calling a POST service which will accept parameters and returns a json result . This is method we will be using to add parameters which we want to send to server.

  try {

                        StringRequest stringRequest = new StringRequest(Request.Method.POST, Scan_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(QRScan_Activity.this, error.toString(), Toast.LENGTH_LONG).show();
                                    }
                                }) {
                            @Override
                            protected Map<String, String> getParams()
                            {

                                Map<String, String> params = new HashMap<String, String>();
                                params.put("UserID", strUserId);
                                params.put("UserQRCode", Data);
                                params.put("QRLAt",sessionManager.getCurrentLat());
                                params.put("QRLong",sessionManager.getCurrentLong());

                    return params;
                            }
                        };

                        RequestQueue requestQueue = Volley.newRequestQueue(this);
                        requestQueue.add(stringRequest);


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