这是link to the API for JSON。
我正在尝试访问列表和犬种的图像,但是当我的应用在Android Studio中启动时,它什么也没有显示。
在主活动类之后,我还给出了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
最佳答案
我对您的代码进行了如下更改:
更新:感谢@Jay Rathod RJ的solution,我更新了代码,因此它将从服务器加载“品种名称”,然后根据品种名称加载图像。
创建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;
}
}
这是您的主要活动:
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);
}
}
结果: