java - 狗品种 API Android Studio

标签 java android json api

这是link to the API for JSON .

我正在尝试访问狗品种的列表和图像,但当我的应用程序在 Android Studio 中启动时,它没有显示任何内容。

在主 Activity 类之后,我还给出了 CustomAdapter 类。 尝试过其他事情但不起作用。

这是我的 MainActivity 类:

public class MainActivity extends AppCompatActivity {

    ArrayList<Product> arrayList;
    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        arrayList = new ArrayList<>();
        list = (ListView) findViewById(R.id.list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new ReadJSON().execute("https://dog.ceo/api/breeds/list/all");
            }
        });
    }

    class ReadJSON extends AsyncTask<String,Integer, String>{
        @Override
        protected String doInBackground(String... params) {
            return readURL(params[0]);
        }

        @Override
        protected void onPostExecute(String content) {
            try {
                JSONObject jsonObject = new JSONObject(content);
                JSONArray jsonArray =  jsonObject.getJSONArray("status");

                for(int i =0;i<jsonArray.length(); i++){
                    JSONObject productObject = jsonArray.getJSONObject(i);
                    arrayList.add(new Product(
                            productObject.getString("status"),
                            productObject.getString("message")
                    ));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            CustomAdapter adapter = new CustomAdapter(
                    getApplicationContext(), R.layout.list_row, arrayList
            );
            list.setAdapter(adapter);
        }
    }

    private static String readURL(String theUrl) {
        StringBuilder content = new StringBuilder();
        try {
            // create a url object
            URL url = new URL(theUrl);
            // create a urlconnection object
            URLConnection urlConnection = url.openConnection();
            // wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            // read from the urlconnection via the bufferedreader
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}

客户适配器:

public class CustomAdapter extends ArrayAdapter<Product> {

    ArrayList<Product> products;
    Context context;
    int resource;

    public CustomAdapter(Context context, int resource, ArrayList<Product> products) {
        super(context, resource, products);
        this.products = products;
        this.context = context;
        this.resource = resource;
    }

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

        if (convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) getContext()
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_row, null, true);

        }
        Product product = getItem(position);

        ImageView image = (ImageView) convertView.findViewById(R.id.image);
        Picasso.with(context).load(product.getImage()).into(image);

        TextView breedName = (TextView) convertView.findViewById(R.id.breedName);
        breedName.setText(product.getBreedName());


        return convertView;
    }
}

产品:

enter code here

最佳答案

我对您的代码进行了如下更改:

更新:感谢 solution作者:@Jay Rathod RJ,我更新了代码,以便它将从服务器加载品种名称,然后根据品种名称相应地加载图像。

创建 BreedLoader 类:

package com.example.pbp22.dogbreed;

import android.content.AsyncTaskLoader;
import android.content.Context;

import java.util.List;

public class BreedLoader extends AsyncTaskLoader<List<Breed>> {
/**
 * Tag for log messages
 */
private static final String LOG_TAG = BreedLoader.class.getName();

List<String> breedNames;

public BreedLoader(Context context, List<String> breedNames) {
    super(context);
    this.breedNames = breedNames;
}

@Override
protected void onStartLoading() {
    forceLoad();
}

/**
 * This is on a background thread.
 */
@Override
public List<Breed> loadInBackground() {

    // Perform the network request, parse the response, and extract a list of breeds.
    return QueryUtils.fetchBreedData(breedNames);
}
}

创建 BreedNameLoader 类:

package com.example.pbp22.dogbreed;

import android.content.AsyncTaskLoader;
import android.content.Context;

import java.util.List;

public class BreedNameLoader extends AsyncTaskLoader<List<String>> {

    /**
     * Tag for log messages
     */
    private static final String LOG_TAG = BreedLoader.class.getName();

    public BreedNameLoader(Context context) {
        super(context);
    }

    @Override
    protected void onStartLoading() {
        forceLoad();
    }

    /**
     * This is on a background thread.
     */
    @Override
    public List<String> loadInBackground() {

        // Perform the network request, parse the response, and extract a list of earthquakes.
        return QueryUtils.fetchBreedNameData();
    }
}

