BaseAdapter无效

时间:2016-03-10 09:37:02

标签: java android json android-asynctask

我是Android应用开发的初学者。请帮我解决这个问题。

我有一个MainActivityFragment,我必须从远程位置获取并填充一些图像数据。为此,我在一个单独的类中使用了AsyncTask,并从MainActivityFragment类中调用它。我还创建了另一个名为ImageAdapter的类,它扩展了BaseAdapter。

当我通过在阵列中放置一些可绘制图像来运行应用程序时。代码工作得很好。但是,当我从AsyncTask获取JSON数据并从JSON中提取图像路径并将该“提取的图像路径值”分配给AsyncTask类中的ImageAdapter类中的字段时,应用程序运行平稳但屏幕上没有填充图像。我尝试在ImageAdapter类和其他地方放置一些调试点但是找不到问题,因为当应用程序在调试模式下运行时,应用程序从未到达调试点。

MainActivityFragment.java

   package com.example.pavan.moviesapp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

// API : f9b69f2b96bfaa9b1748f12afbe14cea
/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

//    JSONObject jsonObject;
//    JSONObject objectsInJSONArray;
//    ArrayAdapter<String> moviePoster;


    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_main, container, false);

//        new ImageAdater.FetchMovieData().execute("POPULARITY.desc");



        final GridView gridView = (GridView) rootView.findViewById(R.id.movie_grid_view);


        new FetchMovieData().execute("POPULARITY.desc");

        gridView.setAdapter(new ImageAdater(getContext()));

//        gridView.setAdapter(new ImageAdater());



        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getContext(),"position : " + position,Toast.LENGTH_SHORT).show();
            }
        });
        return rootView;
    }

}

FetchMovieData.java

package com.example.pavan.moviesapp;

import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by pavan on 3/7/2016.
 */

public class FetchMovieData extends AsyncTask {

    JSONObject jsonObject;
    JSONObject objectsInJSONArray;

    @Override
    protected Object doInBackground(Object[] params) {
        if (params.length == 0)
            return null;

        String API_KEY = "f9b69f2b96bfaa9b1748f12afbe14cea";
//        String IMAGE_SIZE = "w185";
        String BASE_URL = " http://api.themoviedb.org/3/discover/movie?";
        // String SORT_BY = "POPULARITY.desc";
        String SORT_BY = (String) params[0];

        String SORT_BY_PARAM = "sort_by";
        String API_KEY_PARAM = "api_key";
        Uri.Builder uri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(SORT_BY_PARAM, SORT_BY)
                .appendQueryParameter(API_KEY_PARAM, API_KEY);

        uri.build();


        String MoviesJSONdata = null;
        try {
            URL url = new URL(uri.toString());

            //Creating a request to the moviedb api
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            //Reading the input stream
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();

            if (inputStream == null){
                //do nothing
                Log.e("input stream is null ", inputStream.toString());
                return null;}

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null)
                stringBuffer.append(line + "\n");
            if (stringBuffer.length() == 0)
                return null;

            MoviesJSONdata = stringBuffer.toString();



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return MoviesJSONdata;
    }

    @Override
    protected void onPostExecute(Object result) {
        super.onPostExecute(result);


        try {

            jsonObject = new JSONObject(result.toString());
            JSONArray jsonArray = jsonObject.getJSONArray("results");

            ImageAdater imageAdater = new ImageAdater();



            for (int i = 0; i < jsonArray.length(); i++) {
                objectsInJSONArray = jsonArray.getJSONObject(i);
                for (int j = 0; j < objectsInJSONArray.length(); j++) {
               imageAdater.moviePoster.add(objectsInJSONArray.getString("poster_path"));
//                    System.out.println("string list content: " + imageAdater.moviePoster.get(j));
                }
            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

ImageAdapter.java

package com.example.pavan.moviesapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by pavan on 3/2/2016.
 */
public class ImageAdater extends BaseAdapter {



   public ArrayList<String> moviePoster = new ArrayList();
    Context context;
    ImageView movie_posters_imageView;
//    View movie_posters_imageView;
    String BASE_POSTER_URL;

//    int[] imageId = {
//            R.drawable.one,
//            R.drawable.two,
//            R.drawable.three,
//            R.drawable.four,
//            R.drawable.five,
//            R.drawable.six
//    };


    public ImageAdater(Context context) {

        this.context = context;
    }

    public ImageAdater() {
    }

    @Override
    public int getCount() {
//        return imageId.length;
        return moviePoster.size();
    }

    @Override
    public Object getItem(int position) {
//        return imageId[position];
        return moviePoster.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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


        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.movie_image, parent, false);
            movie_posters_imageView = (ImageView) convertView.findViewById(R.id.movie_poster_image_view);
        }

        else
            movie_posters_imageView = (ImageView) convertView;

//        movie_posters_imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        movie_posters_imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        movie_posters_imageView.setPadding(8, 8, 8, 8);

        BASE_POSTER_URL = "http://image.tmdb.org/t/p/w185/";


            System.out.println("movie poster : " + moviePoster.get(position));

            System.out.println("poster url : " + BASE_POSTER_URL+moviePoster.get(position));

//        Picasso.with(context).load(imageId[position]).centerCrop().resize(185*2,278*2).into(movie_posters_imageView);

            Picasso.with(context)
                    .load(BASE_POSTER_URL + moviePoster.get(position))
                    .noFade()
                    .resize(185 * 2, 278 * 2)
                    .into(movie_posters_imageView);

        return movie_posters_imageView;
    }


}

movie_image.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/movie_poster_image_view">

</ImageView>

fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:padding="8dp"
    tools:context="com.example.pavan.moviesapp.MainActivityFragment"
    tools:showIn="@layout/activity_main">


    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/movie_grid_view"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:gravity="center">

    </GridView>

</RelativeLayout>

请帮助解决此问题。

谢谢。

0 个答案:

没有答案