TUTORIAL ON CUSTOM LISTVIEW USING VOLLEY IN ANDROID STUDIO.

Agenda:-

1.      What is Volley Library?

2.     What is JSON?

3.     What is Custom ListView?

4.     Build Simple APP Using Volley Library, JSON, and Custom ListView.

So let’s start.

1: What is Volley?

  • Volley is a networking library developed by Google and introduced during Google I/O 2013 networking class capable of working without user interfering.
  • Until the release of Volley, the Apache and canonical Java class java.net.HttpURLConnection were the only available tools for the communication between a client with the backend.

Why Volley?

  • Avoid HttpUrlConnection and HttpClient.
  • Avoid AsyncTask, too.
  • It’s much faster.
  • Small Metadata operations.

Using Volley

  • Volley mostly works with just two classes, RequestQueue and Request. First, you have to create a RequestQueue, which manages worker threads and delivers the parsed results back to the main thread. You then pass it one or more Request objects.
  • When you create an object of Request class, it will take four parameters: the method type (GET, POST, etc.), the URL of the resource, and event listeners. Then, depending on the type of request, it may ask for some more variables.

Importing Volley

Download the Volley source from its repository. If you feel confident doing this, this Git command can do all the work for you:

https://android.googlesource.com/platform/frameworks/volley

There is another way as well; Add following line in the dependency of the build.gradle:

compile 'com.android.volley:volley:1.0.0'

2. Go to AndroidManifest.xml to Add Internet Access to Your App:

  • As we are fetching our JSON data from a URL, we need to have internet access permission in our application.
<uses-permission android:name=”android.permission.INTERNET”/>

3. Edit your MainActivity.xml file.

  • Go to Android/res/layout/MainActivity.xml. (My file name is activity_main.xml)
  • Add a relative layout and a list view, either drag and drop or by XML code
  • Below is the XML code. (Your code should look similar to this).
<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"
tools:context=".MainActivity"><ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:background="#ef2505"/>
</RelativeLayout>

4. Create Another XML File for Showing Data.

  • Now you need to add listview row XML file where we will show data.
  • Go to layout-> right click go to New-> add Layout Resource File-> name your XML file and click ok.
  • Add 4 TextViews and 1 NetworkImageView within RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="8dp"
    android:background="#cf7f7f"
    >

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed"
        />

    <TextView
        android:id="@+id/worth"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:fontFamily="sans-serif-condensed"

        />

    <TextView
        android:id="@+id/source"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/worth"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="15dp"
        android:textColor="#575294"
        android:fontFamily="sans-serif-condensed"

        />

    <TextView
        android:id="@+id/inYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:textSize="15dp"
        android:textColor="#f9f9f9"
        android:fontFamily="sans-serif-condensed"

        />

</RelativeLayout>

5.  Go to MainActivity.java file:

  • This class contains JsonArrayRequest with their attributes.
  • In this class, we are parsing data from URL.

Here, I am using above JSON’s link as example.

package volleylistview.com.volleylistview;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

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

import java.util.ArrayList;
import java.util.List;

/**
* Created by Ganesh Divekar on 11/07/2016.
*/

public class MainActivity extends Activity {

private static final String tag = MainActivity.class.getSimpleName();
private static final String url = "https://raw.githubusercontent.com/iCodersLab/Custom-ListView-Using-Volley/master/richman.json";
private List<DataSet> list = new ArrayList<DataSet>();
private ListView listView;
private Adapter adapter;

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

listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, list);
listView.setAdapter(adapter);


JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

for (int i = 0; i < response.length(); i++) {
try {

JSONObject obj = response.getJSONObject(i);
DataSet dataSet = new DataSet();
dataSet.setName(obj.getString("name"));
dataSet.setImage(obj.getString("image"));
dataSet.setWorth(obj.getString("worth"));
dataSet.setYear(obj.getInt("InYear"));
dataSet.setSource(obj.getString("source"));
list.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}

}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getPermission().addToRequestQueue(jsonreq);
}

}

