NullPointerException on setContentView() but it exists - android

I have an adapter class extended to BaseAdapter that starts another activity through intent. That another activity is giving me the error:
10-10 23:58:57.171: E/AndroidRuntime(3651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.migdinny.passman/com.migdinny.passman.DataActivity}: java.lang.NullPointerException
...
10-10 23:58:57.171: E/AndroidRuntime(3651): Caused by: java.lang.NullPointerException
10-10 23:58:57.171: E/AndroidRuntime(3651): at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:77)
10-10 23:58:57.171: E/AndroidRuntime(3651): at com.migdinny.passman.DataActivity.onCreate(DataActivity.java:20)
Here's the code:
THE CODE THAT STARTS THE NEW ACTIVITY (this is inside a new listener)
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("category", category);
context.startActivity(intent);
}
THIS CODE IS THE NEW ACTIVITY THAT IS STARTED BY THE CODE ABOVE
public class DataActivity extends ActionBarActivity {
String category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // i've tried this line on all places and it doesnt fix the problem, after the setcontentview, before, etc
Intent intent = getIntent(); // this works
category = intent.getExtras().getString("category"); // this exists
setContentView(R.layout.activity_data); // THIS IS THE LINE 20 OF DATA ACTIVITY and of course that the activity_data layout exists. the eclipse does not warn me anything.
}
........
EDIT:
here's the activity_data.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.migdinny.passman.DataActivity" >
<TextView
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
the category variable that is used on onClick:
final String category = list.get(position).getCatname(); // on the beginning of getView method and i think the error is not here

Do you have any custom theming? I remember reading somewhere someone with an issue related and was related to the mind, if you have try to remove it to see if it's related (worth at try)

Related

why the app crash after calling a method?

I hope you can help me I was trying to look into the other questions but I didnt found what I was trying to do or didn't get it.
this is a very simple example of what I'm trying to do. I have this main activity:
public class MainActivity extends Activity {
static EditText num1, num2; //Change EditText from TextView
static TextView num3; //Textview variable
int x, y, r;
Addition addition=new Addition();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(EditText)findViewById(R.id.editText);
num2=(EditText)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.textView);
x = 0;
y = 0;
}
public void add (View view){
setXY();
r=addition.addResult(x,y);
num3.setText(String.valueOf(r));
}
public void setXY(){
x=Integer.parseInt(num1.getText().toString());
y=Integer.parseInt(num2.getText().toString());
}
}
and I am trying to call that method from this class
public class Addition {
public int addResult(int x, int y){
return x+y;
}
}
so at the beginning the app crashed because of the null values that was receiving from the layout, but after set the try catch the app was running. The problem comes when I click the "add" button the app crash again. do you guys can tell me why? what am I doing wrong? how should I do it? and if I have an app with more "operations" ,methods, is it worth creating a class with all this operations and call them from the main one? or maybe I shouldn't try to do this?
Greetings!!!
Chiok
Logcat
07-14 14:35:24.625 5407-5407/com.chiok.x2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chiok.x2, PID: 5407
java.lang.IllegalStateException: Could not find method addition(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-14 14:35:25.893 5407-5407/com.chiok.x2 I/Process: Sending signal. PID: 5407 SIG: 9
and this is the xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.chiok.x2.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:onClick="add" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="addition" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="56dp" />
I guess it have something to do with the editable objets that are null.. but nothing that I try works.
change these code
num1=(TextView)findViewById(id.editText);
num2=(TextView)findViewById(id.editText2);
num3=(TextView)findViewById(id.editText3);
to
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
and remember to import R.java in your project.
onClick command which stored in layout need parameter View v in receiver method, so change addResult() to addResult(View v)
if I have an app with more "operations" ,methods, is it worth creating
a class with all this operations and call them from the main one?
Yes it worths that, it will make your code more object oriented. In this case it will make more sense if you change the name of class from Addition to Operations. Also Addition class does not need to be an activity. So don't extend it from MainActivity.
Just send two parameter to that method and make addResult return an int result which is addition of those two parameters.
And in your MainActivity get the return value of your addResult method and setText the edittext3.
public class MainActivity extends Activity {
TextView num1, num2,num3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
// here I am trying to call the method
Addition x = new Addition();
int param1 = Integer.parseInt(num1.getText().toString());
int param2 = Integer.parseInt(num2.getText().toString());
int result = x.addResult(param1, param2);
num3.setText(String.valueOf(result));
}
}
And your Addition Class can be like this;
public class Addition {
public int addResult(int param1, int param2){
return param1 + param2;
}
}
Summary I changed setContentView(R.layout.activity_main);
Delete extends MainActivity in your Addition class.
Also if the error still persists, I need to see your xml layout where you define your textviews and button.
Make your Textview static. Try
static TextView num1, num2,num3;
Reason
Addition x = new Addition();
In the above code, it is creating a new instance of Addition class which is extending the MainActivity and hence the TextView will be NULL for the new instance. In order to make the TextView initialization available for all instances, make the TextView static.
Use following code.
public class MainActivity extends Activity {
EditText num1, num2; //Change EditText from TextView
TextView num3; //Textview variable
Button add; //Button variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Add R.layout.activity_main
num1=(EditText)findViewById(R.id.editText); //R.id.editText
num2=(EditText)findViewById(R.id.editText2); //R.id.editText2
num3=(TextView)findViewById(R.id.textview); // initialize textview
add=(Button) findViewById(R.id.add); //initialize add button
final Addition x = new Addition();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x.addResult();
}
});
}
}
public class Addition {
public void addResult(){
try {
num3.setText(String.valueOf((Integer.parseInt(num1.getText().toString())+(Integer.parseInt(num2.getText().toString())))));
}
catch (Exception e) {}
}
}
}

