I'm pretty new to Java and Android. I'm trying to make an app that calculates a volume of a liquid in a cylinder, then return the result to a textView box. But now when I click the button to Calculate, it is crashing and I don't know what I'm missing. Everything compiles fine.
package com.somename.fuel.volume.calculator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class CalculateCylinder extends Activity {
EditText length, width, height, depth;
TextView result;
Button calculate;
double firstNum, secNum, thirdNum, volume, area;
double liqVolume;
double radius;
double a, l, aSide,aTop,b,Arc,FluidSurfaceAreaTotal,r,d,v,h,fsal;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculate_cylinder);
calculate = (Button) findViewById(R.id.buttonCylCalc);
length = (EditText) findViewById(R.id.editCylLength);
height = (EditText) findViewById(R.id.editCylHeight);
depth = (EditText) findViewById(R.id.editCylDepth);
result = (TextView) findViewById(R.id.buttonCylResult);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
try {
calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText((CharSequence) result);
}
public TextView calculate() throws Exception {
// TODO Auto-generated method stub
double firstNum = Double.valueOf(length.getText().toString());
double secNum = Double.valueOf(height.getText().toString());
double thirdNum = Double.valueOf(depth.getText().toString());
radius = (secNum/2);
area = ((secNum*secNum)*3.14);
//liqVolume = (firstNum) * (radius*radius)(acos(radius-depth/radius))
// Cubic Volume
v = aSide * l;
// Fluid surface Area, Side
aSide = (r*r)*(3.14 / 2 -Math.acos(1-h/r)) - (r-h)*Math.sqrt(h*(2*r-h));
// Fluid Surface Area Top
aTop = 2*Math.sqrt((r*r)-((r-h)*(r-h) * l));
// Fluid Surface Area Bottom
b = fsal*l;
// Fluid Surface Area Total
FluidSurfaceAreaTotal = 2*aSide+aTop+b;
// Cylinder Radius
r = d/2;
// Cylinder Diameter
d = 2*r;
if (h <= r )
// Fluid Side Arc Length
fsal = 2*r*Math.acos((r-h)/r);
else if (h > r)
fsal = 2*r*(3.14-Math.acos((h-r)/r));
return result;
}
});
}
}
Here is a logcat:
10-18 05:24:38.893: E/AndroidRuntime(964): FATAL EXCEPTION: main
10-18 05:24:38.893: E/AndroidRuntime(964): java.lang.ClassCastException: android.widget.Button
10-18 05:24:38.893: E/AndroidRuntime(964): at com.dbryant423.fuel.volume.calculator.CalculateCylinder$1.onClick(CalculateCylinder.java:55 )
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View.performClick(View.java:2408)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View$PerformClick.run(View.java:8816)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.handleCallback(Handler.java:587)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Looper.loop(Looper.java:123)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-18 05:24:38.893: E/AndroidRuntime(964): at dalvik.system.NativeStart.main(Native Method)
I've been wracking my brains to try to figure out how to do the math on this, and I've not been able to find the answer to why it's crashing. I'm sure it's probably something simple that I've missed somewhere. If you need more information from the other files let me know, but this one seem the be the only one with the problem. I also know that there is unused variables that I've not removed yet.
result.setText((CharSequence) result);
This line cause Exception because you are casting Android View class to CharSequence Class.
Possible Solution:
Change return type of your method public TextView calculate() to
public String calculate()
Now in method public String calculate() return String of result fsal
And your button's Click() is something like,
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
String resultValue = "";
try {
resultValue = calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText( resultValue);
}
result = (TextView) findViewById(R.id.buttonCylResult);
Are you casting properly? based on the naming, i would say that you are casting from a button to TextView. Try changing to,
result = (Button) findViewById(R.id.buttonCylResult);
Related
I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..
Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. Would like to know why it is happening ill display the class and where the error is occuring. Thankyou in advanced.
package com.example.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewRate extends Activity implements OnClickListener {
private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewrate);
setViews();
Bundle extra=getIntent().getExtras();
rowID=extra.getInt(MainActivity.ROW_ID);
fillViews();
convertto = (Button)findViewById(R.id.convertto);
convertfrom =(Button)findViewById(R.id.convertfrom);
convertfrom.setOnClickListener(from);
convertto.setOnClickListener(to);}
private OnClickListener to = new OnClickListener() { <-------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//converttocur();
conRate.setText("pressed"); <------testing still wont work
}
};
private OnClickListener from = new OnClickListener() { <--------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertfromcur();
conRate.setText("pressed"); <--------testing
}
};
private void convertfromcur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(fromrate.getText().toString());
double com = (val / val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void converttocur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(torate.getText().toString());
double com = (val * val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void fillViews() {
// TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id ?", new String[] {String.valueOf(rowID)});
if(c!=null && c.moveToFirst()==true){
String code=c.getString(c.getColumnIndex("Code"));
String sign=c.getString(c.getColumnIndex("Sign"));
String rate=c.getString(c.getColumnIndex("Rate"));
codetv.setText(code);
signtv.setText(sign);
ratetv.setText(rate);
}
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open database");
}
finally{
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void setViews() {
// TODO Auto-generated method stub
codetv=(TextView)findViewById(R.id.code);
signtv=(TextView)findViewById(R.id.sign);
ratetv=(TextView)findViewById(R.id.rate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.viewtask,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.edit:
getEdit();
return true;
case R.id.delete:
getDelete();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void getDelete() {
//TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
sampleDB.delete(tableName, "id= "+rowID,null);
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open dB");
}
finally {
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void getEdit(){
//TODO Auto-generated method stub
Intent addEdit=new Intent(this,AddEdit.class);
addEdit.putExtra("ID",rowID);
addEdit.putExtra("code",codetv.getText().toString());
addEdit.putExtra("sign",signtv.getText().toString());
addEdit.putExtra("rate",ratetv.getText().toString());
startActivity(addEdit);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And so the error is on the button clicks and i getting this error message
E/AndroidRuntime(2524): FATAL EXCEPTION: main
E/AndroidRuntime(2524): java.lang.NullPointerException
E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
E/AndroidRuntime(2524): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2524): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2524): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2524): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2524): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2524): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2524):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2524): at dalvik.system.NativeStart.main(Native Method)
so here is the other logcat
E/AndroidRuntime(2743): FATAL EXCEPTION: main
E/AndroidRuntime(2743): java.lang.NullPointerException
E/AndroidRuntime(2743): at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
E/AndroidRuntime(2743): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2743): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2743): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2743): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2743): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2743): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2743): at dalvik.system.NativeStart.main(Native Method)
I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick.
conRate =(TextView)findViewById(R.id.conRate);
Hope this will help you...:)
One of these values is null:
ratetv
torate
ratetv.getText()
torate.getText()
You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException.
I think you have missed the following in your onCreate()
torate = (EditText) findViewById(R.id.to_rate)
ratetv = (TextView) findViewById(R.id.rate_tv)
Plz first check your all UI components are referenced well in your java file means in activity.
this may be the place where you get NPE.
also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value
Blockquote
just change your code::
Blockquote
you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId == R.id.convertto)
{
//Here write you code when converTo button Clicked
}
else if(v.getId == R.id.converfrom)
{
//Here write your code when converfrom button clicked
}
}
This is my code:
Line no. 94 corresponds to my method of getting all ids.
Always I get an error : Your application has stopped unexpectedly.
package karan.app.caloriecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Main extends Activity implements AdapterView.OnItemSelectedListener {
Button bcal;
TextView intro, choose, duration, min, weight, kg;
EditText dur, weigh;
Spinner sel;
String temp;
public double w, d, calories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get_all_ids();
setArrayAdapter();
sel.setOnItemSelectedListener(this);
bcal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
w = Float.valueOf(weigh.getText().toString());
d = Float.valueOf(dur.getText().toString());
if (temp.contentEquals("Aerobics:general")){
calories = 0.11*w*d;
}
else if (temp.contentEquals("Badminton")){
calories = (w/13)*d;
}
else if (temp.contentEquals("Basketball")){
calories = (w/7.45)*d;
}
else if (temp.contentEquals("Bicycling:slow (10-12 mph)")){
calories = (w/9.65)*d;
}
else if (temp.contentEquals("Bicycling:general (12-14 mph)")){
calories = (w/7.2)*d;
}
else if (temp.contentEquals("Bicycling:moderate (14-16 mph)")){
calories = (w/6)*d;
}
else if (temp.contentEquals("Bicycling:fast (16+ mph)")){
calories = (w/5)*d;
}
else if (temp.contentEquals("Bowling")){
calories = (w/19.1)*d;
}
else if (temp.contentEquals("Boxing: punching bag")){
calories = (w/9.6)*d;
}
else if (temp.contentEquals("Boxing: sparring")){
calories = (w/6.375)*d;
}
/* Thread t = new Thread(){
public void run(){
try{
sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openResult = new Intent("karan.app.caloriecalculator.RESULT");
startActivity(openResult);
}
}
}; // close the thread with a ;
*/
}});
}
public void get_all_ids() {
bcal.findViewById(R.id.b1);
intro.findViewById(R.id.tv1);
choose.findViewById(R.id.tv2);
duration.findViewById(R.id.tv3);
min.findViewById(R.id.tv4);
weight.findViewById(R.id.tv5);
kg.findViewById(R.id.tv6);
dur.findViewById(R.id.et2);
weigh.findViewById(R.id.et1);
sel.findViewById(R.id.sp1);
}
public double getCalories() {
return calories;
}
public void setArrayAdapter(){
//The createFromResource() method allows you to create an ArrayAdapter from the string array
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_dropdown_item);
//You should then call setDropDownViewResource(int) to specify the layout the adapter should use to display the list of spinner choices
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Call setAdapter() to apply the adapter to your Spinner.
sel.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Object item = parent.getItemAtPosition(position);
temp = item.toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
LogCat:
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Looper.loop(Looper.java:123)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 14:10:03.545: E/AndroidRuntime(266): at dalvik.system.NativeStart.main(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): Caused by: java.lang.NullPointerException
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.get_all_ids(MainActivity.java:96)
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.onCreate(MainActivity.java:28)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 14:10:03.545: E/AndroidRuntime(266): ... 11 more
You are incorrectly fetching views in get_all_ids().
To get a view, you must do:
TextView intro;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intro = (TextView) findViewById(R.id.tv1);
....
}
// You can now use intro and methods of TextView class.
I recommend you read the Android Beginner Guides.
i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.
Well, my program keeps giveing me a null point exception and I don't know why? I know it has something to do with the lvl variable, but I don't know what? What can I do to fix this problem?
Logcat:
03-18 16:14:55.852: ERROR/AndroidRuntime(277): FATAL EXCEPTION: main
03-18 16:14:55.852: ERROR/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.games.think/com.games.think.Think}: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): Caused by: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.games.think.Think.onCreate(Think.java:38)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): ... 11 more
Here is some of my code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class Think extends Activity implements OnClickListener{
int question = 1, lvl;
/** Called when the activity is first created. */
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button exit = (Button)findViewById(R.id.exit);
exit.setOnClickListener(this);
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)findViewById(R.id.lvl1);
lvl2 = (RadioButton)findViewById(R.id.lvl2);
lvl3 = (RadioButton)findViewById(R.id.lvl3);
lvl4 = (RadioButton)findViewById(R.id.lvl4);
lvl5 = (RadioButton)findViewById(R.id.lvl5);
lvl = getLevel();
if(lvl == -1) {
lvl=getLevel();
}
}
#SuppressWarnings("null")
private int getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return -1;
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
int iLevel = Integer.valueOf(level);
return iLevel;
}
private void setLevel(String level) {
String FILENAME = "think_level";
String string = level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
case R.id.level:
setContentView(R.layout.level);
switch(getLevel()) {
case 1:
lvl1.setChecked(true);
case 2:
lvl2.setChecked(true);
case 3:
lvl3.setChecked(true);
case 4:
lvl4.setChecked(true);
case 5:
lvl5.setChecked(true);
}
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
}
}
private void setQuestion() {
}
}
Check if the button with id "setLevel" is in your main.xml. If it is somewhere else, you can not find it like this:
Button setLevel = (Button)findViewById(R.id.setLevel);
But you need an inflater.
If iunderstand this is 37-38 lines
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
Seems like setLevel is null. Is button with id setLevel described in xml layout ?
Button setLevel = (Button)findViewById(R.id.setLevel);
This line is not returning an object. Make sure you have the id right and that there is a button registered with it.