创建 QueryUtils 类:

    package com.example.pbp22.dogbreed;

import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class QueryUtils {

    /** Tag for the log messages */
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();

    /**
     * Query the dataset and return a list of {@link Breed} objects.
     * @param breedNames
     */
    public static List<Breed> fetchBreedData(List<String> breedNames) {

        // Perform HTTP request to the URL and receive a JSON response back
        List<String> jsonResponse = readImageUrl(breedNames);

        // Extract relevant fields from the JSON response and create a list of {@link Breed}s
        List<Breed> breeds = extractBreedFromJson(jsonResponse, breedNames);

        // Return the list of {@link Breed}s
        return breeds;
    }

    /**
     * Query the dataset and return a list of {@link Breed} objects.
     */
    public static List<String> fetchBreedNameData() {

        // Perform HTTP request to the URL and receive a JSON response back
        String jsonResponse = readBreedNameUrl();

        // Extract relevant fields from the JSON response and create a list of {@link Breed}s
        List<String> breedNames = extractBreedNameFromJson(jsonResponse);

        // Return the list of {@link Breed}s
        return breedNames;
    }

    private static List<String> readImageUrl(List<String> breedNames) {

        List<String> reponses = new ArrayList<>();

        for (String breed : breedNames) {
            StringBuilder content = new StringBuilder();
            try {
                // create a url object
                URL url = new URL(String.format("https://dog.ceo/api/breed/%s/images/random", breed));
                // create a urlconnection object
                URLConnection urlConnection = url.openConnection();
                // wrap the urlconnection in a bufferedreader
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;
                // read from the urlconnection via the bufferedreader
                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line + "\n");
                }
                bufferedReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            reponses.add(content.toString());
        }

        return reponses;
    }

    /**
     * Return a list of {@link Breed} objects that has been built up from
     * parsing the given JSON response.
     */
    private static List<Breed> extractBreedFromJson(List<String> responses, List<String> breedNames) {

        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(responses.toString())) {
            return null;
        }

        // Create an empty ArrayList that we can start adding breeds to
        List<Breed> breeds = new ArrayList<>();

        for (int i = 0; i < responses.size(); i++) {

            try {

                // Create a JSONObject from the JSON response string
                JSONObject baseJsonResponse = new JSONObject(responses.get(i));

                String image = baseJsonResponse.getString("message");

                String breedName = breedNames.get(i);

                breeds.add(new Breed(image, breedName));

            } catch (JSONException e) {
                // If an error is thrown when executing any of the above statements in the "try" block,
                // catch the exception here, so the app doesn't crash. Print a log message
                // with the message from the exception.
                Log.e("QueryUtils", "Problem parsing the JSON results", e);
            }


        }

        // Return the list of breeds
        return breeds;
    }

    private static String readBreedNameUrl() {

            StringBuilder content = new StringBuilder();
            try {
                // create a url object
                URL url = new URL("https://dog.ceo/api/breeds/list/all");
                // create a urlconnection object
                URLConnection urlConnection = url.openConnection();
                // wrap the urlconnection in a bufferedreader
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;
                // read from the urlconnection via the bufferedreader
                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line + "\n");
                }
                bufferedReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        return content.toString();
    }

    /**
     * Return a list of {@link String} objects (breed names) that has been built up from
     * parsing the given JSON response.
     */
    private static List<String> extractBreedNameFromJson(String responses) {

        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(responses)) {
            return null;
        }

        // Create an empty ArrayList that we can start adding breed names to
        List<String> breedNameList = new ArrayList<>();


            try {
                JSONObject jsonObject = new JSONObject(responses);
                JSONObject messageObj = jsonObject.getJSONObject("message");

                for (Iterator<String> iter = messageObj.keys(); iter.hasNext(); ) {
                    String key = iter.next();
                    Log.w("key", key);
                    breedNameList.add(key);
                }

                Log.w("messageObj", messageObj.toString());

            } catch (JSONException e) {
                // If an error is thrown when executing any of the above statements in the "try" block,
                // catch the exception here, so the app doesn't crash. Print a log message
                // with the message from the exception.
                Log.e("QueryUtils", "Problem parsing the JSON results", e);
            }

        // Return the list of breeds
        return breedNameList;
    }

}

