Advanced Android - Holder View



A way around repeated use of findViewById() is to use the "view holder" design pattern. A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly.

Example

This example demostrate about how to integrate Android Snackbar.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<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 = "@dimen/activity_vertical_margin"
   android:paddingLeft = "@dimen/activity_horizontal_margin"
   android:paddingRight = "@dimen/activity_horizontal_margin"
   android:paddingTop = "@dimen/activity_vertical_margin">
   <ListView
      android:id = "@+id/list_view"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:scrollbars = "none" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

package myapplication.example.com.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
   private ListView listView;
   private ArrayList<String> strings;
   private ArrayAdapter<String> adapter;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      listView = (ListView)findViewById(R.id.list_view);
      strings = new ArrayList<>();
      
      for (int i = 0; i < 5; i++) {
         strings.add("");
      } 
      adapter = new ListViewAdapter(this, R.layout.item_listview, strings, false);
      listView.setAdapter(adapter);
   } 
   
   private void loadJSONDataFromURL() {
      final Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
         @Override
         public void run() {
            new GetJSONTask(MainActivity.this).execute();
         } 
      }, 1000);
      Log.i("Main", "load data");
   }
   
   //parsing json after getting from Internet
   public void parseJsonResponse(String result) {
      strings.clear();
      try {
         JSONObject json = new JSONObject(result);
         JSONArray jArray = new JSONArray(json.getString("message"));
         for (int i = 0; i < jArray.length(); i++) {
            JSONObject jObject = jArray.getJSONObject(i);
            strings.add(jObject.getString("name"));
         } 
         adapter.notifyDataSetChanged();
         Log.i("Main", "finish load data");
      } catch (JSONException e) {
         e.printStackTrace();
      }
   } 
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   } 
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      if (item.getItemId() == R.id.load) {
         adapter = new ListViewAdapter(this, R.layout.item_listview, strings, true);
         listView.setAdapter(adapter);
         loadJSONDataFromURL();
      } 
      return super.onOptionsItemSelected(item);
   }
}

Step 4 − Add the following code to src/ListViewAdapter.java

package myapplication.example.com.myapplication;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class ListViewAdapter extends ArrayAdapter<String> {
   private Activity activity;
   private boolean isLoadImage;
   private final static String IMAGE_URL = "
      https://www.tutorialspoint.com/green/images/logo.png";
   
   public ListViewAdapter(Activity context, int resource, 
      ArrayList<String> objects, boolean isLoadImage) {
         
      super(context, resource, objects);
      this.activity = context;
      this.isLoadImage = isLoadImage;
   } 
   
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      LayoutInflater inflater = (LayoutInflater) 
         activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
         
      // If holder not exist then locate all view from UI file.
      if (convertView == null) {
         // inflate UI from XML file
         convertView = inflater.inflate(R.layout.item_listview, parent, false);
         
         // get all UI view
         holder = new ViewHolder(convertView);
         
         // set tag for holder
         convertView.setTag(holder);
      }  else {
         // if holder created, get tag from view
         holder = (ViewHolder) convertView.getTag();
      } 
      if (!getItem(position).equals("")) {
         holder.countryName.setText(getItem(position));
      } 
      if (isLoadImage) {
         Picasso.with(activity).load(IMAGE_URL).into(holder.imageView);
      } 
      return convertView;
   } 
   
   private class ViewHolder{
      private ImageView imageView;
      private TextView countryName;
      
      public ViewHolder (View view) {
         imageView = (ImageView)view.findViewById(R.id.image_view);
         countryName = (TextView)view.findViewById(R.id.text_view);
      }
   }
}

Step 5 − Add the following code to res/layout/item_listview.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content"
   android:orientation = "horizontal"
   android:paddingBottom = "@dimen/activity_horizontal_margin">
   <com.elyeproj.loaderviewlibrary.LoaderImageView
      android:id = "@+id/image_view"
      android:layout_width = "100dp"
      android:layout_height = "100dp"
      android:layout_centerVertical = "true" />
   <com.elyeproj.loaderviewlibrary.LoaderTextView
      android:id = "@+id/text_view"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_centerInParent = "true"
      android:layout_marginLeft = "@dimen/activity_horizontal_margin"
      android:layout_toRightOf = "@id/image_view"
      android:gravity = "left"
      android:maxHeight = "120dp" />
</RelativeLayout>

Step 6 − Add the following code to src/ListViewAdapter.java

package myapplication.example.com.myapplication;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetJSONTask extends AsyncTask<Void, Void, String> {
   private HttpURLConnection urlConnection;
   private final String JSON_URL = "https://gist.githubusercontent.com/DevExchanges/57430306b4a060eee19a4d845b07a478/raw/e8c05e8ed7e83e7cc3d00d840cca0558c125330d/example.json";
   private MainActivity activity;
   public GetJSONTask(MainActivity activity) {
      this.activity = activity;
   } 
   
   @Override
   protected String doInBackground(Void... params) {
      Log.i("Async", "doInBackground");
      StringBuilder result = new StringBuilder();
      try {
         URL url = new URL(JSON_URL);
         urlConnection = (HttpURLConnection) url.openConnection();
         InputStream in = new BufferedInputStream(urlConnection.getInputStream());
         
         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
         String line;
         while ((line = reader.readLine()) != null) {
            result.append(line);
         } 
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         urlConnection.disconnect();
      } 
      return result.toString();
   } 
   
   @Override
   protected void onPostExecute(String result) {
      Log.i("Async", "onPostExecute");
      activity.parseJsonResponse(result);
   }
}

Step 7 − Add the following code to manifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package = "myapplication.example.com.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      
   </application>
</manifest>

Step 8 − Add the following code to build.gradle

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:24.2.1'
   compile 'com.elyeproj.libraries:loaderviewlibrary:1.0.3'
   compile 'com.squareup.picasso:picasso:2.5.2'
}

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Holder
Advertisements