2016-03-01 91 views
0

我一直在努力解決這個問題,當我點擊我的應用程序中的刷新按鈕時,圖像無法加載到屏幕上。當我點擊刷新按鈕時,圖像從不出現

這是DataFragment文件,當我構建這個應用程序時沒有錯誤。

package com.example.popularmovis; 

    import android.app.Fragment; 
    import android.content.SharedPreferences; 
    import android.net.Uri; 
    import android.os.AsyncTask; 
    import android.os.Bundle; 
    import android.preference.PreferenceManager; 
    import android.util.Log; 
    import android.view.LayoutInflater; 
    import android.view.Menu; 
    import android.view.MenuInflater; 
    import android.view.MenuItem; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.GridView; 
    import android.os.AsyncTask; 

    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.URL; 
    import java.util.jar.JarException; 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public class DataFragment extends Fragment { 

     public ImageAdapter display; 

     public DataFragment() { 
     } 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      // Add this line in order for this fragment to handle menu events. 
      setHasOptionsMenu(true); 
     } 

     @Override 
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
      inflater.inflate(R.menu.datafragment_menu, menu); 
     } 

     @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_refresh) { 
       FetchMovieData movieData = new FetchMovieData(); 
       movieData.execute(); 

       return true; 
      } 

      return super.onOptionsItemSelected(item); 
     } 

     @Override 
     public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      display = new ImageAdapter(rootView.getContext()); 
      GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies); 
      gridView.setAdapter(display); // uses the view to get the context instead of getActivity(). 
      return rootView; 

     } 

     public class FetchMovieData extends AsyncTask<Void, Void, String[]>{ 
      private final String LOG_TAG = FetchMovieData.class.getSimpleName(); 

      private String[] extractdisplayFromJason(String jasnData) 
               throws JSONException{ 
       //These jason display need to be extracted 
       final String movie_results = "results"; 
       final String movie_poster = "poster_path"; 

       JSONObject movieData = new JSONObject(jasnData); 
       JSONArray movieArray = movieData.getJSONArray(movie_results); 
       String[] posterAddreess = new String[movieArray.length()]; 

       //Fill ther posterAddreess with the URL to display 
       for(int j=0; j < movieArray.length(); j++){ 

        String posterPath; 
        JSONObject movieArrayItem = movieArray.getJSONObject(j); 
        posterPath = movieArrayItem.getString(movie_poster); 
        posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath; 
       } 
       for (String s : posterAddreess) { 
        Log.v(LOG_TAG, "Thumbnail Links: " + s); 
       } 
       return posterAddreess; 
      } 

      @Override 
      protected String[] doInBackground(Void... params) { 

       HttpURLConnection urlConnection = null; 
       BufferedReader reader = null; 
       String JsonData = null; 

       String country = "US"; 
       String rating = "R"; 
       String sort = "popularity.desc"; 
       String apiKey = ""; 
       //building the URL for the movie DB 

       try { 
        //building the URL for the movie DB 
        final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?"; 
        final String Country_for_release = "certification_country"; 
        final String Rating = "certification"; 
        final String Sorting_Order = "sort_by"; 
        final String Api_Id = "api_key"; 

        Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon() 
          .appendQueryParameter(Country_for_release, country) 
          .appendQueryParameter(Rating, rating) 
          .appendQueryParameter(Sorting_Order, sort) 
          .appendQueryParameter(Api_Id, apiKey) 
          .build(); 

        //Converting URI to URL 
        URL url = new URL(buildUri.toString()); 
        Log.v(LOG_TAG, "Built URI = "+ buildUri.toString()); 


        //Create the request to the Movie Database 
        urlConnection = (HttpURLConnection) url.openConnection(); 
        urlConnection.setRequestMethod("GET"); 
        urlConnection.connect(); 

        //Read the input from the database into string 
        InputStream inputStream = urlConnection.getInputStream(); 

        //StringBuffer for string Manipulation 
        StringBuffer buffer = new StringBuffer(); 


        if (inputStream == null) { 
         // Nothing to do. 
         return null; 
        } 
        reader = new BufferedReader(new InputStreamReader(inputStream)); 
        String line; 
        while ((line = reader.readLine()) != null) { 
         // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) 
         // But it does make debugging a *lot* easier if you print out the completed 
         // buffer for debugging. 
         buffer.append(line + "\n"); 
        } 
        if (buffer.length() == 0) { 
         // Stream was empty. No point in parsing. 
         return null; 
        } 
        JsonData = buffer.toString(); 
        Log.v(LOG_TAG,"Forecaast Jason String" + JsonData); 
       } catch (IOException e) { 
        // If the code didn't successfully get the weather data, there's no point in attemping 
        // to parse it. 
        return null; 
       } finally { 
        if (urlConnection != null) { 
         urlConnection.disconnect(); 
        } 
        if (reader != null) { 
         try { 
          reader.close(); 
         } catch (final IOException e) { 
          Log.e(LOG_TAG, "Error closing stream", e); 
         } 
        } 
        try { 
         return extractdisplayFromJason(JsonData); 
        } catch (JSONException e) { 
         Log.e(LOG_TAG, e.getMessage(), e); 
         e.printStackTrace(); 
        } 
       } 
       return null; 
      } 
      protected void onPostExecute(String[] posterAddreess) { 

        for (String poster : posterAddreess) { 
         display.addItem(poster); 
        } 


      } 
     } 
    } 

這個ImageAdapter代碼

package com.example.popularmovis; 

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

import com.example.popularmovis.R; 
import com.squareup.picasso.Picasso; 

import java.util.ArrayList; 

public class ImageAdapter extends BaseAdapter { 
    private Context mContext; 
    public ArrayList<String> images = new ArrayList<String>(); 
    public ImageAdapter(Context c){ 
     mContext = c; 
    } 

    @Override 
    public int getCount(){ 
     return images.size(); 
    } 

    @Override 
    public Object getItem(int position){ 
     return images.get(position); 
    } 

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

    public View getView(int position, View convertView, ViewGroup parent){ 
     ImageView imageview; 
     if (convertView == null){ 
      imageview = new ImageView(mContext); 
      imageview.setPadding(0, 0, 0, 0); 
      //imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
      imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
      imageview.setAdjustViewBounds(true); 
     } else { 
      imageview = (ImageView) convertView; 
     } 

     Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview); 
     return imageview; 
    } 

    /* 
    Custom methods 
    */ 
    public void addItem(String url){ 
     images.add(url); 
    } 

    public void clearItems() { 
     images.clear(); 
    } 
} 

回答

2

當你在這樣的onCreate方法使用,這意味着該對象是本地的方法,不能以其他方式使用。

ImageAdapter display = new ImageAdapter(rootView.getContext()); 

首先創建一個全局類的成員變量

private ImageAdapter display; 

那麼你的onCreate方法內做到這一點

display = new ImageAdapter(rootView.getContext()); 
+0

現在我沒有得到的異常,但圖像不會出現在應用程序中。 – kanduken

+0

你的onCreateView方法中仍然有這一行 - ImageAdapter display = new ImageAdapter(rootView.getContext());將其更改爲 - display = new ImageAdapter(rootView.getContext()); – Inducesmile

+0

我按照您所描述的方式編輯了代碼,現在圖像沒有出現在屏幕上 – kanduken

相關問題