Tutorial 3: Search an image from camera

This tutorial is very similar to Tutorial 2. Clicking on the button opens the camera app instead of the Photo app. Once your camera is focused and ready to search, capture an image will trigger the search. The difference here is we handle the search in an asynchronous manner. Which is usually the way you should go when integrating aiqkit image search service in your app. Since most of the codes are similar, the only difference is in the MainActivity class, I'll only post the codes for MainActivty here for simplicity. You can always refer to our source code at https://github.com/IQNECT-ORG/aiqkit-android.

MainActivity


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void OnClick(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 0);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
            //scale up the bitmap large enough
            imageBitmap = Bitmap.createScaledBitmap(imageBitmap, imageBitmap.getWidth() * 3, imageBitmap.getHeight() * 3, true);
            Observable<AIQKit.MatchResult> result = AIQKit.matchImage(imageBitmap);

            result.observeOn(AndroidSchedulers.mainThread()).subscribe(
                    new Action1<AIQKit.MatchResult>() {
                        @Override
                        public void call(AIQKit.MatchResult result) {
                            // take the returned payload as url and show it in browser window
                            if (result != null) {
                                Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getPayload()));
                                startActivity(myIntent);
                            } else {
                                showToast("No match found");
                            }
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            // check if the result is "no match found'
                            if (AIQKit.isImageNotFoundError(throwable)) {
                                showToast("No match found");
                            } else {
                                showToast("Error: " + throwable.getMessage());
                            }
                        }
                    }
            );
        }
    }

    private void showToast(String text) {
        Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
    }
}