Cannot start new activity in the AsyncTask - java

Here is my login activity. The loginButtonListener declares a AsyncTask variable to work on the verify info on remote MySQL
public class LoginActivity extends AppCompatActivity implements AsyncResponse {
private EditText editText_email;
private EditText editText_password;
private Button button_login;
private Button button_register;
#Override
protected void onCreate(Bundle savedInstanceState) {
BackgroundWorker worker = new BackgroundWorker(LoginActivity.this);
loginButtonListener();
registerButtonListener();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void loginButtonListener(){
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String type = "login";
String email = editText_email.getText().toString();
String password = editText_password.getText().toString();
BackgroundWorker worker = new BackgroundWorker(LoginActivity.this);
worker.execute(type, email, password);
}
});
}
}
Here is my backgroundwork.class
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
public AsyncResponse delegate = null;
BackgroundWorker (Context ctx) {
context = ctx;
}
// Http MySQL stuffs
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
//LoginActivity.get=result;
//delegate.processFinish(result);
alertDialog.setMessage(result);
alertDialog.show();
if(result.contains("Remote login success")){
Intent i = new Intent(LoginActivity.this, MainpanelActivity.class); // ERROR HERE, FIRST ARGUMENT IS NOT AN ENCLOSING CLASS
i.putExtra("email", this.email); /
startActivity(i);
}
}
}
However, I got a "xxx is not an enclosing class error" in the onpostexecute() when I try starting a new activity (login success, jumps to another activity)

you can call the activity from following code,
if(result.contains("Remote login success")){
Intent i = new Intent(context, MainpanelActivity.class); //use context here
i.putExtra("email", this.email);
startActivity(i);
}

Related

Firebase signOut() method or AuthListener not working as intended

I have a Fragment with a signOut button in my android studio app that is supposed to log the user out of his account and then redirect him back to the login page. I've tried several things so far and looked at every thread I could find but nothing is working. There is no error, just no reaction at all.
First thing I've tried is this:
public class PreferenceFragment extends Fragment {
private PreferenceViewModel preferenceViewModel;
private FragmentPreferenceBinding binding;
private Button btnSignOut;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authListener;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
preferenceViewModel =
new ViewModelProvider(this).get(PreferenceViewModel.class);
auth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_preference, container, false);
btnSignOut = (Button) view.findViewById(R.id.sign_out);
binding = FragmentPreferenceBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textPreference;
preferenceViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = auth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
}
};
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
}
});
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
This is my LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
First I thought it might be the signOut() that isn't working as intended or logging me back in automatically. But if I put the signOut() into the onStop() method of the MainActivity it is working, obviously only when I close the app:
#Override
public void onStop() {
super.onStop();
FirebaseAuth.getInstance().signOut();
}
then I thought the program might not be calling the same FirebasAuth instance so I've tried calling the FirebaseAuth instance from the MainActivity to the same effect:
(MainActivity)getActivity()).auth.signOut();
I've tried several other things like putting the authListener in the MainActivity or removing the code calling the FirebasAuth instance at the start of the LoginActivity, always to the same effect. Maybe it has to do with my startActivity but I'm not sure how to do it differently. Thanks in advance for any help.

How can I refresh a RecyclerView when I add data using Retrofit into database?

