2017-03-08 90 views
4

我目前在我的android應用程序中由於「活動無法轉換爲接口」而導致ClassCastException。 這是我的代碼:活動不能轉換爲接口(ClassCastException)

Logcat說異常引發在MovieGridFragment的onAttach部分的行「this.clickListener =(clickInterfaceHelper)context;」。

我的接口:

public interface clickInterfaceHelper { 
void clickOnItem(int id); 
void favoriteMovieItem(int movieId); } 

片段類:

public class MovieGridFragment extends Fragment { 

public clickInterfaceHelper clickListener; 
private int index; 
private GridView movieGridView; 
public List<movieData> movieDataList = new ArrayList<>(); 

public MovieGridFragment() {} //empty constructor 

@Override 
public void onAttach(Context context) { 
    this.clickListener = (clickInterfaceHelper) context; 
    super.onAttach(context); 
} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    if(savedInstanceState != null) { 
     if (!movieDataList.isEmpty()) { 
      movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA")); 
     } 
    } 
    super.onCreate(savedInstanceState); 
} 

在MainActivity:

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    setHasOptionsMenu(true); 


    View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false); 

    movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display); 
    movieAdapter adapter = new movieAdapter(getActivity(),movieDataList); 
    adapter.notifyDataSetChanged(); 
    movieGridView.setAdapter(adapter); 
    movieGridView.setSelection(index); 
    movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      if(clickListener != null) 
        clickListener.clickOnItem(position); 

     } 
    }); 
    return rootView; 
} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    index = movieGridView.getFirstVisiblePosition(); 
    outState.putSerializable("OLDMOVIEDATA",movieData.movieDataArray); 
    super.onSaveInstanceState(outState); 
}} 
and mainactivity: 

public class MainActivity extends AppCompatActivity implements clickInterfaceHelper { 

public static String sorterString = null; 
public static String urlBase = "https://api.themoviedb.org/3/movie/"; 
public static String urlFinal = null; 

RequestQueue requestQueue; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if(savedInstanceState == null) { 
       getSupportFragmentManager().beginTransaction() 
       .add(R.id.activity_container, new MovieGridFragment()) 
       .commit(); 
     movieData.movieDataPosition = 0; 
    } 
    if(savedInstanceState != null) { 
     sorterString = savedInstanceState.getString("SORTER"); 
    } 

    if(savedInstanceState == null) 
     movieData.movieDataPosition = 0; 

