java - 使用互联网调用以 Java 编码的 Android 应用程序不显示数据

标签 java android

我正在为在线类(class)编写应用程序。该应用程序应该以网格模式显示数据,可以通过按下菜单中的按钮来更新。我以为我写完了代码并运行了应用程序,但我看到的只是一个白色背景和一个我写的菜单选项。我正在删除问题中的 API 代码,它在我的代码中没有丢失

主要 Activity “启动器 Activity ”

public class MainMenu extends AppCompatActivity {

MovieAdapter mV = new MovieAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    updateMovie();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.action_refresh){
        updateMovie();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

void updateMovie(){
    FetchMovieTask movieTask = new FetchMovieTask();
    movieTask.execute();
}
@SuppressLint("StaticFieldLeak")
class FetchMovieTask extends AsyncTask<Void,Void,List<String>>{
    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

    @Override
    protected List<String> doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String movieJsonStr;

        try{
            URL url = new URL("http://api.themoviedb.org/3/discover/movie?" +
                    "sort_by=popularity.desc&api_key=InsertAPIHERe");

            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if(inputStream == null){
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while((line = reader.readLine())!= null){
                buffer.append(line).append("\n");
            }
            if(buffer.length() == 0){
                return null;
            }
            movieJsonStr = buffer.toString();
        }catch (IOException e){
            Log.e(LOG_TAG,"Error",e);
            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 getMovieDataFromJson(movieJsonStr);
        }catch (JSONException j){
            Log.e(LOG_TAG,"JSON Error", j);
        }
        return null;
    }

    private List<String>getMovieDataFromJson(String mVJsonStr)
        throws JSONException{
        JSONObject movieJson = new JSONObject((mVJsonStr));
        JSONArray movieArray = movieJson.getJSONArray("results");
        List<String> urls = new ArrayList<>();
        for (int i = 0;i < movieArray.length();i++){
            JSONObject movie = movieArray.getJSONObject(i);
            urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
        }
        return urls;
    }

    @Override
    protected void onPostExecute(List<String> strings) {
        mV.replace(strings);
    }
}

GridView 类

public class MovieFragment extends Fragment{


MovieAdapter mA = new MovieAdapter(getActivity());

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_movie,container,false);
    GridView mL = (GridView)rootView.findViewById(R.id.movie_grid);
    mL.setAdapter(mA);
    return rootView;
}
}

适配器类

public class MovieAdapter extends BaseAdapter{

private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();

MovieAdapter(Context context) {
    this.context = context;
    Collections.addAll(urls);
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null){
        convertView = new ImageView(context);
    }
    ImageView iV = (ImageView)convertView;

    String url = (String) getItem(position);

    Log.e(LOG_TAG,"URL" + url);
    Picasso.with(context).load(url).into(iV);
    return convertView;
}

void replace(List<String> urls){
    this.urls.clear();
    this.urls.addAll(urls);
    notifyDataSetChanged();
}

有了这三个类,我以为我拥有了应用程序运行所需的一切,但事实并非如此。我是否遗漏了一段代码来将流入的信息连接到 GridView ,或者我的逻辑是否存在缺陷?

没有任何错误消息,应用程序正在运行,但没有任何功能。

编辑

activity_main_xml

 <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment"
        android:name="com.example.djadu.discovermovies.MovieFragment"
        tools:layout="@layout/fragment_movie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

电影 fragment

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/movie_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MovieFragment"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">
</GridView>

最佳答案

可能有几个原因。最明显的是您在 MainMenuMovieFragment 类中使用了不同的 MovieAdapter 实例。您向 MainMenu 中的适配器发出请求并设置数据,但向 GridView 附加了在 MovieFragment 中创建的另一个 MovieAdapter 实例.如果您想在 MainMenu 中控制 MovieAdapter,您需要将其共享给 MovieFragment

主菜单类

...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    ((MyFragment) getFragmentManager().findFragmentById(R.id.fragment)).setAdapter(mV);
    updateMovie();
}
...

MovieFragment 类

...
GridView mGridView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_movie, container, false);
    mGridView = view.findViewById(R.id.movie_grid);
    return view;
}

public void setAdapter(BaseAdapter adapter) {
    mGridView.setAdapter(adapter);
}
...

关于java - 使用互联网调用以 Java 编码的 Android 应用程序不显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665507/

相关文章:

java - 更新 recyclerview 中帖子的评论计数

android - 将数组列表转换为稀疏数组

java - 如何根据 JavaRDD<ObjectHandler> 对象中的特定列查找不同元素?

Java Play Framework 嵌套模板 - 参数传递

java - 将项目 id 从项目上下文附加到 JIRA web-item url

Android 低功耗蓝牙特性通知计数限制 : does this vary by device?

android - 如何旋转照片而不丢失Exif和元数据?

java - 运行 "empty"Undertow 时每秒 HTTP 请求数的限制因素是什么?

java - 如何使任何 pdf 文件中的水印文本不可选择?

android - Kotlin MediaPlayer 简单使用