Description of code:

  • We created an object of Adapter class which is used to add data on.
  • We have created the object of JsonObjectRequest and also passed the parameter in the JsonObjectRequest class.
  • Now I will tell you one by one how and why we passed each parameter.
  • The first parameter is URL from where we want to parse our data.
  • The second parameter is Listener. Here we have passed the Response. A listener which will override the method onResponse() and passed JSONObject as a parameter. onResponse()method take the response from the JSON data requested by a user.
  • Here we are using for loop to get the JSON Objects from JSON Array. This for loop works until all the JSON objects are parsed.
  • We are creating the object of JSONObject() class . This will get the each object from the JSON array continuously.
  • Here we created the object of DataSet class which is user built in class.
  • Here we are retrieving the data from JsonArray using JsonObject and passing it to a method which is basically in DataSet class.
  • The third and the last parameter is ErrorListener . The Response.ErrorListener which will override the method onErrorResponse() and gives the VolleyError variable for any Exception. onErrorResponse() method handle the error occurs due to volley library.
  • To send a request, add JsonRequest object to the requestQueuewith add().
  • Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.

 

6. Create DataSet.java file.

  • This class holds object after parsing to provide data to ListView.
package volleylistview.com.volleylistview;


/**
* Created by Ganesh Divekar on 11/07/2016.
*/

public class DataSet {

private String name, image;
private int year;
private String source;
private String worth;

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 int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public String getSource() {
return source;
}

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

public String getWorth() {
return worth;
}

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

Description of code:

“This class is straightforward to understand, so I am not going to describe this class because you already know about methods in java so let’s skip description and move on another part of App.”

 

7. Create Adapter.java file.

  •  This class contains adapter for our listview and will show our data.
  •  It is custom list adapter which renders each row of ListView, getView method is called for each row, which uses list_row.xml as view and fills it with the appropriate data.
package volleylistview.com.volleylistview;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;


/**
* Created by Ganesh Divekar on 11/07/2016.
*/

public class Adapter extends BaseAdapter {

private Activity activity;
private LayoutInflater inflater;
private List<DataSet> DataList;
ImageLoader imageLoader = Controller.getPermission().getImageLoader();

public Adapter(Activity activity, List<DataSet> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}

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

@Override
public Object getItem(int location) {
return DataList.get(location);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);

if (imageLoader == null)
imageLoader = Controller.getPermission().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView worth = (TextView) convertView.findViewById(R.id.worth);
TextView source = (TextView) convertView.findViewById(R.id.source);
TextView year = (TextView) convertView.findViewById(R.id.inYear);
DataSet m = DataList.get(position);
thumbNail.setImageUrl(m.getImage(), imageLoader);
name.setText(m.getName());
source.setText("Wealth Source: " + String.valueOf(m.getSource()));
worth.setText(String.valueOf(m.getWorth()));
year.setText(String.valueOf(m.getYear()));

return convertView;
}

}

  

Description of code:

  • In our GetView method, we are using ImageLoader’s object for checking if permission is granted or not.
  • We created an object of NetworkImageCiew which is basically Volley’s tool and TextView’s object, too.
  • Then we set all the data on different TextViews.

8.  Create Controller.java File.

  • This class controller our request and control our app.
package volleylistview.com.volleylistview;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;


/**
* Created by Ganesh Divekar on 11/07/2016.
*/

public class Controller extends Application {

public static final String TAG = Controller.class.getSimpleName();

private RequestQueue queue;
private ImageLoader ImageLoader;

private static Controller controller;

@Override
public void onCreate() {
super.onCreate();
controller = this;
}

public static synchronized Controller getPermission() {
return controller;
}

public RequestQueue getRequestQueue() {
if (queue == null) {
queue = Volley.newRequestQueue(getApplicationContext());
}

return queue;
}

public ImageLoader getImageLoader() {
getRequestQueue();
if (ImageLoader == null) {
ImageLoader = new ImageLoader(this.queue,
new BitmapCache());
}
return this.ImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
if (queue != null) {
queue.cancelAll(tag);
}
}

}

