我正在尝试从API获取数据,然后在gridview上显示图像。
我可以从api获取数据并将值(url image)放到我在onpostexecute方法上创建的自定义适配器上。
但它没有在网格上显示任何内容。值为空
我一直在寻找这个解决方案两天
有人可以帮我解决这个问题吗?
这是我的代码:
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private MovieAdapter movieAdapter;
MovieList[] movieList;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), new ArrayList<MovieList>());
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);
gridView.setAdapter(movieAdapter);
return rootView;
}
public void fetchMoviesData(){
try {
SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortCateg = perf.getString(getString(R.string.pref_sort_key), getString(R.string.sort_value_popular));
fetchMovieDataTask fwd = new fetchMovieDataTask();
fwd.execute(sortCateg).get();
}catch(Exception e){
Toast.makeText(getActivity(),"Failed retreive movies data!",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStart() {
super.onStart();
fetchMoviesData();
}
public class fetchMovieDataTask extends AsyncTask<String,Void,MovieList[]>{
private final String LOG_TAG = fetchMovieDataTask.class.getSimpleName();
@Override
protected MovieList[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
String movieStr = null;
String sortOrder = params[0];
try{
final String BASE_URL = "http://api.themoviedb.org/3/movie/"+sortOrder;
final String API_KEY = "api_key";
Uri buildUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_KEY,BuildConfig.theMovieDbApiKey)
.build();
URL url = new URL(buildUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer stringBuffer = new StringBuffer();
if(inputStream == null){
movieStr = null;
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = bufferedReader.readLine()) != null){
stringBuffer.append(line + "\n");
}
if(stringBuffer.length() == 0){
return null;
}
movieStr = stringBuffer.toString();
}catch(IOException e){
Log.e(LOG_TAG,"Error",e);
movieStr = null;
}finally {
if(urlConnection != null){
urlConnection.disconnect();
}
if(bufferedReader != null){
try{
bufferedReader.close();
}catch(final IOException e){
Log.e(LOG_TAG,"Error Closing Reader",e);
}
}
}
try{
return getMoviePosterFromJson(movieStr);
}catch(JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(MovieList[] result) {
if(result != null){
movieAdapter.clear();
movieAdapter = new MovieAdapter(getActivity(), Arrays.asList(result));
}
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
private MovieList[] getMoviePosterFromJson(String movieJsonStr)
throws JSONException {
final String BASE_URL = "http://image.tmdb.org/t/p/w185";
final String TMDb_RESULT = "results";
final String TMDb_POSTER = "poster_path";
final String TMDb_TITLE = "original_title";
final String TMDb_DATE = "release_date";
final String TMDb_VOTE = "vote_average";
final String TMDb_OVERVIEW = "overview";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(TMDb_RESULT);
movieList = new MovieList[movieArray.length()];
for(int i = 0; i < movieArray.length() - 1; i++) {
String title;
String poster;
Integer year;
String rating;
String overview;
JSONObject movieObject = movieArray.getJSONObject(i);
poster = BASE_URL + movieObject.getString(TMDb_POSTER);
title = movieObject.getString(TMDb_TITLE);
year = stringToDate(movieObject.getString(TMDb_DATE),"yyy-MM-dd").getYear();
rating = movieObject.getString(TMDb_VOTE);
overview = movieObject.getString(TMDb_OVERVIEW);
movieList[i] = new MovieList(title,poster,year,rating,overview);
}
return movieList;
}
}
}
编辑2:
public class MainActivityFragment extends Fragment {
public MovieAdapter movieAdapter;
MovieList[] movieList;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), new ArrayList<MovieList>());
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);
gridView.setAdapter(movieAdapter);
fetchMoviesData();
return rootView;
}
public void fetchMoviesData(){
try {
SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortCateg = perf.getString(getString(R.string.pref_sort_key), getString(R.string.sort_value_popular));
fetchMovieDataTask fwd = new fetchMovieDataTask();
fwd.execute(sortCateg).get();
}catch(Exception e){
Toast.makeText(getActivity(),"Failed retreive movies data!",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStart() {
super.onStart();
}
public class fetchMovieDataTask extends AsyncTask<String,Void,MovieList[]>{
private final String LOG_TAG = fetchMovieDataTask.class.getSimpleName();
@Override
protected MovieList[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
String movieStr = null;
String sortOrder = params[0];
try{
//http://api.themoviedb.org/3/movie/popular?api_key=e4a8053d4e3bab726a20dcb2c12897f3
final String BASE_URL = "http://api.themoviedb.org/3/movie/"+sortOrder;
final String API_KEY = "api_key";
Uri buildUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_KEY,BuildConfig.theMovieDbApiKey)
.build();
URL url = new URL(buildUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer stringBuffer = new StringBuffer();
if(inputStream == null){
movieStr = null;
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = bufferedReader.readLine()) != null){
stringBuffer.append(line + "\n");
}
if(stringBuffer.length() == 0){
return null;
}
movieStr = stringBuffer.toString();
}catch(IOException e){
Log.e(LOG_TAG,"Error",e);
movieStr = null;
}finally {
if(urlConnection != null){
urlConnection.disconnect();
}
if(bufferedReader != null){
try{
bufferedReader.close();
}catch(final IOException e){
Log.e(LOG_TAG,"Error Closing Reader",e);
}
}
}
try{
return getMoviePosterFromJson(movieStr);
}catch(JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(MovieList[] result) {
if(result != null){
GridView gridView = (GridView) getActivity().findViewById(R.id.grid_view);
movieAdapter = new MovieAdapter(getActivity(), Arrays.asList(result));
gridView.setAdapter(movieAdapter);
}
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
private MovieList[] getMoviePosterFromJson(String movieJsonStr)
throws JSONException {
final String BASE_URL = "http://image.tmdb.org/t/p/w185";
final String TMDb_RESULT = "results";
final String TMDb_POSTER = "poster_path";
final String TMDb_TITLE = "original_title";
final String TMDb_DATE = "release_date";
final String TMDb_VOTE = "vote_average";
final String TMDb_OVERVIEW = "overview";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(TMDb_RESULT);
movieList = new MovieList[movieArray.length()];
for(int i = 0; i < movieArray.length() - 1; i++) {
String title;
String poster;
Integer year;
String rating;
String overview;
JSONObject movieObject = movieArray.getJSONObject(i);
poster = BASE_URL + movieObject.getString(TMDb_POSTER);
title = movieObject.getString(TMDb_TITLE);
year = stringToDate(movieObject.getString(TMDb_DATE),"yyy-MM-dd").getYear();
rating = movieObject.getString(TMDb_VOTE);
overview = movieObject.getString(TMDb_OVERVIEW);
movieList[i] = new MovieList(title,poster,year,rating,overview);
}
return movieList;
}
}
} ERROR EDIT 2
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.william.themovieapps.MainActivityFragment$fetchMovieDataTask.onPostExecute(MainActivityFragment.java:174)
at com.example.william.themovieapps.MainActivityFragment$fetchMovieDataTask.onPostExecute(MainActivityFragment.java:95)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
onPostExecute 应如下所示:
@Override
protected void onPostExecute(MovieList[] result) {
if(result != null){
movieAdapter = new MovieAdapter(getActivity(), Arrays.asList(result));
gridView.setAdapter(movieAdapter);
}
}
修改1:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MovieList movieList = getItem(position);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.poster_griditem_layout,parent,false);
Picasso
.with(getContext())
.load(movieList.poster)
.fit()
.into((ImageView) convertView);
return convertView;
}
编辑2:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), new ArrayList<MovieList>());
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);
gridView.setAdapter(movieAdapter);
fetchMoviesData();
return rootView;
}
@Override
public void onStart() {
super.onStart();
}
希望这会对你有所帮助。
答案 1 :(得分:0)
@Hiren Patel,这是我的代码和logcat: Logcat
MovieAdapter.java
@Column(columnDefinition="BLOB NOT NULL")
@MapKeyColumn(columnDefinition="BLOB NOT NULL")
}
答案 2 :(得分:0)
抱歉,伙计们我的错误。我在我的数组中的数据。现在解决它。感谢所有的帮助