当前位置: 首页 > 知识库问答 >
问题:

无法通过改造实现从api将数据提取到RecycerView中

干照
2023-03-14

我正在与Android Studio工作,我有一个问题与我的简单项目,它使用一个API。我正在尝试通过改型从TVMazeAPI http://api.tvmaze.com获取图像和文本。这个想法是通过SearchView实现搜索功能。你输入一些标题,应用程序会给出http://api.tvmaze.com/search/shows?q=girls的一些结果,当我试图搜索一些显示时,图像和文本不会显示,应用程序崩溃

调试器显示如下:致命异常:main process:com.kate_lebedeva.searchthesHow,PID:3815 java.lang.nullpointerException:试图在com.kate_lebedeva.searchtheshow.movieAdapter.getItemCount(MovieAdapter.java:49)的空对象引用上调用接口方法'int java.util.list.size()'

该错误与适配器中的以下行有关:

@Override
    public int getItemCount() {

        if(movieList != null){
            return movieListFiltered.size();
        } else {
            return 0;
        }
    }

我处理不了这个问题。我在这个领域是全新的。请给我一个建议。

应用程序分级

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.github.bumptech.glide:glide:4.3.1'
    implementation 'com.android.support:support-v4:28.0.0'
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kate_lebedeva.searchtheshow">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme">

    </android.support.design.widget.AppBarLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">
        </android.support.v7.widget.RecyclerView>
    </LinearLayout>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
  >

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:orientation="horizontal"
        android:padding="8dp">

        <ImageView
            android:id="@+id/image"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_marginRight="8dp"
            android:scaleType="fitXY" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Title"
                android:textSize="16sp"
                android:textStyle="bold"
                />

            <TextView
                android:id="@+id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:ellipsize="end"
                android:maxLines="4"
                android:text="summary"
                />
    </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("search/shows?q=girls")
    Call <List<Movie>> getMovies();
}
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TvMazeApiClient {

        public static String BASE_URL ="http://api.tvmaze.com/";
        private static Retrofit retrofit;
        public static Retrofit getClient(){
            if(retrofit == null){
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }

}
 public class MainActivity extends AppCompatActivity {
    private SearchView searchView;
    private RecyclerView recyclerView;
    private MovieAdapter movieAdapter;
    private List<Movie> movieList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        movieAdapter = new MovieAdapter();
        recyclerView.setAdapter(movieAdapter);

        movieList = new ArrayList<>();
        ApiInterface apiService = TvMazeApiClient.getClient().create(ApiInterface.class);
        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                if(movieList != null) {
                movieList = response.body();
                Log.d("TAG", "Response = " + movieList);
                movieAdapter.setMovieList(getApplicationContext(), movieList);
            }
            else{
                Toast.makeText(MainActivity.this,"error", Toast.LENGTH_SHORT).show();
            }
            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Response = "+t.toString());
                Toast.makeText(MainActivity.this,t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.action_search)
                .getActionView();
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                movieAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                movieAdapter.getFilter().filter(query);
                return false;
            }
        });
        return true;
    }

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

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
            return;
        }
        super.onBackPressed();
    }}

适配器:

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MyViewHolder> implements Filterable {

    private List<Movie> movieList;
    private List<Movie> movieListFiltered;
    private Context context;

    public void setMovieList(Context context,final List<Movie> movieList){
        this.context = context;
        this.movieList = movieList;
        this.movieListFiltered = movieList;
    }

    @Override
    public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MovieAdapter.MyViewHolder holder, int position) {
        holder.title.setText(movieListFiltered.get(position).getTitle());
        Glide.with(context).load(movieList.get(position).getImageUrl()).apply(RequestOptions.centerCropTransform()).into(holder.image);
    }

    @Override
    public int getItemCount() {

        if(movieList != null){
            return movieListFiltered.size();
        } else {
            return 0;
        }
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                String charString = charSequence.toString();
                if (charString.isEmpty()) {
                    movieListFiltered = movieList;
                } else {
                    List<Movie> filteredList = new ArrayList<>();
                    for (Movie movie : movieList) {
                        if (movie.getTitle().toLowerCase().contains(charString.toLowerCase())) {
                            filteredList.add(movie);
                        }
                    }
                    movieListFiltered = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = movieListFiltered;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                movieListFiltered = (ArrayList<Movie>) filterResults.values;

                notifyDataSetChanged();
            }
        };
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView title;
        ImageView image;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            image = (ImageView)view.findViewById(R.id.image);
        }
    }
}

movie.java

public class Movie {

    private String title;

    private String imageUrl;

    public Movie(String title, String imageUrl) {
        this.title = title;
        this.imageUrl = imageUrl;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

共有1个答案

唐沈义
2023-03-14

您应该添加检查movieListFiltered

if(movieList != null && movieListFiltered!=null){
   return movieListFiltered.size();
}
 类似资料:
  • 问题内容: 我一直在尝试使用nativescript创建一个android应用程序。我正在使用fetch模块从服务器获取响应。当我尝试从 **httpbin.org/get 获取响应时,可以。但是当我尝试获取响应时从我的本地服务器上,我收到 网络请求失败。** 错误。 发送到httpbin.org/get- 发送到localhost:8000 / api- 当我尝试通过请求模块在纯node.js中

  • 这是我收到的错误: 请求的资源上不存在“< code > Access-Control-Allow-Origin ”标头。因此,不允许访问源“https://s.codepen.io”。如果不透明响应满足您的需要,请将请求的模式设置为' < code>no-cors ',以便在禁用cors的情况下获取资源。 我将模式设置为但仍然没有运气。

  • 我正在学习一门改造课程,在这门课程中,我创建了一个带有api的小型后端,其中我有一个POST方法来执行教师登录。在课程中,他所做的是创建一名教师,并使用set方法向他传递电子邮件和密码,这是该方法在API中接收的内容。 我希望这样做,在电话改造中,您可以直接通过此电子邮件和密码,我已通过以下方式完成: 这就是我的模范老师: 最后,我呼吁进行以下改造: 然而,当我运行应用程序并通过表单传递电子邮件和

  • main.java Controller/Controller.java 模型/ConnectDB.java 查看/fxmlSample.fxml 错误: 错误:(64,9)Java:类Sample.Controller.Controller中的method initData无法应用于给定类型;必需:javafx.event.actionevent找到:没有参数原因:实际和正式参数列表的长度不同

  • 我一直在尝试使用nativescript创建一个android应用程序。我正在使用fetch模块从服务器获取响应。当我试图从httpbin获得响应时。org/get,没关系。但当我试图从本地服务器获取响应时,网络请求失败。错误 发送到httpbin。组织/获取- 发送到本地主机:8000/api- 当我尝试从纯节点中的localhost:8000/api获取响应时。js通过请求模块。它工作得很好。