我正在开发一款Android应用,可以按照moviedb.org api中最热门或最受欢迎的电影来分类电影。应用程序应该在更改设置时从服务器获取新数据。这不起作用。这是我的代码,请帮助我完成它:
//MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new MainActivityFragment()).commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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_main, 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) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
//SettingsActivity.java
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
public void bindPreferenceSummaryToValue(Preference preference){
preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue=value.toString();
if(preference instanceof ListPreference){
ListPreference listPreference=(ListPreference)preference;
int prefIndex=listPreference.findIndexOfValue(stringValue);
if(prefIndex>=0){
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
}else {
preference.setSummary(stringValue);
}
return true;
}
//MainActivityFragment.java
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_main, container, false);
if (getActivity()!=null){
ArrayList<String>arrayList=new ArrayList<String>();
PosterAdapter imageAdapter=new PosterAdapter(getActivity(),arrayList,deviceWidth);
imageGridView=(GridView)rootView.findViewById(R.id.image_grid_view);
imageGridView.setColumnWidth(deviceWidth);
imageGridView.setAdapter(imageAdapter);
}
imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra("overview", overview.get(position))
.putExtra("poster", images.get(position))
.putExtra("title", title.get(position))
.putExtra("date", date.get(position))
.putExtra("rating", rating.get(position));
startActivity(intent);
}
});
return rootView;
}
private class PreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener{
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
imageGridView.setAdapter(null);
onStart();
}
}
@Override
public void onStart(){
super.onStart();
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
preferenceChangeListener=new PreferenceChangeListener();
sharedPreferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_most_popular)){
sortByPopular=true;
}else if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_top_rated)){
sortByPopular=false;
}
ImageLoader imageLoader=new ImageLoader();
if (isInternetAvailable()) {
imageLoader.execute();
Log.v(LOG_TAG,"async task completed");
}else {
TextView textView=new TextView(getActivity());
RelativeLayout relativeLayout=(RelativeLayout)getActivity().findViewById(R.id.fragment_layout);
textView.setText("There is no Internet service");
if (relativeLayout.getChildCount()==1){
relativeLayout.addView(textView);
}
imageGridView.setVisibility(GridView.GONE);
}
}
public boolean isInternetAvailable(){
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return networkInfo !=null&&networkInfo.isConnected();
}
public class ImageLoader extends AsyncTask<Void,Void,ArrayList<String>>{
@Override
protected ArrayList<String> doInBackground(Void... params) {
while (true){
try {
images=new ArrayList<>(Arrays.asList(getPathsFromURL(sortByPopular)));
return images;
}catch (Exception e){
continue;
}
}
}
@Override
protected void onPostExecute(ArrayList<String>results){
if (results!=null&&getActivity()!=null){
PosterAdapter posterAdapter=new PosterAdapter(getActivity(),results,deviceWidth);
imageGridView.setAdapter(posterAdapter);
}
}
public String[] getPathsFromURL(boolean sorting){
while (true){
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
String JSONResult;
try {
if (sortByPopular){
url = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=281ad0257e71bca17a21b42c9fee7304";
}else {
url="http://api.themoviedb.org/3/discover/movie?sort_by=vote_average.desc&vote_count.gte=500&api_key=281ad0257e71bca17a21b42c9fee7304";
}
URL url1=new URL(url);
httpURLConnection=(HttpURLConnection)url1.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream=httpURLConnection.getInputStream();
StringBuffer stringBuffer=new StringBuffer();
if (inputStream==null){
return null;
}
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String data;
while ((data=bufferedReader.readLine())!=null){
stringBuffer.append(data+"\n");
}
if (stringBuffer.length()==0){
return null;
}
JSONResult=stringBuffer.toString();
Log.v(LOG_TAG,JSONResult);
try {
overview=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "overview")));
title=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "original_title")));
rating=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "vote_average")));
date=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "release_date")));
return getDataFromJSON(JSONResult);
}catch (JSONException e){
return null;
}
}catch (Exception e){
continue;
}finally {
if (httpURLConnection!=null){
httpURLConnection.disconnect();
}
if (bufferedReader!=null){
try {
bufferedReader.close();
}catch (final IOException e){
}
}
}
}
}
}
public String[] getStringsFromAPI(String JSONStringParameter,String parameter) throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
if (parameter.equals("vote_average")){
Double decimalNumber=poster.getDouble("vote_average");
String userRating=Double.toString(decimalNumber)+"/10";
results[i]=userRating;
}
String posterPath=poster.getString(parameter);
results[i]=posterPath;
}
return results;
}
public String[] getDataFromJSON(String JSONStringParameter)throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
String posterPath=poster.getString("poster_path");
results[i]=posterPath;
}
return results;
}
//PosterAdapter.java
private Context context;
private ArrayList<String> arrayList;
private int posterWidth;
public PosterAdapter(Context c,ArrayList<String> filePaths,int a){
context=c;
arrayList=filePaths;
posterWidth=a;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView==null){
image=new ImageView(context);
}else {
image=(ImageView)convertView;
}
String url = "http://image.tmdb.org/t/p/w185" + arrayList.get(position);
Picasso.with(context).load(url).into(image);
return image;
}
提前谢谢
答案 0 :(得分:0)
我与其他开发人员交谈,看来我的代码是准确的,并且有一个其他开发人员试图找出的错误。我会告诉你们。谢谢你的帮助。