我编写了一个具有以下功能的代码:当我按下一个按钮时,它会启动一个新活动,但是如果我运行该代码并按下按钮,则会出现以下错误:
无法开始活动 ComponentInfo {com.koddev.instagramtest / com.koddev.instagramtest.News.NewsActivity}: java.lang.NullPointerException:尝试调用虚拟方法'void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout $ OnRefreshListener)'
这是我的NewsActivity的代码:
package com.koddev.instagramtest.News;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.koddev.instagramtest.News.api.ApiClient;
import com.koddev.instagramtest.News.api.ApiInterface;
import com.koddev.instagramtest.News.models.Article;
import com.koddev.instagramtest.News.models.News;
import com.koddev.instagramtest.R;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
public static final String API_KEY = "8c330acf07f946aeb5848800508096ca";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Article> articles = new ArrayList<>();
private Adapter adapter;
private String TAG = NewsActivity.class.getSimpleName();
private TextView topHeadline;
private SwipeRefreshLayout swipeRefreshLayout;
private RelativeLayout errorLayout;
private ImageView errorImage;
private TextView errorTitle, errorMessage;
private Button btnRetry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
topHeadline = findViewById(R.id.topheadelines);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(NewsActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(false);
onLoadingSwipeRefresh("");
errorLayout = findViewById(R.id.errorLayout);
errorImage = findViewById(R.id.errorImage);
errorTitle = findViewById(R.id.errorTitle);
errorMessage = findViewById(R.id.errorMessage);
btnRetry = findViewById(R.id.btnRetry);
}
public void LoadJson(final String keyword){
errorLayout.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(true);
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
String country = Utils.getCountry();
String language = Utils.getLanguage();
Call<News> call;
if (keyword.length() > 0 ){
call = apiInterface.getNewsSearch(keyword, language, "publishedAt", API_KEY);
} else {
call = apiInterface.getNews(country, API_KEY);
}
call.enqueue(new Callback<News>() {
@Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body().getArticle() != null){
if (!articles.isEmpty()){
articles.clear();
}
articles = response.body().getArticle();
adapter = new Adapter(articles, NewsActivity.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
initListener();
topHeadline.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
} else {
topHeadline.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
String errorCode;
switch (response.code()) {
case 404:
errorCode = "404 not found";
break;
case 500:
errorCode = "500 server broken";
break;
default:
errorCode = "unknown error";
break;
}
showErrorMessage(
R.drawable.no_result,
"No Result",
"Please Try Again!\n"+
errorCode);
}
}
@Override
public void onFailure(Call<News> call, Throwable t) {
topHeadline.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
showErrorMessage(
R.drawable.oops,
"Oops..",
"Network failure, Please Try Again\n"+
t.toString());
}
});
}
private void initListener(){
adapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.img);
Intent intent = new Intent(NewsActivity.this, NewsDetailActivity.class);
Article article = articles.get(position);
intent.putExtra("url", article.getUrl());
intent.putExtra("title", article.getTitle());
intent.putExtra("img", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("author", article.getAuthor());
Pair<View, String> pair = Pair.create((View)imageView, ViewCompat.getTransitionName(imageView));
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
NewsActivity.this,
pair
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(intent, optionsCompat.toBundle());
}else {
startActivity(intent);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryHint("Search Latest News...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (query.length() > 2){
onLoadingSwipeRefresh(query);
}
else {
Toast.makeText(NewsActivity.this, "Type more than two letters!", Toast.LENGTH_SHORT).show();
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
@Override
public void onRefresh() {
LoadJson("");
}
private void onLoadingSwipeRefresh(final String keyword){
swipeRefreshLayout.post(
new Runnable() {
@Override
public void run() {
LoadJson(keyword);
}
}
);
}
private void showErrorMessage(int imageView, String title, String message){
if (errorLayout.getVisibility() == View.GONE) {
errorLayout.setVisibility(View.VISIBLE);
}
errorImage.setImageResource(imageView);
errorTitle.setText(title);
errorMessage.setText(message);
btnRetry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onLoadingSwipeRefresh("");
}
});
}
}
这就是我的main_activity的代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/colorBackground">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/topheadelines"
android:textColor="@color/colorTextTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Top Headlines"
android:fontFamily="sans-serif-light"
android:textSize="17sp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="10dp"
android:visibility="invisible"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
<include layout="@layout/error"/>
</android.support.design.widget.CoordinatorLayout>
问题出在哪里?