Not able to set text of textview from other activity

i have main activity:
public class MainActivity extends AppCompatActivity {
Button btnadd;
int a1 = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SecondAct sa = new SecondAct();
sa.ttl(a1);
}
});
}
}
and i have other activity:
public class SecondAct extends Activity {
public TextView txt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
txt2 = (TextView) findViewById(R.id.txt2);
}
public void numsum(int no)
{
txt2.setText(String.valueOf(no));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btnadd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="addd"></Button>
<LinearLayout
android:layout_below="#+id/btnadd"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/second"></include>
</LinearLayout>
</RelativeLayout>
When i click on button from main activity to set textview text of second activity then it gives me error.
Error:
FATAL EXCEPTION: main
Process: com.example.sumdemo, PID: 13809
java.lang.NullPointerException
at com.example.sumdemo.MainActivity$1.onClick(MainActivity.java:28)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
How can i set second activity value from main activity without passing data through intent ?
final SecondAct sa = new SecondAct();
sa.ttl(a1);
never use the new operator on a class that extends Activity. You have to use startActivity to start SecondAct, and provide additional info through the Intent object
Use Application class with a static parameter.
That is
class MyApp extends Application{
public static TextView tv;
}
in the first activity:
usemyapp.tv = (TextView) findViewById(...);
in oreder to have an access from somewhere use this:
if (MyApp.tv != null)
MyApp.tv.setText("a new text");
do not forget to wrap it in mainUiThread by using a handler.
in AndroidMainfest.xml file use this:
<application
android:name=".MyApp" <<<<<<<<<<<<<<<<<<<<<<<this the name of the class
>
Futhermore, do not create an activity class by a constructor. this is a very very bad idea:) You have this error because you have created the class but onCreate() method has not called and has not attached to Android UI process.
Use this question as guide.
How to manage `startActivityForResult` on Android?
And don't try to change one activity content from another activity.
When you create an Activity object through its constructor, you can't call its life cycle methods (e.g onCreate) so your activity doesn't have a View and you can't access your views. you must use startActivity and let android handle creating Activity object and call its life cycle method. you should change its view after inflating view. for your case, you can pass extra data via Intents and use that data in your second Activity