您的适配器类已发生了一点变化:

package com.example.pbp22.dogbreed;

import android.app.Activity;
import android.content.Context;
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.List;

public class CustomAdapter extends ArrayAdapter<Product> {

    List<Product> products;
    Context context;
    int resource;

    public CustomAdapter(Context context, int resource, List<Product> products) {
        super(context, resource, products);
        this.products = products;
        this.context = context;
        this.resource = resource;
    }

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

        if (convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) getContext()
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_row, null, true);

        }
        Product product = getItem(position);

        ImageView image = (ImageView) convertView.findViewById(R.id.image);
        Picasso.with(context).load(product.getImage()).into(image);

        TextView breedName = (TextView) convertView.findViewById(R.id.breedName);
        breedName.setText(product.getBreedName());


        return convertView;
    }

}

这是您的主要 Activity :

    package com.example.pbp22.dogbreed;

import android.app.LoaderManager;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity{

    ListView list;

    LoaderManager.LoaderCallbacks<List<String>> breedNameLoaderCallbacks;
    LoaderManager.LoaderCallbacks<List<Breed>> breedLoaderCallbacks;

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

        list = (ListView) findViewById(R.id.list);

        breedLoaderCallbacks = new LoaderManager.LoaderCallbacks<List<Breed>>() {
            @Override
            public Loader<List<Breed>> onCreateLoader(int i, Bundle bundle) {

                List<String> breedNames = null;

                if (bundle != null) {
                    breedNames = new ArrayList<>(bundle.getStringArrayList("breed_name"));
                }

                return new BreedLoader(MainActivity.this, breedNames);
            }

            @Override
            public void onLoadFinished(Loader<List<Breed>> loader, List<Breed> products) {


                if (products != null && !products.isEmpty()) {
                    Log.v("DogXXX", products.toString());
                    CustomAdapter adapter = new CustomAdapter(
                            getApplicationContext(), R.layout.list_row, products
                    );
                    list.setAdapter(adapter);
                }
            }

            @Override
            public void onLoaderReset(Loader<List<Breed>> loader) {

            }
        };

        breedNameLoaderCallbacks = new LoaderManager.LoaderCallbacks<List<String>>() {
            @Override
            public Loader<List<String>> onCreateLoader(int i, Bundle bundle) {
                return new BreedNameLoader(MainActivity.this);
            }

            @Override
            public void onLoadFinished(Loader<List<String>> loader, List<String> strings) {

                Bundle breedNameBundle = new Bundle();
                breedNameBundle.putStringArrayList("breed_name", (ArrayList<String>) strings);
                getLoaderManager().initLoader(2, breedNameBundle, breedLoaderCallbacks);
            }

            @Override
            public void onLoaderReset(Loader<List<String>> loader) {

            }
        };

        getLoaderManager().initLoader(1, null, breedNameLoaderCallbacks);
    }
}

结果:

enter image description here

关于java - 狗品种 API Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186716/

相关文章:

java - 为什么由 ScheduledExecutorService.schedule() 启动的线程永远不会终止?

java - 带有 Gradle 的谷歌云存储 Java 客户端库

android - 将导航架构组件与抽屉导航一起使用

javascript - Microsoft QnA Maker API 错误未找到资源

python - JSON 响应和 Scrapy

json - 如何在全日历中将事件显示为彩色点?

java - 如何确保在 Apache Tomcat 中运行的 Spring Boot 应用程序中替换了环境变量占位符?

java - 如何在Gradle项目中创建单个可执行jar

Android build.gradle ERROR : ParseError at [row, col] :[65, 9] 消息:预期的开始或结束标记受影响的模块:app

android - Android 4.4 Kitkat 中的内部文件选择器