Description of code:

  • Here we created RequestQueue class object which is basically Volley’s main class ,I already gave the description of this class above.
  • Here we created ImageLoader class object which is basically Volley’s main class, I already gave the description of this class above.
  • Here we created Controller class instance.
  • We created method getRequestQueue() to get a request from the web server.

Finally.

9. Create BitmapCache.java File:

  • Now we are going to do the main coding for our application.
  • This file takes care of caching the image on disk.

v

package volleylistview.com.volleylistview;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader;


/**
 * Created by Ganesh Divekar on 11/07/2016.
 */

public class BitmapCache extends LruCache<String, Bitmap> implements
        ImageLoader.ImageCache {

    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public BitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public BitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}
Get Postion Using OnItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 Intent intent = new Intent(MainActivity.this,
 NewsDetailsActivity.class);
 DataSet data = new DataSet();
 System.out.println("aaaaa"+data.getWorth());
 DataSet m = list.get(position);

 System.out.println("YES"+m.getName());
 intent.putExtra("NewsBigHeading", m.getName());
 startActivity(intent);
 }
});


How to send Data from Next Activity getposition Data:
Bundle bundle = getIntent().getExtras();
String name =  bundle.getString("NewsBigHeading");

Creating and Publishing an Android Third Party Library

Our lives as Android developers would be a lot harder if not for all those third-party libraries out there that we love to include in our projects. In this tutorial, you will learn how to give back to the developer community by creating and publishing your own Android libraries, which people can effortlessly add and use in their projects.

If your library is going to be composed of only Java classes, packaging it as a JAR and distributing it using a file host is perhaps the quickest and easiest way to share it. If you were to create it from the console, the following command would suffice:

This tutorial however, shows you how to work with more complex libraries that contain not just Java classes, but also various types of XML files and resources. Such libraries are created as Android library modules and are usually packaged as AAR files.

Let’s create a simple Android library that offers a custom View to developers who use it.

To begin, add a new Android module to your project by selecting New > New Module from the File menu. You will be shown the following screen, which offers lots of choices:

New module dialog

Select Android Library and press Next. In the form that follows, enter a name for your library and press Next. I’ll be calling this library mylittlelibrary.

In the last screen, select Add no Activity and press Finish.

Your project will now have two modules, one for the app and one for the library. Here’s what its structure looks like:

Structure of project

Create a new layout XML by right-clicking on the res folder of your library module and selecting New > XML > Layout XML File. Name it my_view.xml.

To keep this tutorial simple, we’ll be creating a custom View that has two TextView widgets inside a LinearLayout. After adding some text to the TextView widgets, the layout XML file should look like this:

Create a new Java class and name it MyView.java. Make sure to put this file in the src directory of the library module–not the app module.

To make this class behave as a View, make it a subclass of the LinearLayout class. Android Studio will prompt you to add a few constructors to the class. After adding them, the new class should look like this:

As you can see, we now have two constructors. To avoid adding initialization code to each constructor, call a method named initialize from each constructor. Add the following code to each constructor:

In the initialize method, call inflate to associate the layout we created in the previous step with the class.

Now that the library is ready, let’s make use of it in the app module of the same project in order to make sure that there are no issues. To do so, add it as a compile dependency in the build.gradle file of the app module:

Create a new Java class, MainActivity, inside the app module. Make it a subclass of the Activity class and override its onCreate method.

Inside the onCreate method, create an instance of the custom view using its constructor. Pass it to the setContentView method so that it fills all the screen space of the Activity:

Your Activity is now ready. After adding it to the app manifest, build your project and deploy your app to an Android device. You should be able to see the custom view when the app starts.