Passing data from an Activity to a Layout in Android

I have an Android Activity as below.
public class DummyActivity extends android.support.v7.app.ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy_layout);
Intent intent = getIntent();
int dots = intent.getExtras().getInt("dots");
}
}
This activity gets the value of dots from another activity without any problem.
Now I want to pass dots to the layout dummy_layout which is given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.test.DummyView
android:id="#+id/dummyView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
</LinearLayout>
I tried creating a hidden field in 'dummy_layout' but could not get it working. Is there any straight forward way I can do this ?. I need to access the value of 'dots' in the init method of 'dummyView' which is the class handling 'dummy_layout' as seen in the layout xml.
Why don't you just do
((DummyView) findViewById(R.id.dummyView)).setDots(dots)
in your onCreate?

oncreate function doesnt start

Trying to launch another activity from my main activity using a button i placed on my main activity, now when the button is clicked it prints "call activity" and so it works fine, but when the second activity is launched it seems like it doesn't execute oncreate method, as it doesn't print "start" and doesn't call GetCar(); method. The only thing it does is to show the xml.
button that launches second activity (print "call activity" is working fine)
public void allCars(View v){
setContentView(R.layout.activity_cars_menu);
System.out.println("call activity");
}
second activity code (doesn't print "start" or call GetCar().)
public class CarsMenu extends Activity {
Button btn;
public static String[] carId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cars_menu);
System.out.println("start");
GetCar();
}
}
second activity xml (can't see viewlist probably because i can't set text (doesn't call GetCar()) .
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
all of my activity is on the manifest and i'm not getting any errors on logcat.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="btnCarClick"
android:text="Refresh" />
<ListView
android:id="#+id/MlistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true">
</ListView>
</RelativeLayout>
You might want to start your Activity:
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(myIntent);
Just setting the content view is not enough
Your starting your second Activity in the wrong way, and you only change your view in your first Activity.
In order to change activity you need to call
startActivity (Intent intent)
for more info you can read on
http://developer.android.com/training/basics/firstapp/starting-activity.html
Actually you are just changing the content UI of current activity. As
setContentView(R.layout.activity_cars_menu);
does only that. In real your 2nd activity is never started even. For starting second activity you should do
Intent i = new Intent (Activity1.this, CarsMenu.class);
startActivity (i);
Make sure you have added CarsMenu activity to your Android Manifest.

Closing a "Pop-Up like" activity

I made this app, it gives notification to user. Notification is just a string. Sometimes a string can be long so I tried to show that string in a pop-up layout.
Like this, my xml:
<activity
android:name="com.dot.Popup"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Dialog">
</activity>
My layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#aeb25e" >
<TextView
android:id="#+id/notif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="asd"
android:padding="5dp"
android:textColor="#1D331C"
android:textSize="15sp"
android:textStyle="bold"
android:typeface="serif" />
</RelativeLayout>
And the code:
public class Popup extends Activity {
String notif;
Intent sender;
TextView popup_notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup);
sender=getIntent();
notif=sender.getExtras().getString("notif_ana");
popup_notif = (TextView) findViewById(R.id.notif);
popup_notif.setText(notif);
}
}
So here is my problem, I can display first item of string array (notifications), when second notification comes and I click, I display the previous screen. How can I refresh the string array, or kill the activity to call next string array, etc?
Thanks I hope I explanied good enough.
To close Activity you need to call finish(). And instead of activity i'd use rather Toast (with perhaps custom layout) or one of numerous libraries providing toast alterantives. Using activity here may be slightly overkill
try getting the intent and extras in the onResume() function and update the TextView in onResume() function of the activity.
public class Popup extends Activity {
String notif;
Intent sender;
TextView popup_notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup);
popup_notif = (TextView) findViewById(R.id.notif);
}
#Override
protected void onResume() {
super.onResume();
sender=getIntent();
notif=sender.getExtras().getString("notif_ana");
popup_notif.setText(notif);
}
}

Categories

Resources