Java 狗繁殖API安卓工作室
这是最新的 我正在尝试访问列表和狗的图片,但是当我的应用程序在Android Studio中启动时,它什么也没有显示 在主活动类之后,我还提供了CustomAdapter类。 尝试过其他东西,但不起作用 这是我的主要活动课:Java 狗繁殖API安卓工作室,java,android,json,api,Java,Android,Json,Api,这是最新的 我正在尝试访问列表和狗的图片,但是当我的应用程序在Android Studio中启动时,它什么也没有显示 在主活动类之后,我还提供了CustomAdapter类。 尝试过其他东西,但不起作用 这是我的主要活动课: public class MainActivity extends AppCompatActivity { ArrayList<Product> arrayList; ListView list; @Override prot
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();
}
}
请尝试此代码,以便轻松处理 将以下依赖项添加到应用程序级渐变文件中
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
然后在进行如下改造对象类后
public class ApiClient {
private final static String BASE_URL = "https://dog.ceo/api/breed/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2 = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
然后创建api调用的接口,如下代码所示
public interface ApiInterface {
@GET("{catname}/images")
Call<Product> getProductData(@Path("catname") String breed);
public class Product {
@SerializedName("status")
private String status;
@SerializedName("message")
private List<String> message = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
@Override
public String toString() {
return
"Response{" +
"message = '" + message + '\'' +
",status = '" + status + '\'' +
"}";
}
公共接口{
@获取(“{catname}/images”)
调用getProductData(@Path(“catname”)字符串);
}
然后在api中调用类似下面代码的活动
public void getProductData() {
ApiInterface apiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<Product> productCall=apiInterface.getProductData("airedale"); // pass your string as dog brand.
productCall.enqueue(new Callback<Product>() {
@Override
public void onResponse(Call<Product> call, retrofit2.Response<Product> response) {
if (response.isSuccessful() && response.body()!=null){
Product product=response.body();
productlist.add(product);
Log.d("Status",product.getStatus());
Log.d("Message",product.getMessage().toString());
}
}
@Override
public void onFailure(Call<Product> call, Throwable t) {
}
});
}
public void getProductData(){
ApiInterface ApiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
Call productCall=apinterface.getProductData(“airedale”);//将字符串作为dog brand传递。
productCall.enqueue(新回调(){
@凌驾
公共void onResponse(呼叫,改装2.响应){
if(response.issusccessful()&&response.body()!=null){
Product=response.body();
productlist.add(产品);
Log.d(“Status”,product.getStatus());
Log.d(“Message”,product.getMessage().toString());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
}
使产品类别如下代码所示
public interface ApiInterface {
@GET("{catname}/images")
Call<Product> getProductData(@Path("catname") String breed);
public class Product {
@SerializedName("status")
private String status;
@SerializedName("message")
private List<String> message = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
@Override
public String toString() {
return
"Response{" +
"message = '" + message + '\'' +
",status = '" + status + '\'' +
"}";
}
公共类产品{
@序列化名称(“状态”)
私有字符串状态;
@SerializedName(“消息”)
私有列表消息=null;
公共字符串getStatus(){
返回状态;
}
公共无效设置状态(字符串状态){
这个状态=状态;
}
公共列表getMessage(){
返回消息;
}
公共无效设置消息(列表消息){
this.message=消息;
}
@凌驾
公共字符串toString(){
返回
“响应{”+
“消息='”+消息+'\''+
,状态=“+”状态+“\”+
"}";
}
}请尝试此代码,以便轻松处理 将以下依赖项添加到应用程序级渐变文件中
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
然后在进行如下改造对象类后
public class ApiClient {
private final static String BASE_URL = "https://dog.ceo/api/breed/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2 = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
然后创建api调用的接口,如下代码所示
public interface ApiInterface {
@GET("{catname}/images")
Call<Product> getProductData(@Path("catname") String breed);
public class Product {
@SerializedName("status")
private String status;
@SerializedName("message")
private List<String> message = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
@Override
public String toString() {
return
"Response{" +
"message = '" + message + '\'' +
",status = '" + status + '\'' +
"}";
}
公共接口{
@获取(“{catname}/images”)
调用getProductData(@Path(“catname”)字符串);
}
然后在api中调用类似下面代码的活动
public void getProductData() {
ApiInterface apiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<Product> productCall=apiInterface.getProductData("airedale"); // pass your string as dog brand.
productCall.enqueue(new Callback<Product>() {
@Override
public void onResponse(Call<Product> call, retrofit2.Response<Product> response) {
if (response.isSuccessful() && response.body()!=null){
Product product=response.body();
productlist.add(product);
Log.d("Status",product.getStatus());
Log.d("Message",product.getMessage().toString());
}
}
@Override
public void onFailure(Call<Product> call, Throwable t) {
}
});
}
public void getProductData(){
ApiInterface ApiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
Call productCall=apinterface.getProductData(“airedale”);//将字符串作为dog brand传递。
productCall.enqueue(新回调(){
@凌驾
公共void onResponse(呼叫,改装2.响应){
if(response.issusccessful()&&response.body()!=null){
Product=response.body();
productlist.add(产品);
Log.d(“Status”,product.getStatus());
Log.d(“Message”,product.getMessage().toString());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
}
使产品类别如下代码所示
public interface ApiInterface {
@GET("{catname}/images")
Call<Product> getProductData(@Path("catname") String breed);
public class Product {
@SerializedName("status")
private String status;
@SerializedName("message")
private List<String> message = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
@Override
public String toString() {
return
"Response{" +
"message = '" + message + '\'' +
",status = '" + status + '\'' +
"}";
}
公共类产品{
@序列化名称(“状态”)
私有字符串状态;
@SerializedName(“消息”)
私有列表消息=null;
公共字符串getStatus(){
返回状态;
}
公共无效设置状态(字符串状态){
这个状态=状态;
}
公共列表getMessage(){
返回消息;
}
公共无效设置消息(列表消息){
this.message=消息;
}
@凌驾
公共字符串toString(){
返回
“响应{”+
“消息='”+消息+'\''+
,状态=“+”状态+“\”+
"}";
}
}您需要更改
异步任务的方法。您需要更改Json解析过程,如下所示,这是您所做的错误
按如下所示更改您的ReadJSON
类
class ReadJSON extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
@Override
protected void onPostExecute(String content) {
try {
Log.w("content", content);
JSONObject jsonObject = new JSONObject(content);
JSONObject messageObj = jsonObject.getJSONObject("message");
for (Iterator<String> iter = messageObj.keys(); iter.hasNext(); ) {
String key = iter.next();
Log.w("key", key);
arrayList.add(new Product("", key));
}
Log.w("messageObj", messageObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
CustomAdapter adapter = new CustomAdapter(
TestActivity.this, R.layout.list_row, arrayList
);
list.setAdapter(adapter);
}
}
产品
public class Product {
// Store the name of the movie
private String image;
// Store the release date of the movie
private String breedName;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBreedName() {
return breedName;
}
public void setBreedName(String breedName) {
this.breedName = breedName;
}
// Constructor that is used to create an instance of the Movie object
public Product(String image, String breedName) {
this.image = image;
this.breedName = breedName;
}
}
这将仅在列表中为您提供品种名称
在列表中输出品种名称
您需要更改异步任务的方法。您需要更改Json解析过程,如下所示,这是您所做的错误
按如下所示更改您的ReadJSON
类
class ReadJSON extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
@Override
protected void onPostExecute(String content) {
try {
Log.w("content", content);
JSONObject jsonObject = new JSONObject(content);
JSONObject messageObj = jsonObject.getJSONObject("message");
for (Iterator<String> iter = messageObj.keys(); iter.hasNext(); ) {
String key = iter.next();
Log.w("key", key);
arrayList.add(new Product("", key));
}
Log.w("messageObj", messageObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
CustomAdapter adapter = new CustomAdapter(
TestActivity.this, R.layout.list_row, arrayList
);
list.setAdapter(adapter);
}
}
产品
public class Product {
// Store the name of the movie
private String image;
// Store the release date of the movie
private String breedName;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBreedName() {
return breedName;
}
public void setBreedName(String breedName) {
this.breedName = breedName;
}
// Constructor that is used to create an instance of the Movie object
public Product(String image, String breedName) {
this.image = image;
this.breedName = breedName;
}
}
这将仅在列表中为您提供品种名称
在列表中输出品种名称
我对您的代码做了如下更改:
更新:多亏了@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);
}
}
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();
}
}
package com.example.pbp22.dogbride;
导入android.content.AsyncTaskLoader;
导入android.content.Context;
导入java.util.List;
公共类BreedLoader扩展了AsyncTaskLoader{
/**
*日志消息的标记
*/
私有静态最终字符串LOG_TAG=BreedLoader.class.getName();
列出breedNames;
公共BreedLoader(上下文、列表breedNames){
超级(上下文);
this.breedNames=breedNames;
}
@凌驾
开始加载时受保护的void(){
力载荷();
}
/**
*这是一个背景线程。
*/
@凌驾
公共列表加载背景(){
//执行网络请求,解析响应,并提取品种列表。
返回QueryUtils.fetchBreedData(breedNames);
}
}
创建BreedNameLoader类:
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);
}
}
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();
}
}
package com.example.pbp22.dogbride;
导入android.content.AsyncTaskLoader;
导入android.content.Context;
导入java。