Implement search functionality with help of edittext, rxjava and retrofit 2 in android.

Implement search functionality with help of editext, rxjava and retrofit2 in android.
Search text view ,  edittext view , rxjava and retofit demo.


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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:layout_width="match_parent"    
android:layout_height="match_parent"    
tools:context="com.runindiarun.rxjavademo.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <EditText
        android:id="@+id/edittextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>









RetrofitApiInterface.java


package com.runindiarun.rxjavademo;

import com.google.gson.JsonObject;

import io.reactivex.Observable;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

/** * Created by Admin: Yang on 24-05-2018. */
public interface RetrofitApiInterface {

        @Headers("Accept:application/json")
        @POST("search")
        public Observable<JsonObject> getSearch(@Body JsonObject obj);
}




MainActivity.java


package com.runindiarun.rxjavademo;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    public static final String BASE_URL = "";//provide url here
    private CompositeDisposable mCompositeDisposable;
    private TextView textView;
    private EditText editText;
    PublishSubject publishSubject;
    DisposableObserver<JsonObject> observer;



    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=(TextView)findViewById(R.id.textView);
        editText=(EditText)findViewById(R.id.edittextView);

        publishSubject=PublishSubject.create();
        mCompositeDisposable = new CompositeDisposable();
        observer=getSearchObserver();
        loadApi();
    }

    private void loadApi() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        okHttpClient.readTimeout(60, TimeUnit.SECONDS);
        okHttpClient.addInterceptor(logging);
        okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
        okHttpClient.addNetworkInterceptor(new Interceptor() {
            @Override            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();

                Request.Builder requestBuilder = original.newBuilder()
                        .addHeader("Hp-Application", "Android");

//pass header here if required
                requestBuilder.addHeader("key", "value");
                requestBuilder.addHeader("key", "value");
                Request request = requestBuilder.build();
                Response originalResponse = chain.proceed(request);
                return originalResponse;
            }
        });
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        RetrofitApiInterface requestInterface = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient.build())
                .build().create(RetrofitApiInterface.class);



        mCompositeDisposable.add((Disposable) publishSubject.debounce(300,TimeUnit.MILLISECONDS)
        .distinctUntilChanged()
        .switchMap(new Function<String, Observable<JsonObject>>() {
            @Override            public Observable<JsonObject> apply(String s) throws Exception {
                JsonObject obj=new JsonObject();
                    obj.addProperty("keyword", s);
                    obj.addProperty("latitude", "");
                    obj.addProperty("longitude", "");
                    return requestInterface.getSearch(obj)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
            }
        }).subscribeWith(observer));


        mCompositeDisposable.add(RxTextView.textChangeEvents(editText)
                .skipInitialValue()
                .debounce(300, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(searchContactsTextWatcher()));

        mCompositeDisposable.add(observer);

        publishSubject.onNext("");

        }

    private DisposableObserver<TextViewTextChangeEvent> searchContactsTextWatcher() {
        return new DisposableObserver<TextViewTextChangeEvent>() {
            @Override
            public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                Log.d("Search", "Search query: " + textViewTextChangeEvent.text());
                publishSubject.onNext(textViewTextChangeEvent.text().toString());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
    }

    private DisposableObserver<JsonObject> getSearchObserver() {
        return new DisposableObserver<JsonObject>() {
            @Override
            public void onNext(JsonObject jsonObject) {

                textView.setText(jsonObject.toString());
            }

            @Override
            public void onError(Throwable e) {
                Log.e("Error", "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        };
    }


}





build.gradle(app level)


apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.runindiarun.rxjavademo"
        minSdkVersion 16 
       targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }



    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8    }
}

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:23.1.1'    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
    implementation "com.squareup.retrofit2:retrofit:2.0.0"
    implementation "com.squareup.retrofit2:converter-gson:2.0.0"
    implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
    implementation "com.squareup.okhttp3:okhttp:3.0.1"
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.1"
    implementation "com.squareup.okhttp3:logging-interceptor:3.4.1"
    implementation "com.jakewharton.rxbinding2:rxbinding:2.0.0"
}


Link for reference

https://www.androidhive.info/RxJava/android-rxjava-instant-search-local-remote-databases/




Comments

Popular Post

QR code scanner using Zxing library. Scanner for android

Store GPS Location in image background android.

Storing captured image or an image picked from a gallery in internal storage using file provider android.

Shortcut for android for every version, android shortcut for oreo, android shortcut for nougat.