Android: Using getResources might be causing my app to crash - java

I don't know why this is causing my app to crash. I have instantiated 3 class variables to point to the color values I created in my colors.xml file. I have been experimenting, and the code that is commented out here seems to be causing the error "appName has stopped working"
protected int m_nDarkColor = R.color.dark;
//protected int m_nDarkColor = getResources().getColor(R.color.dark);
protected int m_nLightColor = R.color.light;
//protected int m_nLightColor = getResources().getColor(R.color.light);
protected int m_nTextColor = R.color.text;
//protected int m_nTextColor = getResources().getColor(R.color.text);
private boolean isDark = false; //To alternate between colors.
This is the method that is using the class variables on top. If I use the uncommented class variables in the setBackgroundColor() methods, the color is the same gray shade no matter what I change the color values to (that is why I commented those out too), so I tried setBackgroundColor(getResources()get.Color(R.color.dark) and it fixed the problem, but it made my class variables useless. I don't mean to be picky, I am just confused why when I set the class variable to point to my colors values in colors.xml, it causes my app to stop working or the smae gray color, but when I pass it to the setBackgroundColor method it works just fine.
`
protected void addJoke(String strJoke) {
android.widget.TextView display = new android.widget.TextView(this);
display.setText(strJoke); //Sets the text on display.
display.setTextSize(16); //Increases the font size of the text.
display.setTextColor(getResources().getColor(R.color.text));
//display.setTextColor(m_nTextColor);
if(!isDark)
{
display.setBackgroundColor(getResources().getColor(R.color.dark));
//display.setBackgroundColor(m_nDarkColor);
isDark = true;
}
else if(isDark)
{
display.setBackgroundColor(getResources().getColor(R.color.light));
//display.setBackgroundColor(m_nLightColor);
isDark = false;
}
m_vwJokeLayout.addView(display); //Adds the view to the layout.
}
This is all the red from LogCat
09-17 20:47:25.852: E/AndroidRuntime(11212): FATAL EXCEPTION: main
09-17 20:47:25.852: E/AndroidRuntime(11212): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{edu.calpoly.android.lab2/edu.calpoly.android.lab2.SimpleJokeList}: java.lang.NullPointerException
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.os.Looper.loop(Looper.java:137)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.reflect.Method.invoke(Method.java:511)
09-17 20:47:25.852: E/AndroidRuntime(11212): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-17 20:47:25.852: E/AndroidRuntime(11212): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-17 20:47:25.852: E/AndroidRuntime(11212): at dalvik.system.NativeStart.main(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): Caused by: java.lang.NullPointerException
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
09-17 20:47:25.852: E/AndroidRuntime(11212): at edu.calpoly.android.lab2.SimpleJokeList.<init>(SimpleJokeList.java:34)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.Class.newInstanceImpl(Native Method)
09-17 20:47:25.852: E/AndroidRuntime(11212): at java.lang.Class.newInstance(Class.java:1319)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
09-17 20:47:25.852: E/AndroidRuntime(11212): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
09-17 20:47:25.852: E/AndroidRuntime(11212): ... 11 more
Final Note: The way the code is set up now works, the colors come out right and the app runs on my device, the error is only caused when I switch the commented code with the uncommented code. This is my first question on here, so I hope it hasn't been asked before and I formatted it correctly, thanks for help!

Imagine like this: R.color.dark is like a pointer point to the value of color(Certainly not a real pointer like C language). And you use getResources().getColor(R.color.dark) method to get the real value of color.
Do a test:
Log.d("Color", "Value of \"R.color.gray\" is: " + R.color.gray);
Log.d("Color", "Value of \"getResources().getColor(R.color.gray)\" is: " + getResources().getColor(R.color.gray));
Here is the output in logCat:
09-18 11:07:17.458 32359-32359/com.ch.summerrunner D/Color﹕ Value of "R.color.gray" is: 2131099651
09-18 11:07:17.458 32359-32359/com.ch.summerrunner D/Color﹕ Value of "getResources().getColor(R.color.gray)" is: -2144128205
the value -2144128205 means the real color in Android system.
May this help you.
-----------add--------------
I understand what you mean.
Why your app crashes?
Because getResources() method return null.
But why it return null when you call it to set the class variable?
Long Story.
getResource() is a interface of Context and implement by ContextWrapper. Like this :
#Override
public Resources getResources()
{
return mBase.getResources();
}
But the Constructor of ContextThemeWrapper(Subclasses of ContextWrapper) is :
public ContextThemeWrapper() {
super(null);
}
and
public ContextThemeWrapper(Context base, int themeres) {
super(base);
mBase = base;
mThemeResource = themeres;
}
You can see that the mBase of ContextWrapper may be null.
This is the Constructor of Activity(Subclasses of ContextThemeWrapper):
public Activity ()
Activity Constructor
We did not pass a context to Activity, so when did ContextWrapper initialize mBase ?
When system create/start an Activity, system pass a mBase instance to Activity by attachBaseContext(Context base) method of Activity.
This is why you get NULL when you call getResources() to set the class variable.
You call the method too early. Call getResources() in onCreate() of later.
There may be some mistakes in this answer, if you wanna know more, read the source:
frameworks/base/core/java/android/app/ActivityThread.java

You are calling getResources() too early in the activity lifecycle.
The activity is usable as a Context only in onCreate() or later. Instance initialization (<init> in your stacktrace) is too early. Move the getResources() and such to onCreate() or later.

I added iconics to app then after remove that from application I comment the code on attachBaseContext. App started to give this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
After I remove attachBaseContext completely, everything is fine.
#Override
protected void attachBaseContext(Context newBase)
{
//super.attachBaseContext(IconicsContextWrapper.wrap(newBase));
}

Related

Null Pointer Exception while setting value of TextView in an Array Adapter class - Android

I'm getting a NullPointerException while trying to start an Activity which contains a ListView .
In the getView method of the adapter class, the exception happens when the setText function of a textView is being called .
The code bellow is my adapter class:
public class QuestionsListAdapter extends ArrayAdapter<Question> {
Context context;
List<Question> questions;
public QuestionsListAdapter(Context context, List<Question> questions){
super(context, R.layout.list_item_question, questions);
this.context = context;
this.questions = questions;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.list_item_question, null);
Question question = questions.get(position);
TextView tv = (TextView) view.findViewById(R.id.question_list_item_string);
Log.i(TableCreator.LOG_TAG, question.toString()); //this works fine and the string is not null .
tv.setText(question.toString()+""); //NULL POINTER EXCEPTION .
return view;
}
}
As you see, I've logged the string in the logcat and it works just fine, but the next line makes the mistake .
And this is the logcat output:
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist I/Operation Checklist﹕ |-Question-> id:1 summary:mySummary comment:myComment solution:mySolution ownerList:dummyOwner
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist D/AndroidRuntime﹕ Shutting down VM
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0f5f648)
05-27 13:24:02.979 5325-5325/org.kabiri.operationcheklist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at org.kabiri.operationchecklist.adapter.QuestionsListAdapter.getView(QuestionsListAdapter.java:43)
at android.widget.AbsListView.obtainView(AbsListView.java:2177)
at android.widget.ListView.makeAndAddView(ListView.java:1840)
at android.widget.ListView.fillDown(ListView.java:675)
at android.widget.ListView.fillFromTop(ListView.java:736)
at android.widget.ListView.layoutChildren(ListView.java:1655)
at android.widget.AbsListView.onLayout(AbsListView.java:2012)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
The logcat shows that the error happens on this line of my adapter class:
tv.setText(question.toString()+"");
I really appreciate your help .
You already know where the problem is!
tv.setText(question.toString()+"");
is causing the NPE that means the TextView tv is null. And that means that the line
TextView tv = (TextView) view.findViewById(R.id.question_list_item_string);
is not able to find the TextView. Check the question_list_item_string id and make sure it matches the id in your list_item_question.xml file

how to set listadapter for fragment

I have two framelayout in my main.xml file. I add framelayouts to the class that extends Fragment. my main class extends FragmentActivity and this is Oncreate method of it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm =getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
Fragment f=new Freg1();
Fragment f2=new Freg1();
ft.add(R.id.frame1, f);
ft.add(R.id.frame2, f2);
ft.commit();
tf=Typeface.createFromAsset(this.getAssets(),"font/Byekan.ttf" );
tv1=(TextView) findViewById(R.id.textView1);
tv1.setTypeface(tf);
Log.i(TAG,"1");
lv1=(ListView) findViewById(R.id.listView1);
lv2=(ListView) findViewById(R.id.listView2);
Log.i(TAG,"2");
List<String> stringList = new ArrayList<String>(Arrays.asList(s1));
Log.i(TAG,"3");
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this , R.layout.custom_list ,stringList);
Log.i(TAG,"4");
lv1.setAdapter(listAdapter);
Log.i(TAG,"5");
lv2.setAdapter(listAdapter);
Log.i(TAG,"6");
}
when i run the codes, it crashed after LOG no4. that mean setAdapter() method do not work. how can i resolve this problem?
this is my logcat resource:
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x40a13300)
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.taxitabriz/com.example.taxitabriz.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.taxitabriz.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
... 11 more
thank for you that help me to resolve problem.
Your ListView lv1 is null as you can see here:
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
....
com.example.taxitabriz.MainActivity.onCreate(MainActivity.java:55)
The line 55 of MainActivity should be this call: lv1.setAdapter(listAdapter);
Make sure that your listView1 is included within the layout and initialized correctly prior to trying to set an Adapter to it.

FTP connection drivehq

I created an Android app which has an FTP connection, however when I start the app it says "unfortunately your app must stopped", and I can't find the problem.
I tried to enter local passive mode however it didn't help me, I also tried to run the app on my phone however it gave me the same message.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button scan;
String contents;
String format;
TextView contentstext;
TextView formattext;
FTPClient ftpclient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------FTP-------------
new FtpTask().execute();
//ftpclient.enterLocalPassiveMode();
try {
ftpclient.changeToParentDirectory();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scan=(Button)findViewById(R.id.scanbutton);
contentstext=(TextView)findViewById(R.id.contentstext);
formattext=(TextView)findViewById(R.id.formattext);
scan.setOnClickListener(this);
}
private class FtpTask extends AsyncTask<Void, Void, FTPClient> {
protected FTPClient doInBackground(Void... args) {
FTPClient ftp = new FTPClient ();
try {
ftp.connect("ftp.drivehq.com");
ftp.login("zule","****");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ftp;
}
protected void onPostExecute(FTPClient result) {
Log.v("FTPTask","FTP connection complete");
ftpclient = result;
}
}
here is the logcat:
09-17 12:11:30.319: E/AndroidRuntime(1113): FATAL EXCEPTION: main
09-17 12:11:30.319: E/AndroidRuntime(1113): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.market/com.example.market.MainActivity}: java.lang.NullPointerException
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.access$600(ActivityThread.java:123)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.os.Looper.loop(Looper.java:137)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-17 12:11:30.319: E/AndroidRuntime(1113): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 12:11:30.319: E/AndroidRuntime(1113): at java.lang.reflect.Method.invoke(Method.java:511)
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-17 12:11:30.319: E/AndroidRuntime(1113): at dalvik.system.NativeStart.main(Native Method)
09-17 12:11:30.319: E/AndroidRuntime(1113): Caused by: java.lang.NullPointerException
09-17 12:11:30.319: E/AndroidRuntime(1113): at com.example.market.MainActivity.onCreate(MainActivity.java:32)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.Activity.performCreate(Activity.java:4465)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
09-17 12:11:30.319: E/AndroidRuntime(1113): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
09-17 12:11:30.319: E/AndroidRuntime(1113): ... 11 more
Look at the stack trace. It says you have a NullPointerException on line 32.
If I counted right, that's this line:
ftpclient.changeToParentDirectory();
Notice that your class member ftpClient is not instantiated; so it's still null when you try to call changeToParentDirectory() on it.
Adding ftpClient = new FtpClient( ... ) somewhere before this call should solve your problem. Add the correct parameters for the dots.

java.lang.RuntimeException: Unable to start activity ComponentInfo Android Eclipse

I know a bunch of people have asked this same thing but I just don't know what's going on. I'm trying to make a calculator in Eclipse, but I keep getting a list of errors.
There are no errors in the file that the program notices, although there is an error in the layout.xml but it hasn't caused a problem before so that shouldn't cause a problem.
07-30 08:19:50.470: D/AndroidRuntime(2071): Shutting down VM
07-30 08:19:50.470: W/dalvikvm(2071): threadid=1: thread exiting with uncaught
exception (group=0x40a421f8)
07-30 08:19:50.480: E/AndroidRuntime(2071): FATAL EXCEPTION: main
07-30 08:19:50.480: E/AndroidRuntime(2071): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.se.miun.chris.calculator/com.example.se.miun.chris.
calculator.MainActivity}: java.lang.NullPointerException
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread.access$600(ActivityThread.java:123)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.os.Handler.dispatchMessage(Handler.java:99)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.os.Looper.loop(Looper.java:137)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread.main(ActivityThread.java:4424)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
java.lang.reflect.Method.invokeNative(Native Method)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
java.lang.reflect.Method.invoke(Method.java:511)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
dalvik.system.NativeStart.main(Native Method)
07-30 08:19:50.480: E/AndroidRuntime(2071): Caused by: java.lang.NullPointerException
07-30 08:19:50.480: E/AndroidRuntime(2071): at
com.example.se.miun.chris.calculator.MainActivity.onCreate(MainActivity.java:60)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.Activity.performCreate(Activity.java:4465)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-30 08:19:50.480: E/AndroidRuntime(2071): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-30 08:19:50.480: E/AndroidRuntime(2071): ... 11 more
This is my coding. It doesn't really do anything yet, but I wanted to just run it to see if it encountered any errors. This is the mainActivity.java file.
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button Seven;
Button Eight;
Button Nine;
Button Four;
Button Five;
Button Six;
Button One;
Button Two;
Button Three;
Button Zero;
Button Point;
Button Negative;
TextView TextBox;
int x;
int y;
String z;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Seven = (Button)findViewById(R.id.NumberSeven);
Seven.setOnClickListener(this);
Eight = (Button)findViewById(R.id.NumberEight);
Eight.setOnClickListener(this);
Nine = (Button)findViewById(R.id.NumberNine);
Nine.setOnClickListener(this);
Four = (Button)findViewById(R.id.NumberFour);
Four.setOnClickListener(this);
Five = (Button)findViewById(R.id.NumberFive);
Five.setOnClickListener(this);
Six = (Button)findViewById(R.id.NumberSix);
Six.setOnClickListener(this);
One = (Button)findViewById(R.id.NumberOne);
One.setOnClickListener(this);
Two = (Button)findViewById(R.id.NumberTwo);
Two.setOnClickListener(this);
Three = (Button)findViewById(R.id.NumberThree);
Three.setOnClickListener(this);
Zero = (Button)findViewById(R.id.NumberZero);
Zero.setOnClickListener(this);
Point = (Button)findViewById(R.id.Point);
Point.setOnClickListener(this);
Negative = (Button)findViewById(R.id.NNegative);
Negative.setOnClickListener(this);
TextBox = (TextView)findViewById(R.id.Screen);
x = (Integer) null;
y = (Integer) null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View One) {
if(z == null){
x = 1;
TextBox.setText(x);
TextBox.setText("diggity");
}
else if(z != null) {
y = 1;
TextBox.setText(x);
TextBox.setText(z);
TextBox.setText(y);
}
}
}
line 60: x = (Integer) null;
This line will compile to this bytecode (disassembled by javap):
aconst_null
checkcast #2; //class java/lang/Integer
invokevirtual #3; //Method java/lang/Integer.intValue:()I
Third line will cause a NullPointerException becouse Integer object is actually your null constant :)
Primitive data types (int, long etc.) is the only non-object types in Java. null is used to show that the current variable (Object variable) is not backed by the actual object (no memory was allocated). For primitive types memory allocates immediately so they cant have this null state.
So you should check for "if(x == 0)" or define it as Integer.
P.S. And don't cast null to anything :)
It's like this
you're not getting much errors because the application can't launch. it cannot launch because it's onCreate() cannot finish.
onCreate() cannot finish because of a nullPointerException.
you cast null into integer twice, instead of simply instantiating a new integer which will default to 0. once you get rid of that, it should work.
see?
E/AndroidRuntime(2071): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2071): at
MainActivity.onCreate(MainActivity.java:60)
and i bet that this is line 60
x = (Integer) null;
so change it to
x = new Integer();

NullPointerException using arrays

I have in one activity:
...
double []mylab=new double [100];
public void compute(){
...
double mytime=Double.parseDouble(timing.getText().toString().trim());
//fill array
for (int i=0;i<=mytime;i++){
mylab[i]=Math.exp(i);
//Arrays.fill(mylab,Math.exp(i));
}
...
i.putExtra("mylab",mylab);
startActivity(i);
}
and in the linegraph activity:
...
private double [] mylab =new double [100];
public double [] getmylab(){ return this.mylab;}
public void setmylab(double [] mylab){ this.mylab=mylab;}
...
public void onCreate(Bundle savedInstanceState){
Bundle extras=getIntent().getExtras();
double [] mylab=extras.getDoubleArray("mylab");
setmylab(mylab);
..
public Intent getIntent(Context context){
double []mylab=getmylab();
ArrayList<Double> x =new ArrayList<Double>();
ArrayList<Double> y =new ArrayList<Double>();
//fill x,y values
for (int i=0;i<=20;i++){
x.add(mytime/i);
}
for (int i=0;i<=20;i++){
y.add(mylab[i]);
}
...
I suppose the error lies where i fill the array?
-------------Logcat------------------------------
FATAL EXCEPTION: main E/AndroidRuntime(461):
java.lang.RuntimeException: Unable to start activity ComponentInfo
java.lang.NullPointerException E/AndroidRuntime(461): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
E/AndroidRuntime(461): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
E/AndroidRuntime(461): at
android.app.ActivityThread.access$2300(ActivityThread.java:125)
E/AndroidRuntime(461): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
E/AndroidRuntime(461): at
android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(461): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(461): at
android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(461): at
java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(461): at
java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(461): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(461): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(461): at dalvik.system.NativeStart.main(Native
Method) E/AndroidRuntime(461): Caused by:
java.lang.NullPointerException E/AndroidRuntime(461): at
com...LineGraph.getIntent(LineGraph.java:109) E/AndroidRuntime(461):
at com..LineGraph.onCreate(LineGraph.java:80) E/AndroidRuntime(461):
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(461): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
if myTime > the size of the myLab array you will get an ArrayIndexOutOfBounds error
double mytime=Double.parseDouble(timing.getText().toString().trim());
//fill array
for (int i=0;i<=mytime;i++)
mylab[i]=Math.exp(i);
//Arrays.fill(mylab,Math.exp(i));
}
The error occurs because you are accessing an array index which does not exist.
Most likely it's when you are filling the array.
// make sure `mytime` is less or equal than 100
for (int i=0;i<=mytime;i++){
mylab[i]=Math.exp(i);
//Arrays.fill(mylab,Math.exp(i));
}
Are you maybe calling
Intent getIntent()
on a newly created instance of the class? Because that might operate on a mylab that is null since the field is initialized as null at creation of each instance.
My mistake!
I had another activity which was on the middle!I had totally forgotten that!I couldn't see it!
Sorry!
Thank you all for your help and especially L7ColWinters :).

Categories