NullPointerException - android.view.Window.findViewById(int) - Why? [duplicate] - java

This question already has answers here:
Android : getting NullPointerException for ImageView imag = (ImageView) findViewById(R.id.image)
(5 answers)
Closed 7 years ago.
I have had multiple problems with android app dev kit and I can't seem to fix it. I tried running my code and this is what shows up in logcat
Here is my main activity:
public class MainActivity extends AppCompatActivity {
EditText input = (EditText) findViewById(R.id.input);
TextView output = (TextView) findViewById(R.id.output);
ArrayList <String> charzart = new ArrayList<String>();
ArrayList <String> color = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
}
});
Button converter = (Button) findViewById(R.id.button);
int begin = 0;
int total = 16777216;
String text = input.getText().toString();
ArrayList<Integer> hexa = new ArrayList<Integer>();
//charzart array
int b = text.length();
for (int i = 1; i <= b; i++) {
charzart.add(text.substring(i - 1, i));
}
//hexa array
int a = text.length() - 1;
for (int z = 0; z < charzart.size(); z++) {
if (charzart.get(z).matches(" ")) {
a--;
}
}
int numb = total / a;
for (int x = 0; x <= 16777216; x = x + numb) {
hexa.add(x);
}
//changing into hexadecimal numbers
for (int y = 0; y < hexa.size(); y++) {
int cvalue = hexa.get(y);
int one, two, three, four, five, six;
one = cvalue / 1048570;
cvalue = cvalue - one * 1048570;
two = cvalue / 65356;
cvalue = cvalue - two * 65356;
three = cvalue / 4096;
cvalue = cvalue - three * 4096;
four = cvalue / 256;
cvalue = cvalue - four * 256;
five = cvalue / 16;
cvalue = cvalue - five * 16;
six = cvalue;
if (one != 16) {
String let = "";
String fin = "#";
switch (one) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
switch (two) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
switch (three) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
switch (four) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
switch (five) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
switch (six) {
case 0:
let = "0";
break;
case 1:
let = "1";
break;
case 2:
let = "2";
break;
case 3:
let = "3";
break;
case 4:
let = "4";
break;
case 5:
let = "5";
break;
case 6:
let = "6";
break;
case 7:
let = "7";
break;
case 8:
let = "8";
break;
case 9:
let = "9";
break;
case 10:
let = "A";
break;
case 11:
let = "B";
break;
case 12:
let = "C";
break;
case 13:
let = "D";
break;
case 14:
let = "E";
break;
case 15:
let = "F";
break;
default:
let = "x";
}
fin += let;
let = "";
color.add(fin);
fin = "#";
} else {
color.add("#FFFFFF");
}
}
//BUTTON
converter.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
String end = "";
for (int p = 0; p < charzart.size(); p++) {
if (charzart.get(p).equals(" ")) {
}
else{
Spannable colorSpan = new SpannableString(charzart.get(p));
int fake = Integer.parseInt(color.get(p));
colorSpan.setSpan(new ForegroundColorSpan(fake), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
end += colorSpan;
}
}
output.setText(end);
}
}
);
}
Here's my layout xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.hitchhikingapps.rainbowz.MainActivity"
tools:showIn="#layout/activity_main">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert"
android:id="#+id/button"
android:layout_marginTop="124dp"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:text="Insert Text here" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/output"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="78dp" />
</RelativeLayout>
And this is an error which I got it:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.hitchhikingapps.rainbowz/com.hitchhikingapps.rainbowz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2090)
at com.hitchhikingapps.rainbowz.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 
Sorry for the great block of code, but I really don't understand what the problem is. Any help would be appreciate

The problem here is that you are initializing your views as global variables:
EditText input = (EditText) findViewById(R.id.input);
TextView output = (TextView) findViewById(R.id.output);
The current context of your views here is Window and not R.layout.activity_main.
If you want to use input and output as global variables, you have only to declare them:
EditText input;
TextView output;
and initialize them in onCreate() after setContentView():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output = (TextView) findViewById(R.id.output);
}

The NPE is because you're calling findViewById() before onCreate() in the activity lifecycle before the activity has a Window. Move the findViewById() calls from member variable initialization to onCreate() and after setContentView() so that a non-null value can be returned.

Related

Generator printing null before the intended output