I'm making some tests using Retrofit2 to show a list of users and to create a new user. My problem is how to refresh a RecyclerView after adding a user with a POST request to my api.
I have a MainActivity that make the GET request to a Laravel api. Then, I make a CreateUserActivity that has the form for create a new user. After I click on Create User button, I finish that activity to show the MainActivity, but I want to update the RecyclerView with the new user.
CreateUserActivity.java
public class CreateUserActivity extends AppCompatActivity {
private TextInputEditText inputFirstName;
private TextInputEditText inputLastName;
private TextInputEditText inputEmail;
private TextInputEditText inputPassword;
private Button saveButton;
private ApiService api;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputFirstName = (TextInputEditText) findViewById(R.id.txtInputFirstName);
inputLastName = (TextInputEditText) findViewById(R.id.txtInputLastName);
inputEmail = (TextInputEditText) findViewById(R.id.txtInputEmail);
inputPassword = (TextInputEditText) findViewById(R.id.txtInputPassword);
saveButton = (Button) findViewById(R.id.btnCreateUser);
api = RetroClient.getApiService();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstName = inputFirstName.getText().toString().trim();
String lastName = inputLastName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setPassword(password);
user.setGenreId(1);
if (!TextUtils.isEmpty(firstName)) {
sendPost(user);
}
}
});
}
private void sendPost(User user) {
Call<User> call = api.saveUser(user);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if(response.isSuccessful()) {
String message = "Usuario creado correctamente";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
System.out.println("Fail");
}
});
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CreateUserActivity.class);
startActivityForResult(intent, 1);
}
});
ApiService api = RetroClient.getApiService();
Call<UsersList> call = api.getUsers();
call.enqueue(new Callback<UsersList>() {
#Override
public void onResponse(Call<UsersList> call, Response<UsersList> response) {
if (!response.isSuccessful()) {
return;
}
usersList = response.body().getUser();
usersRecyclerView = (RecyclerView) findViewById(R.id.dataTable);
usersAdapter = new UsersAdapter(usersList);
RecyclerView.LayoutManager usersLayoutManager = new LinearLayoutManager(getApplicationContext());
usersRecyclerView.setLayoutManager(usersLayoutManager);
usersRecyclerView.setItemAnimator(new DefaultItemAnimator());
usersRecyclerView.setAdapter(usersAdapter);
}
#Override
public void onFailure(Call<UsersList> call, Throwable t) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
usersAdapter.notifyDataSetChanged();
}
}
So create a setUserList function in your UserAdapter class and inside it use notifyDatabaseChange() after setting the userlist inside adapter to the new list.
public void setUserList(List<UserList> userList) {
userList.clear();
this.userList = userList;
notifyDataSetChanged();
}

Activity intent not working on button click

Hello Stackoverflow community!
Recently, a strange error occured to me. It is with a button in my app. When i press it there is nothing happening. No errors, or crashes but also Intent is not functioning. The transition to DeleteAccountActivity is not happening. I don't know why is this happening. The intent which I am using is very simple(passes nothing). Please help me
AccountSettingsActivity.java
public class AccountSettingsActivity extends AppCompatActivity {
private static final String TAG = "AccountSettingsActivity";
private static final int ACTIVITY_NUM = 4;
private String user_id;
private Context mContext;
public SectionsStatePagerAdapter pagerAdapter;
private ViewPager mViewPager;
private RelativeLayout mRelativeLayout;
private Button mDelete;
User mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
}
});
}
private void deleteAccounts(){
/* DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference("users").child(user_id);
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference("user_photos").child(user_id);
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference("comments").child(user_id);
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();*/
// getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_users))
// .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(mUser.getUser_id())
.removeValue();
/* FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_followers))
.child(mUser.getUser_id())
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.removeValue(); */
}
private void getIncomingIntent(){
Intent intent = getIntent();
if(intent.hasExtra(getString(R.string.selected_image))
|| intent.hasExtra(getString(R.string.selected_bitmap))){
//if there is an imageUrl attached as an extra, then it was chosen from the gallery/photo fragment
Log.d(TAG, "getIncomingIntent: New incoming imgUrl");
if(intent.getStringExtra(getString(R.string.return_to_fragment)).equals(getString(R.string.edit_profile_fragment))){
if(intent.hasExtra(getString(R.string.selected_image))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
intent.getStringExtra(getString(R.string.selected_image)), null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
null,(Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap)));
}
}
}
if(intent.hasExtra(getString(R.string.calling_activity))){
Log.d(TAG, "getIncomingIntent: received incoming intent from " + getString(R.string.profile_activity));
setViewPager(pagerAdapter.getFragmentNumber(getString(R.string.edit_profile_fragment)));
}
}
private void setupFragments(){
pagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new EditProfileFragment(), getString(R.string.edit_profile_fragment)); //fragment 0
pagerAdapter.addFragment(new SignOutFragment(), getString(R.string.sign_out_fragment)); //fragment 1
// pagerAdapter.addFragment(new DeleteAccountFragment(), "Delete Account");
}
public void setViewPager(int fragmentNumber){
mRelativeLayout.setVisibility(View.GONE);
Log.d(TAG, "setViewPager: navigating to fragment #: " + fragmentNumber);
mViewPager.setAdapter(pagerAdapter);
mViewPager.setCurrentItem(fragmentNumber);
}
private void setupSettingsList(){
Log.d(TAG, "setupSettingsList: initializing 'Account Settings' list.");
ListView listView = (ListView) findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString(R.string.edit_profile_fragment)); //fragment 0
options.add(getString(R.string.sign_out_fragment)); //fragement 1
// options.add("Delete Account");
ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, options);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: navigating to fragment#: " + position);
setViewPager(position);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this,bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
DeleteAccountActivity.java
public class DeleteAccountActivity extends AppCompatActivity {
Button yesButton;
Button cancelButton;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_delete_account);
yesButton = (Button) findViewById(R.id.btnDelete2);
cancelButton = (Button) findViewById(R.id.btnDelete3);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAllData();
Intent intent = new Intent(mContext, RegisterActivity.class);
startActivity(intent);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
}
});
}
public void deleteAllData(){
DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference()
.child("user_photos")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference()
.child("user_account_settings")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowing = FirebaseDatabase.getInstance().getReference()
.child("following")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowers = FirebaseDatabase.getInstance().getReference()
.child("followers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();
deleteUserFollowing.removeValue();
deleteUserFollowers.removeValue();
}
}
Issue :
Press backarrow (But this will finish the activity)
Press mdelete to trigger the intent. (so no way to trigger intent)
Because when you press backarrow, you are setting the listener on mdelete which actually has the code to trigger intent and finish will kill the activity so no way to trigger intent
Solution : Separate the listeners
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
Please, change the lines with setting the clickListeners to this:
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
I think your onCreate() method should look like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
}
One simple thing i can see by skimming through is that the onClick listener for your button that should take you to delete activity is assigned inside the back arrow onClick listener.
So the only time your delete button is assigned a click listener is when you press the back button, and it wont still assign because you already called
finish();
On the activity
Change
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
} });
To
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
} });
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
Hope this helps.

