Why do I get a NullPointerException here? - android

I have my code defined the way below. There are two crucial activities. Activity (1) shows some images in a ViewFlipper. It uses methods to load desired image directly. The onOptionsItemSelected() method fetches data from a menu defined within linked XML layout R.layout.browse. The other method, displaySelectedFlag(), gets a tag parameter passed from a different activity, let's call it activity (2).
Activity (1):
public class BrowserActivity extends AppCompatActivity implements SimpleGestureListener, View.OnClickListener {
public ViewFlipper vFlipper;
(...)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse);
vFlipper = (ViewFlipper) findViewById(R.id.viewFlipperBrowser);
(...)
} // onCreate() ends here
// this method below works fine:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
vFlipper.setDisplayedChild(item.getOrder());
return true;
}
// and this one doesn't:
public void displaySelectedFlag(int orderTag) {
vFlipper.setDisplayedChild(orderTag); // crashes here
}
}
Activity (2):
public class ListActivity extends Activity implements View.OnClickListener {
private BrowserActivity browserActivity = new BrowserActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ImageButton imageA = (ImageButton) findViewById(R.id.img_a);
imageA.setOnClickListener(this);
ImageButton imageB = (ImageButton) findViewById(R.id.img_b);
imageB.setOnClickListener(this);
}
public void displayImageInfo(View view) {
String tagValue = (String) view.getTag();
int tagId = Integer.parseInt(tagValue);
Intent intent = new Intent(this, BrowserActivity.class);
startActivity(intent);
browserActivity.displaySelectedImage(imageId);
}
#Override
public void onClick(View view) {
displayImageInfo(view);
}
}
As I checked, the method onClick() called in activity (2) fetches an ID of an ImageButton and passes it to activity (1). Unfortunately, I get a NullPointerException when calling the ViewFlipper (the line is marked in the code above, activity (1)).
Any idea why it happens?

You cannot reference one Activity from another activity. You must let the Android OS create the Activity object via the call to "startActivity". Allocating a local variable as an instance of an Activity doesn't actually mean anything (like your instantiation of the BrowserActivity). Apoorv's comment links to a decent article on the subject.
If you want to pass data from one Activity to another, you need to pass extras within the Intent's bundle. This post goes into detail: https://stackoverflow.com/a/819427/504252

Related

How to get fragment tag or ID?

I have 2 fragments which are instantiated from the same class as the layouts are identical like so:
getSupportFragmentManager().beginTransaction().
add(R.id.leftContainer,new LeftFragmentClass(),"leftFrag").commit();
getSupportFragmentManager().beginTransaction().
add(R.id.rightFrag,new LeftFragmentClass(),"rightFrag").commit();
Within LeftFragmentClass there is a callback method which is called when the button within the fragment is pressed. After this some processing is done and data is displayed, however, right now the callback cannot distinguish which button was pressed. Is there a function which can return which fragment button was pressed?
For this type of condition i create a function inside fragment which will return me the instance of fragment and make the fragment constructor private something like:-
public class LeftFragmentClass extends Fragment{
private String fragmentTag = null;
public LeftFragmentClass(){}
public static LeftFragmentClass newInstance(String tag){
LeftFragmentClass mLeftFragmentClass = new LeftFragmentClass();
Bundle bundle = new Bundle();
bundle.putString ("tag",tag);
mLeftFragmentClass.setArgument(bundle);
return mLeftFragmentClass;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
tag = getArguments().getString("tag")
}
}
So i used newInstance function to create instance of LeftFragmentClass and pass the tag to it which i m setting to Fragment argument using bundle and inside onCreate get bundle using getArguments and from it the tag value. Pass this tag value as one of the parameter to your callback method to identify which button was clicked.
So from activity for getting instance of LeftFragmentClass you can write as
LeftFragmentClass mLeftFragmentClassLeft = LeftFragmentClass.newInstance("left")
LeftFragmentClass mLeftFragmentClassRight = LeftFragmentClass.newInstance("Right")
==== Edit ====
keep the fragment class constructors always public don't make it private as i suggested above in my sample code. Making it private will cause application to crash with exception
java.lang.RuntimeException: Unable to start activity
ComponentInfo{MainActivity}:
android.support.v4.app.Fragment$InstantiationException: Unable to
instantiate fragment com.thatswhy.AppAlertDialog: make sure class name
exists, is public, and has an empty constructor that is public
Fragment fragment = getFragmentManager().findFragmentByTag("Tag")
As per provided the info you can do something like this, in your callback method pass the button object and check accordingly,
Some code snippet to explain the same :
Suppose your callback method is onButtonClick() then you can pass button object like :
public void onButtonClick(Button button){
// check here with button id
if(button.getId() == R.id.button1) {
} else if(button.getId() == R.id.button1) {
}
}
Hope this makes things clear..
The cleanest way of doing this I've seen is to create two distinct View.OnClickListener(s) in the Activity.
Have a getter() for each. public View.OnClickListener getLeftButtonPressed(), public View.OnClickListener getRightButtonPressed()
Then when you instantiate your left and right instances of your fragment, just pass in the appropriate 'View.OnClickListener' to the constructor of the Fragment. This not only reduces the code in the Fragment(s), it also centralizes the 'logic' of what to do when buttons are pressed.
public class MyActivity extends Activity {
// create the two listeners
View.OnClickListener leftButtonListener = new View.OnClickListener() {
public void onClick(View v) {
leftButtonClicked(v);
}
});
View.OnClickListener rightButtonListener = new View.OnClickListener() {
public void onClick(View v) {
rightButtonClicked(v);
}
});
// 2 getters
public View.OnClickListener getLeftListener() { return this.leftButtonListener; }
public View.OnClickListener getRightListener() { return this.rightButtonListener; }
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
}
// actual logic of what to do when each button is pressed.
private void leftButtonClicked(View v){
// some logic here
}
private void rightButtonClicked(View v){
// some logic here
}
}
This removes you later having to keep track of which button was pressed by making use of strings and if/then/else blocks, etc.
Add a parameter to interface callback function in your fragment;
interface Interfacecallback{
public void callbackfunction(int fragid);
}
Interfacecallback interfacecallback;
//in your button click
//pass 1 for fragment right
//pass 2 for fragment left
interfacecallback.callbackfunction(1);
You can check the fragment tag using this line of code if it exists:-
Fragment mapFragment = getFragmentManager().findFragmentByTag("MapRestaurantFragment");