Bintray is a popular platform you can use to publish Android libraries. It is free and easy to use.

Start by creating an account on Bintray. After signing in to your account, you will see that you already own six repositories. You can either use one of them or create a new repository. For this tutorial, I will be using the repository called maven, which is a Maven repository.

Homepage

Visit your profile page and click the Edit button. On the next page, click the API Key link to view your API key.

API Key

Make a note of the key, because you will be needing it to authenticate yourself when using the Bintray plugin.

To interact with Bintray in Android Studio, you should include the Bintray plugin in the dependencies of your project’s build.gradle file.

Because you will be uploading the library to a Maven repository, you should also add the Maven plugin as shown below.

Open the build.gradle file of your library module and add the following code to apply the plugins we added in the previous step.

The Bintray plugin will look for a POM file when it uploads the library. Even though the Maven plugin generates it for you, you should specify the value of the groupId tag and the value of the version tag yourself. To do so, use the group and version variables in your gradle file.

If you are familiar with Maven and you are wondering why we didn’t specify the value of the artifactId tag, it is because the Maven plugin will, by default, use the name of your library as the artifactId.

To conform to the Maven standards, your library should also have a JAR file containing the library’s source files. To generate the JAR file, create a new Jar task, generateSourcesJar, and specify the location of the source files using the from function.

It is also recommended that your library has a JAR file containing its Javadocs. Because you currently don’t have any Javadocs, create a new Javadoc task, generateJavadocs, to generate them. Use the sourcevariable to specify the location of the source files. You should also update the classpath variable so that the task can find classes that belong to the Android SDK. You can do this by adding the return value of the android.getBootClasspath method to it.

Next, to generate a JAR from the Javadocs, create a Jar task, generateJavadocsJar, and pass the destinationDir property of generateJavadocs to its from function. Your new task should look like this:

To make sure the generateJavadocsJar task only starts when the generateJavadocs task has completed, add the following code snippet, which uses the dependsOn method to order the tasks:

To include the source and Javadoc JAR files in the list of artifacts, which will be uploaded to the Maven repository, you should add the names of their tasks to a configuration called archives. To do so, use the following code snippet:

It is now time to run the tasks we created in the previous steps. Open the Gradle Projects window and search for a task named install.

Install task

Double-click it to run the tasks associated with the library module. Once it’s finished running, you will have everything you need to publish your library, a valid POM file, an AAR file, a sources JAR, and a Javadocs JAR.

To configure the plugin, you should use the bintray closure in your Gradle file. First, authenticate yourself using the user and key variables, corresponding to your Bintray username and API key respectively.

On Bintray, your library will reside inside a Bintray package. You should provide details about it using the intuitively named repo, name, licenses, and vcsUrl parameters of the pkg closure. If the package doesn’t exist, it will be created automatically for you.

When you upload files to Bintray, they will be associated with a version of the Bintray package. Therefore, pkg must contain a version closure whose name property is set to a unique name. Optionally, you can also provide a description, release date, and Git tag using the desc, released, and vcsTag parameters.

Finally, to specify the files that should be uploaded, set the value of the configuration parameter to archives.

This is a sample configuration:

Open the Gradle Projects window again and search for the bintrayUpload task. Double-click it to begin uploading the files.

Bintray upload

Once the task completes, open a browser to visit your Bintray package’s details page. You will see a notification that says that you have four unpublished files. To publish these files, click the Publish link.

Notification about unpublished files

Your library is now available as a Bintray package. Once you share the URL of your Maven repository, along with the group ID, artifact ID, and version number, any developer can access your library. For example, to use the library we created, developers would have to include the following code snippet:

Note that the developer has to explicitly include your repository in the list of repositories before adding the library as a compile dependency.

By default, Android Studio searches for libraries in a repository called JCenter. If you include your library in the JCenter repository, developers won’t have to add anything to their repositories list.

