java.lang.NullPointerException: Attempt to invoke virtual method, causing app to crash - java

I'm particularly new to this field. I'm trying to create a login page using fragments and it crashed when I tried to run it. I checked the logcat, turns out its a NullPointerException. It highlighted the error here:
register = (Button) findViewById(R.id.RegisterUser);
register.setOnClickListener(this);
Here is my code
this is mainactivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
register = (Button) findViewById(R.id.RegisterUser);
register.setOnClickListener(this);
ViewPager viewPager = findViewById(R.id.viewPager);
AuthenticationPagerAdapter pagerAdapter = new
AuthenticationPagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragmet(new LoginFragment());
pagerAdapter.addFragmet(new RegisterFragment());
viewPager.setAdapter(pagerAdapter);
}
public void onClick(View v){
switch (v.getId()){
case R.id.RegisterUser:
startActivity(new Intent(this, RegisterUser.class));
break;
}
}
class AuthenticationPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
public AuthenticationPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
#Override
public int getCount() {
return fragmentList.size();
}
void addFragmet(Fragment fragment) {
fragmentList.add(fragment);
}
}
}

It seems you define the global field private TextView register; but you want to cast it to Button register = (Button) findViewById(R.id.RegisterUser);
Please check your XML file and make sure what's your element TextView or Button.

can you please check your activity_main.xml file
check into that is a Button or Textview

Related

how to change actionBar title of Activity1 from a button of Activity2

I am trying to make a button in activity2(settings page), when the button is clicked, then the title of activity1(MainActivity) will change to what I set to. I have been trying to use interface to carry out the function but it gives me a null pointer exception error.
MainActivity
#Override
public void changeActionBarTitle(String editText){
actionTitle = editText;
setTitle(actionTitle);
};
Interface
public interface ActionBarInterface {
void changeActionBarTitle(String editText);
}
Setting page (activity 2)
public class SettingsPage extends AppCompatActivity {
ActionBarInterface actionBarInterface;
Button editCompanyNameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
actionBarInterface.changeActionBarTitle("test");
}
});
}
}
Thanks.
You can try this code without using the interface
MainActivity:
#Override
protected void onResume() {
setTitle(Main2Activity.title);
super.onResume();
}
activity2:
public class SettingsPage extends AppCompatActivity {
Button editCompanyNameButton;
static String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
title = "test";
}
});
}
}
It gives a null pointer exception error because actionBarInterface was not initialised.
Check out topics on 'Getting a Result from an Activity', making use of classes and functions such as Intent, startActivityForResult, onActivityResult.
Android: how to make an activity return results to the activity which calls it?

Sharing data between an adapter-recyclerview and another class

I want to send in a variable the position of a click on an Item in a other activity. I show you my work that does not work. The application quits when I press an item.
MyViewHolder in my adapter:
public myViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get position
int poss = getAdapterPosition();
// sharing position
Intent intent = new Intent(mContext, Main2Activity.class);
intent.putExtra("position", poss );
mContext.startActivity(intent);
}
}
});
And my Activity for recept:
public class Main2Activity extends AppCompatActivity {
private TextView textTest;
int id = getIntent().getExtras().getInt("position");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
String position = String.valueOf(id);
textTest = findViewById(R.id.text_test);
textTest.setText(position);
}
Try
public class Main2Activity extends AppCompatActivity {
private TextView textTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textTest = findViewById(R.id.text_test);
int id = getIntent().getExtras().getInt("position");
String position = String.valueOf(id);
textTest.setText(position);
}
Remove this line of code int id = getIntent().getExtras().getInt("position"); from outside of the onCreate() method & put this code inside of your onCreate Method in Main2Activity
textTest = findViewById(R.id.text_test);
int id = getIntent().getExtras().getInt("position");
String position = String.valueOf(id);
textTest.setText(position);
Create Interface class
Public interface OnPostionClick{
Public void yourmethod(int pos)
}
Place interface method on Adapter viewHolder onClick method
If(context instanceof OnPostionClick){
((OnPostionClick) context).yourmethod(poss);
}
implement OnPostionClick interface on Second Activity and override yourmethod

Get information from current fragment in TableLayout