    if(sorterString==null) 
     sorterString="popular?"; 
    if(sorterString!="favorite" && sorterString!=null) { 
     if(networkChecker.isNetworkAvailableChecker(this)) { 
      movieRequest(); 
     } 
    } 



} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main_menu_act, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 

    if(id == R.id.m_popularity_action) { 
     if(sorterString != "popular?") { 
      sorterString = "popular?"; 
      if(networkChecker.isNetworkAvailableChecker(this)) 
      movieRequest(); 
     } 
     return true; 
    } 

    if(id == R.id.m_action_voter) { 
     if(sorterString != "top_rated?") { 
      sorterString = "top_rated?"; 
      if(networkChecker.isNetworkAvailableChecker(this)) 
      movieRequest(); 
     } 
     return true; 
    } 

    if(id == R.id.m_favorite_btn) { 
     if(sorterString != "favorite") { 
      SQLiteOpenHelper helper = new movieDataDbHelper(this); 
      SQLiteDatabase database = helper.getReadableDatabase(); 
      Cursor cursor= database.query(movieDataContract.contractEntry.TABLE_NAME, 
        new String[] { 
          movieDataContract.contractEntry.ID, 
          movieDataContract.contractEntry.IMG_PATH},null,null,null,null,null); 
      if(cursor.getCount() == 0) { 
       Toast.makeText(this, "there are no favorite movies yet!",Toast.LENGTH_SHORT).show(); 
      } else { 
       sorterString = "favorite"; 
       showFavoriteFragment(); 
      } 
      database.close(); 
      helper.close(); 
      cursor.close(); 
     } 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

public void showFavoriteFragment() { 
    favoriteMoviesDetailsFragment fragment = new favoriteMoviesDetailsFragment(); 
    try { 
     getFragmentManager().beginTransaction().replace(R.id.activity_container,fragment).commit(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

@Override 
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { 
    outState.putString("SORTER", sorterString); 
    outState.putInt("POSITION",movieData.movieDataPosition); 
    super.onSaveInstanceState(outState, outPersistentState); 
} 

public void movieRequest() { 
     urlFinal = urlBase + sorterString + movieData.apiKey; 
     urlFinal.trim(); 
     requestQueue = Volley.newRequestQueue(this); 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       try { 
        JSONArray array = response.getJSONArray("results"); 
        movieData.movieDataArray = new movieData[array.length()]; 

        for (int i = 0; i < array.length(); i++) { 
         movieData movie = new movieData(); 
         JSONObject jsonObject = array.getJSONObject(i); 
         //movie.setPosition(i); 
         movie.setMovieId(jsonObject.getString("id")); 
         movie.setMovieImagePath(jsonObject.getString("poster_path")); 
         movie.setMovieTitle(jsonObject.getString("original_title")); 
         movie.setMoviePlot(jsonObject.getString("overview")); 
         movie.setMovieVoting(jsonObject.getString("vote_average")); 
         movie.setMovieReleaseDate(jsonObject.getString("release_date")); 
         movieData.movieDataArray[i] = movie; 
        } 

        MovieGridFragment gridFragment = new MovieGridFragment(); 
        gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen 
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
        transaction.replace(R.id.activity_container, gridFragment); 
        try { 
         transaction.commitAllowingStateLoss(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.e("volley", String.valueOf(error)); 
      } 
     } 
     ); 
     requestQueue.add(jsonObjectRequest); 

} 

@Override 
public void clickOnItem(int id) { 
    movieData.movieDataPosition = id; 
    if(movieData.movieDataArray == null) { 
     movieRequest(); 
    } else { 
     Intent intent = new Intent(this, detailsActivity.class); 
     intent.putExtra("FRAGMENT","MOVIE"); 
     startActivity(intent); 
    } 

} 

@Override 
public void favoriteMovieItem(int movieId) { 
    movieData.dbPosition = movieId; 

    Intent intent = new Intent(this,detailsActivity.class); 
    intent.putExtra("FRAGMENT","favorite"); 
    startActivity(intent); 
} } 

回答

3

你可以試試這個

this.clickListener = (MainActivity) getActivity(); 

你得到的FragmentActivity丟在你的MainActivity

編輯:

我建議你在你的片段增加一個功能,如:

public void setListener(clickInterfaceHelper listener) { 
    this.clickListener = listener; 
} 

而在你的活動:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if(savedInstanceState == null) { 
    MovieGridFragment fragment = new MovieGridFragment(); 
    fragment.setListener(this); // some change here 
       getSupportFragmentManager().beginTransaction() 
       .add(R.id.activity_container, fragment) 
       .commit(); 
     movieData.movieDataPosition = 0; 
    } 
    if(savedInstanceState != null) { 
     sorterString = savedInstanceState.getString("SORTER"); 
    } 

    if(savedInstanceState == null) 
     movieData.movieDataPosition = 0; 

    if(sorterString==null) 
     sorterString="popular?"; 
    if(sorterString!="favorite" && sorterString!=null) { 
     if(networkChecker.isNetworkAvailableChecker(this)) { 
      movieRequest(); 
     } 
    } 

} 

.... no relevant functions 


public void movieRequest() { 
     urlFinal = urlBase + sorterString + movieData.apiKey; 
     urlFinal.trim(); 
     requestQueue = Volley.newRequestQueue(this); 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       try { 
        JSONArray array = response.getJSONArray("results"); 
        movieData.movieDataArray = new movieData[array.length()]; 

        for (int i = 0; i < array.length(); i++) { 
         movieData movie = new movieData(); 
         JSONObject jsonObject = array.getJSONObject(i); 
         //movie.setPosition(i); 
         movie.setMovieId(jsonObject.getString("id")); 
         movie.setMovieImagePath(jsonObject.getString("poster_path")); 
         movie.setMovieTitle(jsonObject.getString("original_title")); 
         movie.setMoviePlot(jsonObject.getString("overview")); 
         movie.setMovieVoting(jsonObject.getString("vote_average")); 
         movie.setMovieReleaseDate(jsonObject.getString("release_date")); 
         movieData.movieDataArray[i] = movie; 
        } 

        MovieGridFragment gridFragment = new MovieGridFragment(); 
        gridfragment.setListener(this); // some change here 
        gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray); //hier wird datalist eigentlich zugewiesen 
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
        transaction.replace(R.id.activity_container, gridFragment); 
        try { 
         transaction.commitAllowingStateLoss(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.e("volley", String.valueOf(error)); 
      } 
     } 
     ); 
     requestQueue.add(jsonObjectRequest); 

} 

希望這有助於。

+1

不幸的是,它沒有,仍然得到一個ClassCastException – Torben

+0

@Torben看看我的編輯可以幫助你。 – Cochi

3

傳入的背景不一定是你的活動。它可能是一個包裝它與各種主題和其他覆蓋。你永遠無法假定當傳遞一個Context時,你傳遞了一個Activity。如果您需要對單擊處理程序的引用,請編寫一個setClickHandler函數並明確調用它。

即使它是Activity,應用程序也不知道 - 在那一點上它是一個Context。你需要明確地投它,它可能無法正常工作(並可以在OS,而不是其他的一些版本的工作),由於第1款

0

嘗試將您的接口放入片段類中。

public class MovieGridFragment extends Fragment { 
    public clickInterfaceHelper clickListener; 
    private int index; 
    private GridView movieGridView; 
    public List<movieData> movieDataList = new ArrayList<>(); 

    public MovieGridFragment() {} //empty constructor 

    @Override 
    public void onAttach(Context context) { 
    this.clickListener = (clickInterfaceHelper) context; 
    super.onAttach(context); 
    } 

    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
    if(savedInstanceState != null) { 
     if (!movieDataList.isEmpty()) { 
      movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA")); 
     } 
    } 
    super.onCreate(savedInstanceState); 
    } 

    public interface clickInterfaceHelper { 
    void clickOnItem(int id); 
    void favoriteMovieItem(int movieId); 
    } 
} 
+0

,仍然給我一個崩潰 – Torben

相關問題