How do I display public text in Activity A after it has been changed by Activity B

This probably demonstrates the most appalling lack of understanding of the activity life cycle, but please be sympathetic. I am ultimately going to want to invoke Activity B from Activity A a number of times, each time passing a different parameter to Activity B which is then responded to by the user and stores/sets various public variables. As a precursor to this, I just want to get my head round how Activity A sees the change to a public variable that Activity B has changed.
I have three very simple classes: Common.java that holds the public variables, the main activity MainActivity.java and the child activity Child.java. There is only one public variable right now; it's the string mess1 which is initialized to "***". All the code does at the moment is when mainbutton is clicked in MainActivity, it invokes Child. In Child, we immediately set mess1 to "Child here" then set the text in a Child-based TextView to mess1. On clicking the childbtn button in Child, we finish() the child activity (and of course the system returns us to MainActivity.
When this app is run, wee see the three stars displayed in MainActivity. When mainbutton is pressed we go to Child and see "Child here" displayed. When the childbtn is pressed, we return to MainActivity BUT, the three stars are still there although we know for sure that mess1 now holds "Child here".
My questions are:
1. Why, when we know mess1 has been changed, does MainActivity still display "***" on return from the Child activity?
2. What do I need to change in the code to get "Child here" to display?
Relevant code extracts follow. Thanks in advance for your help.
Common.java
public class Common
{
public static String mess1 = "***";
}
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainbutton = (Button)findViewById(R.id.mainbutton);
TextView maintop = (TextView)findViewById(R.id.maintop);
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
startActivity(new Intent(MainActivity.this, Child.class));
}
});
maintop.setText(Common.mess1);
}
Child.java
public class Child extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
TextView childtext = (TextView) findViewById(R.id.childtext);
final Button childbtn = (Button) findViewById(R.id.childbtn);
Common.mess1 = "Child here";
childtext.setText(Common.mess1);
childbtn.setOnClickListener
(new View.OnClickListener()
{public void onClick(View v)
{finish();
}
}
);
}
Likely you are moving back on the back stack history and you are resuming the previous activity that was placed in a paused state and therefore the onCreate isn't being called but the onResume (of the initial activity)..
Using global state this way isn't advised but this should work if you place the appropriate code in the onResume method.
You should set the text in onResume() of MainActivity. When you get back from Child.java onResume() (not onCreate()) is invoked and, since maintop's text is set in onCerate() only, nothing changes it on return.
protected void onResume() {
super.onResume();
maintop.setText(Common.mess1);
}
Reference: Activity Lifecycle and Implementing the lifecycle callbacks

Android application closes on click