To add your library to JCenter, open a browser and visit your Bintray package’s details page. Click the button labeled Add to JCenter.

JCenter button

You will then be taken to a page that lets you compose a message. You can use the Comments field to optionally mention any details about the library.

Compose message page

Click the Send button to begin Bintray’s review process. Within a day or two, the folks at Bintray will link your library to the JCenter repository and you will be able to see the link to JCenter on your package’s details page.

Link to JCenter

Any developer can now use your library without changing the list of repositories.

In this tutorial, you learned how to create a simple Android library module and publish it to both your own Maven repository and to the JCenter repository. Along the way, you also learned how to create and execute different types of gradle tasks.

Picasso Android Tutorial – Android Picasso Image Loader Library

Adding Picasso Library to our Android Project.

After adding it just sync your project.

Loading Image from URL by Using Picasso Android Library

Loading image from URL by using Picasso Android Library is very simple and easy. The first thing we would need is an ImageView. Unlike Volley’s NetworkImageView with Picasso we can use normal ImageView.

Code for Loading Image with Picasso

It is very simple. We have to use the Picasso class.

Picasso.with(this)
   .load(“YOUR IMAGE URL HERE”)
   .into(imageView);

Loading Image from URL by Using Picasso Android Library

Loading image from URL by using Picasso Android Library is very simple and easy. The first thing we would need is an ImageView. Unlike Volley’s NetworkImageView with Picasso we can use normal ImageView.

Code for Loading Image with Picasso

It is very simple. We have to use the Picasso class

Placeholder and Error Handling

Because we are loading the image from internet; the process would take some time depending on the internet speed. So it would be a good idea to display a image from the device while the image from URL is getting loaded.

One more situation could be when the image is not downloaded from the URL (when the URL given is wrong). In this case we should display an error image. Both these things can be done very easily by using picasso. See the following code snippet.

Re-sizing and Rotating

We can also resize and rotate the image very easily.

Picasso.with(this)

Picasso.with(context)
        .load(itemsList.get(position).getStatus())
        .resize(40,40)                        // optional
        .into(drawerHolder.imgIcon);

Generate signed apk android studio

Step 1: Go to Build>Generate Signed APK>Next (module selected would be your module , most often called “app”)

Step 2:Click on create new

Step 3: Basically, fill in the form with the required details. The confusing bit it is where it asks for a Key Store Path. Click on the icon on the right with the 3 dots (“…”), which will open up a navigator window asking you to navigate and select a .jks file.Navigate to a folder where you want your keystore file saved and then at the File Name box at the bottom of that window, simply enter a name of your liking and the OK button will be clickable now. What is happening is that the window isnt really asking you chose a .jks file but rather it wants you to give it the location and name that you want it to have.

Step 4:Click on Next and then select Release and Voila ! you are done.

Android – Search ListView content using BaseAdapter

I am having a ListView and I have inserted values using BaseAdapter, but I realized that to search we have to use ArrayAdapter it working fine with the help of getfilter().but when i am going with BaseAdapter using getfilter() That Time Created Problem because getfilter()not supported in BaseAdapter You need to make custom getfilter().

1)Create EditTextView in XML file For Enter The Elements you want to Search.
<EditText android:id=”@+id/inputSearch”
android:layout_width=”fill_parent”
android:gravity=”center”
android:layout_height=”wrap_content”
android:hint=”Search User”/>

2)Bind This Id in JAVA file an Perform addTextChangedListener event.

inputSearch.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
mAdapter.getFilter().filter(cs);

}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub+
}

@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub

}
});
getfilter() are not supported in BaseAdapter.so you need to Custom create the getfilter method.

3)you need to implemented BaseAdapter using Filterable.it will create override methods.