I'm using TabLayout and ViewPager.I successfully integrated it and used from fragments.This is my mainTabActivity java class
public class MainTabActivity extends AppCompatActivity {
private CustomTabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (CustomTabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
findViewById(R.id.tab_ticket).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainTabActivity.this, TicketsActivity.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
findViewById(R.id.tab_main).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("BottomClickAction","BottomClickAction");
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneWayFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "ROUND");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Also i have custom bottom bar.Now i try to explain my problem.In my fragments contains some elements,fro example spinners,Textviews or etc.My question is:How i get information from current fragment when i click bottom bar? I mean,spinner'data information,Textview's gettext or etc.
How i can solve my problem? Is it a possible to don't use static variables ?
You can find the fragment OneWayFragment in viewpager like this:
public OneWayFragment getOneWayFragment() {
return (OneWayFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + R.id.viewPager + ":" + 0);
}
public TwoFragment getTwoFragment() {
return (TwoFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + R.id.viewPager + ":" + 1);
}
You can access public method from OneWayFragment or TwoFragment a get data you want.
For ex, create method getText from OneWayFragment:
public String getData() {
return tv.getText().toString();
}
And in your MainTabActivity. For ex you click button has id tab_main and you get data from OneWayFragment.
findViewById(R.id.tab_main).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("BottomClickAction","BottomClickAction");
OneWayFragment fragment = getOneWayFragment();
if(fragment != null) {
String data = fragment.getData();
}
}
});
Create own method like getFragmentData() in fragments. Access this method whenever you want. In your case:
1) take references of your fragment
_oneWayaFrgament= new OneWayFragment()
adapter.addFragment(_oneWayaFrgament, "ONE");
2) call _oneWayaFrgament.getFragmentData()
similarly apply your conditional logic on TwoFragment.
Please call getFragmentData() by identifying current fragment.
yes you can have public variables and methods in your fragments and then you can set and get your variables or call your methods from your activity.
for example in your fragments:
public String myString;
public Button someButton;
or
public void fillMyTextView(){//some codes};
and in your activity you can call those methods or access your views like this:
myFragment.fillMyTextView("hello");
myFragment.someButton.setText("my btn");
I would suggest you create singleton as state object(as you want as the state of the views, you can go with integer or short or byte for state marks memory wise) use as you want, and nullify once done usage. This way you can be access any data, in any fragment or activity, at any point of time. You can go with other implementations also like interface kinds as design and architectural way.But depends on the how important states are.

Can i declare and use the same button in an Activity and a class?

I want to use the button for different calls in the different classes. However, when I declare and try to call the Button click method in the Activity class, it throws a null exception. In my Class I want to do this:
public class CustomFeedListViewAdapter extends BaseAdapter {
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
private class ViewHolder {
Button feedUpVoteButton;
}
And in my main activity I want to do this:
public class Feed extends AppCompatActivity {
Button upVoteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
upVoteButton = (Button) findViewById(R.id.feedUpVoteButton);
feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
You are getting NullPointerException because you are trying to access feedUpVoteButton which is present in the item layout used in CustomFeedListViewAdapter and not in the layout used by Feed activity.
Do you want to have access to the ClickListener whenever you create an adapter of type CustomFeedListViewAdapter? If yes then do this...
Your Activity class
public class Feed extends AppCompatActivity {
CustomFeedListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
adapter = new CustomFeedListViewAdapter( new OnClickListener() {
#Override
public void onClick(View v) {
// Handle click here
}
});
}
}
And your custom adapter class
public class CustomFeedListViewAdapter extends BaseAdapter {
View.OnClickListener clickListener;
// Constructor
public CustomFeedListViewAdapter(View.OnClickListener listener) {
clickListener = listener;
}
#Override
void getView(){
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
This way you can set a different listener for each instance of the adapter you create.

OnClickListener throws NullPointerException

I'm trying to set onClick listener to a button from a ViewPager's page but when I try to run the app I get NullPointerException
....
public class MainActivity extends Activity {
private ViewPager vPager;
private MyPagerAdapter pagerAdapter;
private TextView tv;
private MyViewPagerListener pagerListener;
private Button deleteAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.page_state);
pagerListener = new MyViewPagerListener();
pagerAdapter = new MyPagerAdapter();
vPager = (ViewPager) findViewById(R.id.vPager);
vPager.setAdapter(pagerAdapter);
vPager.setCurrentItem(0);
vPager.setOnPageChangeListener(pagerListener);
//Here is the problem
ClickListener cl = new ClickListener();
deleteAll = (Button) vPager.findViewById(R.id.btnDelete);
deleteAll.setOnClickListener(cl);
}
.....
}
You should register a new OnClickListener object instead of a ClickListener. Also, you have to provide an implementation for the onClick method like this:
new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};

Categories