【问题标题】:Call another api if one api returns null value如果一个 api 返回 null 值,则调用另一个 api
【发布时间】:2018-09-29 14:27:24
【问题描述】:

我正在构建一个用于销售图书的 Android 应用。我有一个集成的条形码扫描仪,我的用户可以使用它扫描他们想要出售的图书的条形码。

我可以使用 Zxing 图书馆从条形码中获取图书的 ISBN 号。我正在使用这个 ISBN 号从 openlibrary.org API 获取数据。

现在的问题是,如果 openlibrary 没有该图书数据,我想调用 Google Books API。

尽管 openlibrary 的数据不如 Google 多,但我仍然使用它们的原因是它们提供了高质量的书籍封面图片。 Google 没有可用的数据。

所以现在我需要知道如果 openlibrary 的响应为空,如何调用 Google 的 API。

这是我的完整代码:

package com.example.gaayathri.barcodetest;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

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

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

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

        Button button = this.findViewById(R.id.button);
        final Activity activity = this;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageView ivBookImage = findViewById(R.id.ivBookImage);
                ivBookImage.setImageBitmap(null);

                TextView tvTitle = findViewById(R.id.tvTitle);
                tvTitle.setText("");

                TextView tvAuthor = findViewById(R.id.tvAuthor);
                tvAuthor.setText("");


                IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
                integrator.setPrompt("Scan a barcode");
                integrator.setCameraId(0);  // Use a specific camera of the device
                integrator.setOrientationLocked(true);
                integrator.setBeepEnabled(true);
                integrator.setCaptureActivity(CaptureActivityPortrait.class);
                integrator.initiateScan();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();

                final String isbn = result.getContents();

                String bookOpenApi = "https://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&jscmd=data&format=json";

                //String bookSearchString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(bookOpenApi)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        // ... check for failure using `isSuccessful` before proceeding

                        // Read data on the worker thread
                        final String responseData = response.body().string();

                        // Run view-related code back on the main thread
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                JSONObject resultObject = null;

                                try {

                                    resultObject = new JSONObject(responseData);

                                    JSONObject isbnObject = resultObject.getJSONObject("ISBN:" + isbn);

                                    String TitleL = isbnObject.getString("title");

                                    if (TitleL.length()!=0){

                                        Toast.makeText(MainActivity.this, "Title length = " + TitleL.length(), Toast.LENGTH_SHORT).show();

                                        try{
                                            TextView tvTitle = findViewById(R.id.tvTitle);
                                            tvTitle.setText("TITLE: "+isbnObject.getString("title"));
                                        }
                                        catch(JSONException jse){
                                            TextView tvTitle = findViewById(R.id.tvTitle);
                                            tvTitle.setText("");
                                            jse.printStackTrace();
                                        }

                                        try{

                                            JSONArray authors = isbnObject.getJSONArray("authors");
                                            JSONObject author = authors.getJSONObject(0);

                                            String authorName = author.getString("name");

                                            TextView tvAuthor = findViewById(R.id.tvAuthor);
                                            tvAuthor.setText("AUTHOR(S): "+ authorName);
                                        }
                                        catch(JSONException jse){
                                            TextView tvAuthor = findViewById(R.id.tvAuthor);
                                            tvAuthor.setText("");
                                            jse.printStackTrace();
                                        }

                                        try{

                                            JSONObject imageObject = isbnObject.getJSONObject("cover");

                                            String imageUrl = imageObject.getString("large");

                                            ImageView ivBookImage = findViewById(R.id.ivBookImage);

                                            Glide.with(MainActivity.this).load(imageUrl).into(ivBookImage);
                                        }
                                        catch(JSONException jse){

                                            Toast.makeText(MainActivity.this, "No book image available", Toast.LENGTH_SHORT).show();
                                            jse.printStackTrace();
                                        }

                                    } else {

                                        String bookSearchString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

                                        OkHttpClient client = new OkHttpClient();

                                        Request request = new Request.Builder()
                                                .url(bookSearchString)
                                                .build();

                                        client.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(Call call, IOException e) {

                                            }

                                            @Override
                                            public void onResponse(Call call, Response response) throws IOException {

                                                final String googleResponseData = response.body().string();

                                                MainActivity.this.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {

                                                        JSONObject resultObject = null;

                                                        try {

                                                            resultObject = new JSONObject(googleResponseData);

                                                            JSONArray items = resultObject.getJSONArray("items");

                                                            JSONObject volumeInfo = items.getJSONObject(0);

                                                            JSONObject volumeObject = volumeInfo.getJSONObject("volumeInfo");

                                                            String TitleL = volumeObject.getString("title");

                                                            TextView tvTitle = findViewById(R.id.tvTitle);

                                                            tvTitle.setText(TitleL);

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

                                                        try {

                                                            JSONArray items = resultObject.getJSONArray("items");

                                                            JSONObject volumeInfo = items.getJSONObject(0);

                                                            JSONObject volumeObject = volumeInfo.getJSONObject("volumeInfo");

                                                            JSONArray authorsArray = volumeObject.getJSONArray("authors");

                                                            String authorName = authorsArray.getString(0);

                                                            TextView tvAuthor = findViewById(R.id.tvAuthor);
                                                            tvAuthor.setText("AUTHOR(S): "+ authorName);


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

                                                    }
                                                });

                                            }
                                        });

                                    }

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

                            }
                        });
                    }
                });

            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


}

【问题讨论】:

  • 检查response.body().string() == null或空字符串并调用google api。

标签: android api google-books


【解决方案1】:

好的,我通过使用EditText 字段作为关键字段解决了这个问题。所以想法是使用条形码扫描仪返回的 ISBN 号调用openlibrary API,并填充Simple drawee viewTitle EdittextAuthor Edittext

然后检查Title Edittext 字段是否已填充。如果已填充,则表示OpenLibrary API 已返回有效数据。如果Title Edittext 为空,则调用Google's books API

OnActivityResult()函数的完整源代码如下所示:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    final IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
        if(result.getContents() == null) {
            Log.d("MainActivity", "Cancelled scan");
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Log.d("MainActivity", "Scanned");
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // This function will fetch the data from openlibrary API
                    checkinOpenLibrary(result.getContents());

                    EditText tvTitle = findViewById(R.id.etMaterialTitle);
                    if (tvTitle.getText().length() == 0) {
                        // This function will fetch the data from Google's books API
                        checkinGoogleAPI(result.getContents());
                    }

                }
            });

        }
    } else {
        // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 2022-11-17
    • 2019-06-12
    相关资源
    最近更新 更多