@Override
public Filter getFilter() {
Filter filter = new Filter() {

@SuppressWarnings(“unchecked”)
//publishResults also override methods of getfilter
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {

listValues = (ArrayList<String>) results.values;
notifyDataSetChanged();
}

//performFiltering also override methods of getfilter
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String dataNames=””;
FilterResults results = new FilterResults();
//FilteredArrayNames is the temp listview for filter char
ArrayList<String> FilteredArrayNames = new ArrayList<String>();

listValues=listValues1;
// perform your search here using the searchConstraint String.

constraint = constraint.toString().toLowerCase();
//if(constraint.toString().trim().length()>0){
for (int i = 0; i < listValues1.size(); i++) {
//listValues1 is also second listvalues arrays
//listValues is first listValues arrays
dataNames = listValues1.get(i);
//getting listValues1 to dataNames which are we enter..

if (dataNames.toLowerCase().contains(constraint.toString().trim())) {
//add enter char to filter listview.
FilteredArrayNames.add(dataNames);

}

}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
return results;
}
};
return filter;
}
}

About the 64K limit & MultiDex Not Supporting.

Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term  denotes 1024 . Because 65,536 is equal to 64 X 1024, this limit is referred to as the ’64K reference limit’.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a singleclasses.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

Continue reading About the 64K limit & MultiDex Not Supporting.

In this article, i will present an OCR (Android Character Recognition) android demo application, that recognize words from a bitmap source.

In this article, i will present an OCR android demo application, that recognize words from a bitmap source.

There is an open source OCR library that supports android: Tesseract.

This demo project contains in addition other parts, like accessing the camera, handling bitmaps, making a camera focus box view, internal storage access etc.

OCR can be used in many purposes: reading text from images, scaning numbers or codes for specific services…

1.ADD Google Play Service First In Your Gradle.app file.

compile 'com.google.android.gms:play-services-vision:9.8.0'

2.ADD Permission For Camera To Scan our Take A Picture of Image An Convert That Image Into Text.

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Continue reading In this article, i will present an OCR (Android Character Recognition) android demo application, that recognize words from a bitmap source.

In this tutorial we learn how to implement QR Code Scanner & Generator using ZXing Scanner & Generator library in Android Application.

A.Add ZXING LiabaryFor Scanning an Generating QR Code. compile ‘com.google.zxing:core:3.2.1’ compile ‘com.journeyapps:zxing-android-embedded:3.2.0@aar’ B. Generate QR Code i…

Source: In this tutorial we learn how to implement QR Code Scanner & Generator using ZXing Scanner & Generator library in Android Application.

In this tutorial we learn how to implement QR Code Scanner & Generator using ZXing Scanner & Generator library in Android Application.

A.Add ZXING LiabaryFor Scanning an Generating QR Code.

compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'

B. Generate QR Code in Android

Step 1 : Select File -> New -> Project -> Android Application Project  create a new project .

 

Step 2 : Open res -> layout -> activity_generate.xml (or) activity_generate.xml and add following code :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_generate"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.example.spider.qrcode.GenerateActivity">

    <LinearLayout
    android:layout_width="match_parent"
    android:background="#ddd"
    android:layout_margin="35dp"
    android:orientation="vertical"
    android:layout_height="match_parent">
    
        <TextView
            android:text="QR Code Generator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:textSize="22dp"
            android:layout_gravity="center"
            android:id="@+id/textView"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:layout_marginTop="35dp"
        android:padding="10dp"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:hint="Enter The String"
            android:ems="10"
            android:id="@+id/generate_editText" />

        <Button
        android:text="Generate"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:textColor="#fff"
        android:background="@color/colorPrimary"
        android:id="@+id/button"
     />
    </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:gravity="center"
            android:layout_height="match_parent">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/imageView" />
        </LinearLayout>
</LinearLayout>
</LinearLayout>

Step 3 : Open src -> package -> Generate_Activity.java and add following code :

Continue reading In this tutorial we learn how to implement QR Code Scanner & Generator using ZXing Scanner & Generator library in Android Application.