RecyclerViewAdapter.notifyDataSetChanged() on a null object reference

I got an error with notifyDataSetChanged() on RecyclerView when I press back button. This is the code:
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 (Error File)
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();
}
}
});
}
And the 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)
How can I solve this?
In your MainActivity
public static MainActivity mactivity;
public static MainActivity getinstance(){
return mactivity;
}
In your WriteArticle activity
MainActivity mainActivity;
And use it as
mainActivity.getinstance.saveArticle(art_title, art_desc);
mainActivity.getinstance.adapter.notifyDataSetChanged();

Unable to instantiate activity?

i'm getting this error
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.bassammetwally.like/com.example.bassammetwally.like.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
when i'm trying to switch activity in another method in the
mainActivity.class
The Code i'm trying to run(not going to include libraries);
public class MainActivity extends AppCompatActivity {
final Intent i = new Intent(this, profile.class);
ImageButton ButtonOne = (ImageButton) findViewById(R.id.profile);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent i = new Intent(this, profile.class);
ImageButton ButtonOne = (ImageButton) findViewById(R.id.profile);
ButtonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button();
}
});
}
public void button()
{
startActivity(i);
}
}
code before that worked
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent i = new Intent(this, profile.class);
ImageButton ButtonOne = (ImageButton)findViewById(R.id.profile);
ButtonOne.setOnClickListener(new View.OnClickListener(){
public void onClick( View v ){
startActivity(i);
}
});
}}
Questions:
What is the meaning of the error?
why is this error showing?
Try this code:
final Intent i ;
ImageButton ButtonOne ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i =new Intent(MainActivity.this, profile.class);
ButtonOne = (ImageButton) findViewById(R.id.profile);
ButtonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button();
}
});
}
public void button()
{
startActivity(i);
}
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton ButtonOne = (ImageButton) findViewById(R.id.profile);
ButtonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(this, profile.class);
startActivity(i);
}
});
}
}
Also Added Profile.java in manifest file
You're initiating variable i twice. When going to function button() you are using the one in public scope (above the onCreate method), not the one from onCreate. Your code should look like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent i = new Intent(this, profile.class);
ImageButton ButtonOne = (ImageButton) findViewById(R.id.profile);
ButtonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button(i);
}
});
}
public void button(Intent i)
{
startActivity(i);
}
}

Categories