当我按下后退按钮时,notifyDataSetChanged()
上的RecyclerView
出错了。这是代码:
MainActivity.java
class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public List<Article> articleList;
public RecyclerView recyclerView;
public RecyclerViewAdapter adapter;
ArrayList<String> my_list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
initData();
adapter = new RecyclerViewAdapter(articleList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
private void initData() {
articleList = new ArrayList<>();
queryArticle();
}
public void saveArticle(String title, String desc) {
//ab is a instance for class Article_Bmob
ab.setTitle(title);
ab.setDesc(desc);
ab.save(new SaveListener<String>() {
@Override
public void done(String s, BmobException e) {
if(e == null) {
} else {
e.printStackTrace();
}
}
});
}
}
WriteArticle.java(错误文件)
public class WriteArticle extends AppCompatActivity {
MainActivity mainActivity;
private String art_title, art_desc;
private EditText edt_title, edt_desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_article);
edt_title = (EditText) findViewById(R.id.w_art_title);
edt_desc = (EditText) findViewById(R.id.w_art_desc);
Button btn_send = (Button) findViewById(R.id.send_article);
mainActivity = new MainActivity();
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
art_title = edt_title.getText().toString();
art_desc = edt_desc.getText().toString();
if (art_title.isEmpty()) {
Snackbar.make(view, "R.String.xxx", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else if (art_desc.isEmpty()) {
Snackbar.make(view, "R.String.xxx", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
mainActivity.saveArticle(art_title, art_desc);
mainActivity.adapter.notifyDataSetChanged();
finish();
}
}
});
}
错误:
java.lang.NullPointerException: Attempt to invoke virtual method
'void com.myapplication.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference
at com.myapplication.WriteArticle$1.onClick(WriteArticle.java:52)
我该如何解决这个问题?
答案 0 :(得分:4)
在您的MainActivity中
public static MainActivity mactivity;
public static MainActivity getinstance(){
return mactivity;
}
在您的WriteArticle活动中
MainActivity mainActivity;
并将其用作
mainActivity.getinstance.saveArticle(art_title, art_desc);
mainActivity.getinstance.adapter.notifyDataSetChanged();