I do my android app , but I have a bug I don't know how to fix it.
My code is below :
This is my Main Activity :
public class MainActivity extends Activity {
private ImageView imgHot;
public final static String EXTRA_MESSAGE="com.cuonglm.KhoHinh.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgHot=(ImageView)findViewById(R.id.imageViewHot);
imgHot.setOnClickListener(toContentHot);
}
View.OnClickListener toContentHot=new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent content=new Intent(MainActivity.this,ContentActivity.class);
String signal="1";
content.putExtra(EXTRA_MESSAGE,signal);
startActivity(content);
}
};
And this is my second Activity :
public class ContentActivity extends Activity {
private TextView viewMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent content=getIntent();
String messageReceive=content.getStringExtra(MainActivity.EXTRA_MESSAGE);
viewMessage=(TextView)findViewById(R.id.content_receive);
viewMessage.setText(messageReceive);
setContentView(R.layout.activity_content);
}
I want to click on the image on the Main Activity , string "1" or number "1" will send to the Second Activity via Intent and view on the TextView.
But my app will be close "Unfortunately..."
Thanks
Change to
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
viewMessage=(TextView)findViewById(R.id.content_receive);
viewMessage.setText(messageReceive);
In your ContentActivity
findViewById looks for a view with the id for the current infalted layout. SO you need to set the content of your layout to the activity first and then initialize your views.
You are probably gettting NullPointerException coz your initialization fails.
You need to call setContentView() in your second Activity before trying to access any of the Views in that layout. Change it to
public class ContentActivity extends Activity {
private TextView viewMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
Intent content=getIntent();
String messageReceive=content.getStringExtra(MainActivity.EXTRA_MESSAGE);
viewMessage=(TextView)findViewById(R.id.content_receive);
viewMessage.setText(messageReceive);
}
If this doesn't fix your problem then please post your logcat so we can see the error. Also always post logcat in the future when your app crashes. They aren't always this easy to see.
Also, I'm not sure you understand how putExtra() works. It is a key, value pair so when you put EXTRA_MESSAGE as the key then that is what you would use to retrieve the value added in the second param. So the way you are doing it may work if the Activity gets destroyed but it looks really strange to me and probably not realy safe or efficient. I would change it to something like
content.putExtra("message",signal);
in your first Activity then get it with
String messageReceive = content.getStringExtra("message");
in your second Activity
You need to set the layout before trying to reference the Views associated with it.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent content=getIntent();
String messageReceive=content.getStringExtra(MainActivity.EXTRA_MESSAGE);
setContentView(R.layout.activity_content);
viewMessage=(TextView)findViewById(R.id.content_receive);
viewMessage.setText(messageReceive);
}

using onClickView to call another class

I want to use a button click to pass selection parameters to another class that will build a map screen using the passed parameters. I am focused on getting my button action working. I a using onCLickListener and onCLickView as follows
Class1:
public class Class1 extends Activity implements OnClickListener {
Class2 class2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
..........
Button button = (Button)findViewById(R.id.btn_configup1);
button.setOnClickListener(this);
}
public void onClick(View v) {
Class2 class2 = new Class2();
//Save state.. selections and params and use bundle
//to pass into class2
class2.execMapBuild();
}
}
Class2:
public class Class2 extends MapActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.drawable.navup);
}
public void execMapBuild() {
finish(); //just in case we return.
Intent intent = new Intent(CLass2.this, Class2.class);
startActivity(intent);
}
I have everything working except the desired button action. I want the button click in Class1.onVlickView to call Class2.execMapBuild using the button click action. I have the button click capturing the action and calling the execMapBuild method on Class2. But I get a NullPointerException as it moves from startActivity(intent) into onCreate.
I have tried several other ways of nailing this down, but this seems the best and I seem close to figuring it out. I would really appreciate an explanation of what I may be missing.
Added code that was initially not copied in.
To expand on #Heiko Rupp's answer, if you want Class2 to display a map, it needs to extend something like Activity. As such, you can't just call it with a normal method. You need to register the Activity in your manifest and then call it using an Intent. Here is a sample of the kind of thing you should be doing:
public class Class1 extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Button button = (Button)findViewById(R.id.btn_configup1);
button.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent(Class1.this,Class2.class);
intent.putExtra("key","data");
...
startActivity(intent);
}
}
public class Class2 extends MapActivity {
String mData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
mData = extras.getString("key");
...
}
...
}
}
Can I also suggest that you use more descriptive class names than Class1 and Class2.
Class2 is no activity, so the callbacks of an Activity will not be called by the system.
And if it were an Activity, you could not just call into it via new Class2(), as still the callbacks are not executed.
Try to clean this up and then start Class2 activity from Class1 with an Intent as you are doing within execMapBuild().

Android: Button action not being called

I'm trying to make an app where you start at a menu, click a button and are brought to a list of items (which I later hope to make clickable). But I can't seem to make it call my next activity. Can anyone help?
Your main class / activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Menu Button
Button startNewActivity = (Button)findViewById(R.id.startnew);
startNewActivity.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent newActivityIntent = new Intent(YOUR-CLASS-NAME.this,NewActivity.class);
startActivity(newActivityIntent);
}
});
Your NewActivity Class:
public class NewActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new);
}
}
Is the question "How do I call the next activity" ?
If so, it's pretty easy - Assuming the Activity you want to call is "SomeActivity", call this:
Intent someActivity = new Intent(getBaseContext(), SomeActivity.class);
startActivity(someActivity);
There's also a "startActivityForResult" method, if you want data back from the Activity you're calling. For reference, the Activity page of the API Documentation can be found here. Good luck!

Categories

Resources