java - RecyclerViewAdapter.notifyDataSetChanged() en una referencia de objeto nulo
android nullpointerexception (1)
notifyDataSetChanged()
un error con notifyDataSetChanged()
en RecyclerView
cuando notifyDataSetChanged()
el botón Atrás. Este es el código:
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 (archivo de error)
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();
}
}
});
}
Y el error:
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)
¿Como puedo resolver esto?
En su actividad principal
public static MainActivity mactivity;
public static MainActivity getinstance(){
return mactivity;
}
En su actividad WriteArticle
MainActivity mainActivity;
Y úsalo como
mainActivity.getinstance.saveArticle(art_title, art_desc);
mainActivity.getinstance.adapter.notifyDataSetChanged();