I've created a random word generator and it seems to work pretty well except for the fact that before the desired output, in the same line, it prints "null".
Here's my code:
import java.util.Random;
public class wordGenerator {
private static String r,s;
public static void randChar(int x) {
Random rand = new Random();
x = rand.nextInt((26 - 1) + 1) + 1;
switch(x) {
case 1: r = "a"; break;
case 2: r = "b"; break;
case 3: r = "c"; break;
case 4: r = "d"; break;
case 5: r = "e"; break;
case 6: r = "f"; break;
case 7: r = "g"; break;
case 8: r = "h"; break;
case 9: r = "i"; break;
case 10: r = "j"; break;
case 11: r = "k"; break;
case 12: r = "l"; break;
case 13: r = "m"; break;
case 14: r = "n"; break;
case 15: r = "o"; break;
case 16: r = "p"; break;
case 17: r = "q"; break;
case 18: r = "r"; break;
case 19: r = "s"; break;
case 20: r = "t"; break;
case 21: r = "u"; break;
case 22: r = "v"; break;
case 23: r = "w"; break;
case 24: r = "x"; break;
case 25: r = "y"; break;
case 26: r = "z"; break;
default: r = "|null|";
}
if(x != 1 && x != 5 && x != 9 && x != 15 && x != 21) {
int h = rand.nextInt(4 - 0);
if(h == 2) {
int k = rand.nextInt(6 - 0);
switch(k) {
case 1: r = "a"; break;
case 2: r = "e"; break;
case 3: r = "i"; break;
case 4: r = "o"; break;
case 5: r = "u"; break;
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
int y = rand.nextInt((10 - 4) + 1) + 4;
for(int z = 1; z < y; z++) {
randChar(0);
s = s + r;
}
System.out.println(s);
}
To me it seems fine, but when I think it should output something like
opfruvme
it prints
nullopfruvme
What's the problem?
You didn't initialize s.
private static String r,s="";
When you start your application in the loop the statement s = s + r; takes null value before concatenating with r in the first cycle. Initializing variable with empty string will give you result that you have been expected.
You didn't initialize s, so then the first time the s = s + r; line executes the current value of s (null) will be coerced to a String, so you will assign "null" + r to s.

How do you place a class in the default package in netbeans for Mac?

My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.

Java randInt switch function issue

I am kind of relatively new to java and am working on a project for class. This is a portion of the system and i have been getting errors in this piece.
public class NumberTest
{
private static void main( String[] args )
{
}
static private char GenerateNumber()
{
int gennumber = 0;
while(gennumber < 3)
{
char returnChar = ' ';
switch(randInt(0,9))
{
case 0:
returnChar = '0';
break;
case 1:
returnChar = '1';
break;
case 2:
returnChar = '2';
break;
case 3:
returnChar = '3';
break;
case 4:
returnChar = '4';
break;
case 5:
returnChar = '5';
break;
case 6:
returnChar = '6';
break;
case 7:
returnChar = '7';
break;
case 8:
returnChar = '8';
break;
case 9:
returnChar = '9';
break;
default:
System.out.println("Error Random int outside expected values");
}
return returnChar;
System.out.println(GenerateNumber());
gennumber++;
}
}
}
The error I am receiving is:
Test.Again.java:12: error: cannot find symbol
switch(randInt(0,9)
symbol: method randInt(int,int)
location: class NumberTest
You are trying to call undeclared function randInt. It means you must first write this function in your class and then use it.
However you may use java.util.Random:
Random rand = new Random();
switch(rand.nextInt() % 10)
...

Number Format Exception when converting a string

The following code won't run and keeps throwing a Number Format Exception on the line the error is "Exception in thread "main" java.lang.NumberFormatException: For input string: "SAN 1905 1808+24 1512+17 1209+10 1708-06 2016-16 211831 211941 192652" ""
intAlt = Integer.parseInt(strAlt);
I'm not sure why this is happening and would appreciate any advice on the matter
private int getPos(String strAlt)
{
int intAlt;
int intPos =0;
intAlt = Integer.parseInt(strAlt);
switch (intAlt)
{
case 3:
intPos = 4;
break;
case 6:
intPos = 9;
break;
case 9:
intPos = 17;
break;
case 12:
intPos = 25;
break;
case 18:
intPos = 33;
break;
case 24:
intPos = 41;
break;
case 30:
intPos = 49;
break;
case 34:
intPos = 56;
break;
case 39:
intPos = 63;
break;
}
return intPos;
}
If you pass "SAN 1905 1808+24 1512+17 1209+10 1708-06 2016-16 211831 211941 192652" into getPos(String strAlt), it will execute:
intAlt = Integer.parseInt(strAlt);
Of course it will throw exception.
See this doc

code for calculations in android

I'm working with an application right now for our project in school. My application is about Resistor Color Code calculation. My codes are working, but in displaying the values, I used the value as string. My problem is I want to make my result value as 1.2K ohms, 1.5M ohm or 5.4M ohms, just like that. Because in my codes the result will display 1200 ohms, 1500K ohms or 5400K ohms. Help me Please. Thanks in advance for the help.
This is my code for a, b, c, d and value is the display in EditText.
calcu is a button.
calcu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//for first band
if (a=="Black")
a = " ";
if (a=="Brown")
a = "1";
if (a=="Red")
a = "2";
if (a=="Orange")
a = "3";
if (a=="Yellow")
a = "4";
if (a=="Green")
a = "5";
if (a=="Blue")
a = "6";
if (a=="Violet")
a = "7";
if (a=="Gray")
a = "8";
if (a=="White")
a = "9";
//for second band
if (b=="Black")
b = "0";
if (b=="Brown")
b = "1";
if (b=="Red")
b = "2";
if (b=="Orange")
b = "3";
if (b=="Yellow")
b = "4";
if (b=="Green")
b = "5";
if (b=="Blue")
b = "6";
if (b=="Violet")
b = "7";
if (b=="Gray")
b = "8";
if (b=="White")
b = "9";
//for multiplier
if (c=="Black")
c = " ";
if (c=="Brown")
c = "0";
if (c=="Red")
c = "00";
if (c=="Orange")
c = "000";
if (c=="Yellow")
c = "0000";
if (c=="Green")
c = "00000";
if (c=="Blue")
c = "000000";
if (c=="Violet")
c = "0000000";
if (c=="Gray")
c = "00000000";
if (c=="White")
c = "000000000";
//for Tolerance
if (d=="Brown")
d = "1";
if (d=="Red")
d = "2";
if (d=="Green")
d = "0.5";
if (d=="Blue")
d = "0.25";
if (d=="Violet")
d = "0.1";
if (d=="Gray")
d = "0.05";
if (d=="Gold")
d = "5";
if (d=="Silver")
d = "10";
Value.setText(a + b + c + "\u2126" + " " + "\u00B1" + d + "%" + " Tolerance");
int result = getTheResult();
String Result = "";
if(result > 0 && result < 1000) Result = "" + result + " Ohms";
else if(result >= 1000 && result < 1000000) Result = "" + (result / 1000) + "K Ohms";
else if (result >= 1000000) Result = "" + (result / 1000000) + "M Ohms";
else Result = "Invalid Value";
import javax.swing.JOptionPane;
public class Resistance {
String digit_band1_color;
String digit_band2_color;
String multiplier_band3_color;
String tolerance_band4_color;
int temp1,temp2,temp3;
double temp4;
double result;
public Resistance(String a,String b,String c,String d){
digit_band1_color=a;
digit_band2_color=b;
multiplier_band3_color=c;
tolerance_band4_color=d;
switch (digit_band1_color){
case "Black":
temp1=0;
break;
case "Brown":
temp1=1;
break;
case "Red":
temp1=2;
break;
case "Orange":
temp1=3;
break;
case "Yellow":
temp1=4;
break;
case "Green":
temp1=5;
break;
case "Blue":
temp1=6;
break;
case "Voilet":
temp1=7;
break;
case "Grey":
temp1=8;
break;
case "White":
temp1=9;
break;
}
switch (digit_band2_color){
case "Black":
temp2=0;
break;
case "Brown":
temp2=1;
break;
case "Red":
temp2=2;
break;
case "Orange":
temp2=3;
break;
case "Yellow":
temp2=4;
break;
case "Green":
temp2=5;
break;
case "Blue":
temp2=6;
break;
case "Voilet":
temp2=7;
break;
case "Grey":
temp2=8;
break;
case "White":
temp2=9;
break;
}
switch (multiplier_band3_color){
case "Black":
temp3=0;
break;
case "Brown":
temp3=1;
break;
case "Red":
temp3=2;
break;
case "Orange":
temp3=3;
break;
case "Yellow":
temp3=4;
break;
case "Green":
temp3=5;
break;
case "Blue":
temp3=6;
break;
case "Voilet":
temp3=7;
break;
case "Grey":
temp3=8;
break;
case "White":
temp3=9;
break;
}
switch (tolerance_band4_color){
case "Brown":
temp4=1;
break;
case "Red":
temp3=2;
break;
case "Orange":
temp4=0.05;
break;
case "Yellow":
temp4=0.02;
break;
case "Green":
temp4=0.5;
break;
case "Blue":
temp4=0.25;
break;
case "Voilet":
temp4=0.1;
break;
case "Grey":
temp4=0.01;
break;
case "Gold":
temp4=5;
break;
case "Silver":
temp4=10;
break;
}
result=Math.pow(10,temp3);
System.out.println("Resistance = "+temp1+temp2+result+"+-"+temp4+"%");
}
public static void main(String[] args) {
String a=JOptionPane.showInputDialog(null,"Please Enter Color in Proper Format like this Black,Brown etc");
String b=JOptionPane.showInputDialog(null,"Please Enter Color in Proper Format like this Black,Brown etc");
String c=JOptionPane.showInputDialog(null,"Please Enter Color in Proper Format like this Black,Brown etc");
String d=JOptionPane.showInputDialog(null,"Please Enter Color in Proper Format like this Black,Brown etc");
Resistance calculator=new Resistance(a,b,c,d);
}
}

Categories