我正在使用谷歌图片搜索API获取图片网址。我使用okhttp连接到网址。这是在我的activity的oncreate方法中完成的。在片段的oncreate()方法中我获取所有图像URL并将它们存储在mSmallIMagesUrl中,在oncreateView()中我尝试使用自定义适配器显示图像。但是当我运行我的应用程序时,点击搜索按钮,它显示一个空白页面,当我返回并单击搜索按钮(搜索框中始终有文本)时,它会显示上一个搜索文本的图像。我不知道为什么会这样,下面是我的代码,请让我知道我错过了什么。谢谢
package com.paveynganpi.allsearch;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class ImageGrid extends ActionBarActivity {
private static final String TAG = ImageGrid.class.getSimpleName();
protected int start = 0;//variable to change pages from google Api
//contains extra images urls to supply to ... when need
protected static ArrayList<ArrayList<String>> mBigImagesUrls = new ArrayList<ArrayList<String>>();
//contains image urls to inject into gridview
protected static ArrayList<String> mSmalImagesUrls = new ArrayList<>();
protected static String mEditedString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
for (int start = 0; start < 2; start++) {
if (isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(getImagePage(start)).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
// mSmalImagesUrls = getCurrentDetails(jsonData);
mBigImagesUrls.add(getCurrentDetails(jsonData));
Log.d(TAG, mBigImagesUrls.size() + " big size");
Log.d(TAG, mSmalImagesUrls.size() + " small size");
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
} else {
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_grid, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private String getImagePage(int start) {
return "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString + "&rsz=8&start=" + start;
}
//get data
private ArrayList<String> getCurrentDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject responseData = jsonObject.getJSONObject("responseData");
ArrayList<String> localList = new ArrayList<String>();
JSONArray results = responseData.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
localList.add(results.getJSONObject(i).getString("url"));
}
return localList;
}
//An AlertDialog to display to user when an error occurs
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
//checks if user is connected to a network
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
isAvailable = true;
}
return isAvailable;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Log.d(TAG,"back was pressed");
mBigImagesUrls.clear();
mSmalImagesUrls.clear();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected GridView mGridView;//reference to gridview in fragment_image_grid.xml
static String mEditedString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, mBigImagesUrls.size() + " final big size");
Log.d(TAG, mSmalImagesUrls.size() + "final small size");
for(int i =0;i<mBigImagesUrls.size();i++){
for(int j =0;j<8;j++){
mSmalImagesUrls.add(mBigImagesUrls.get(i).get(j));
}
}
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_image_grid, container, false);
final ArrayList<String> testList = new ArrayList<String>();
//gets the edited string from MainActivity
Bundle args = getActivity().getIntent().getExtras();
mEditedString = args.getString("space");
mGridView = (GridView)rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(), mSmalImagesUrls);
mGridView.setAdapter(adapter);
return rootView;
}
}
}
答案 0 :(得分:0)
由于您正在发出异步请求,因此响应无法立即生效。您可以在下载图像列表时显示ProgressBar,然后在完成下载后显示列表。
之后,通知适配器数据集已更改。