java.lang.NullPointerException Cant figure out what is causing the error - java

I am creating a VERY basic POS system for an assignment for class. I keep getting that dreaded nullpointerexception. I know the error is coming from line 72 in main activity but it is declared in both the main activity and in the xml.
Here is the logcat:
10-07 18:05:36.946: D/AndroidRuntime(1279): Shutting down VM
10-07 18:05:36.946: W/dalvikvm(1279): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-07 18:05:36.958: E/AndroidRuntime(1279): FATAL EXCEPTION: main
10-07 18:05:36.958: E/AndroidRuntime(1279): java.lang.RuntimeException: Unable to start activity ComponentInfo{hotchkissmobilesolutions.kudlerpos/hotchkissmobilesolutions.kudlerpos.MainActivity}: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Handler.dispatchMessage(Handler.java:99)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Looper.loop(Looper.java:137)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invokeNative(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invoke(Method.java:525)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-07 18:05:36.958: E/AndroidRuntime(1279): at dalvik.system.NativeStart.main(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): Caused by: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at hotchkissmobilesolutions.kudlerpos.MainActivity.onCreate(MainActivity.java:72)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Activity.performCreate(Activity.java:5133)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-07 18:05:36.958: E/AndroidRuntime(1279): ... 11 more
Here is the android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hotchkissmobilesolutions.kudlerpos"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="hotchkissmobilesolutions.kudlerpos.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
here is the Main Activity:
package hotchkissmobilesolutions.kudlerpos;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
double dairy = 4.99, seafood = 15.99, wine = 20, meat = 5.99,
cheese = 2.99, fruit = 1.99, vegetable = 0.69;
double total, tax = 0.0725;
String total2;
Button btnDairy, btnSeafood, btnWine, btnMeat, btnFruit, btnVegetable,
btnTotal, btnClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
btnDairy.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + dairy) + (total * tax);
System.out.println(total);
}
});
btnSeafood.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + seafood) + (total * tax);
System.out.println(total);
}
});
btnWine.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + wine) + (total * tax);
System.out.println(total);
}
});
btnMeat.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + meat) + (total * tax);
System.out.println(total);
}
});
btnFruit.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + fruit) + (total * tax);
System.out.println(total);
}
});
btnVegetable.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + vegetable) + (total * tax);
System.out.println(total);
}
});
btnTotal.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
System.out.println(total2);
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = 0;
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
}
});
}
and here is the activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<GridLayout
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:columnCount="6"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:rowCount="8"
tools:context=".MainActivity"
tools:targetApi="14" >
<TextView android:id="#+id/txtViewInstructions"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="0"
android:text="#string/InstructionText"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnDairy"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="3"
android:onClick="onCLickDairy"
android:text="#string/Dairy" />
<Button android:id="#+id/btnWine"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="3"
android:onClick="onCLickWine"
android:text="#string/Wine" />
<Button android:id="#+id/btnMeat"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="4"
android:onClick="onCLickMeat"
android:text="#string/Meat" />
<Button android:id="#+id/btnSeafood"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="4"
android:onClick="onCLickSeafood"
android:text="#string/Seafood" />
<Button android:id="#+id/btnVegetable"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="5"
android:onClick="onCLickVegetable"
android:text="#string/Vegetable" />
<TextView android:id="#+id/txtViewTotalDue"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="7"
android:text="#string/TotalDue"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView android:id="#+id/textViewTotal"
android:layout_width="260dp"
android:layout_height="93dp"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="6"
android:text="#string/total"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnTotal"
android:layout_column="0"
android:layout_gravity="left|center_vertical"
android:layout_row="7"
android:onClick="onCLickTotal"
android:text="#string/TotalButton" />
<Button android:id="#+id/btnFruit"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="5"
android:onClick="onCLickFruit"
android:text="#string/Fruit" />
<Button android:id="#+id/btnClear"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="7"
android:text="#string/ClearButton" />
</GridLayout>
Any help in finding the issue with the btnTotal line in the main activity.java would be so helpful. Thanks in advance!

You don't have a btnTotal so when you click on it, the value is null.
See:
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
//add this
btnTotal = (Button) findViewById(R.id.btnTotal);
No button for btnTotal. Add that button and you'll be fine. Simple mistake. Happens all the time. Good luck.

You did not initialise your total field, so it throws NPE

Related

App stopped working as soon as i clicked the button

I built a simple project that squares a given number. In that app as soon as i click the button "Calculate" it say's "Unfortunately, SquareCalculator has stopped". What should i do to resolve the problem?
Below is my entire code:-
MainActivity.java
package thenerdimite.squarecalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
}
activity_main.xml
<?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"
tools:context="thenerdimite.squarecalculator.MainActivity">
<EditText
android:id="#+id/etInput"
android:layout_width="245dp"
android:layout_height="41dp"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="62dp"
android:layout_below="#+id/tvInput"
android:layout_alignStart="#+id/tvInput" />
<Button
android:id="#+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/etInput"
android:layout_below="#+id/etInput"
android:layout_marginTop="20dp"
android:onClick="Calculate"
android:text="Calculate"
android:textSize="18sp" />
<TextView
android:id="#+id/tvOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_below="#+id/btnCalculate"
android:layout_alignStart="#+id/btnCalculate"
android:layout_marginTop="18dp" />
<TextView
android:id="#+id/tvInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter an Integer:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_marginStart="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
logcat
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator D/AndroidRuntime: Shutting down VM
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa5007678)
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method Calculate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnCalculate'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
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)
04-25 09:28:06.740 3596-3596/? I/Process: Sending signal. PID: 3596 SIG: 9
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thenerdimite.squarecalculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Using the documentation of Button
You see the method need to be public and accept a View
In order for this to work, the method must be public and accept a View as its only parameter.
So it should be
public void Calculate (View v){
Using the xml notation, of course, you should call it calculate and correct the XML
From what I see, the problem is that your button action is android:onClick="Calculate" but should be android:onClick="calculate"
you need to make the method public, protected and private methods are not accessible by xml.
public void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
Change android:onClick="Calculate" to android:onClick="calculate".
Also calculate method should be public.
In XML you have "Calculate" with capital "C" while method is called "calculate". Change XML and it should work.
https://developer.android.com/reference/android/widget/Button.html

Android application crashed

I'm doing an app for Android. I have a main activity (not the default MainActivity.java, other activity named HotelPresentacion.java that has 3 buttons for insert/check registers or exit the app).
If I touch the Registrar button, supposedly I can register, but the app stops unexpectedly. If I touch the Registros button I can visualize the registers of my app, but when I touch one register (a short touch or long short) for only visualize or edit the app again stops unexpectedly.
I modified my androidmanifest.xml to set HotelPresentacion.java as my default starting activity.
This is the code of the HotelPresentacion.java
package com.example.lab007;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class HotelPresentacion extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_presentacion);
}
public void onReservar(View v){
Intent i=new Intent(HotelPresentacion.this, ReservacionFormulario.class);
startActivity(i);
}
public void onVer(View v){
Intent i=new Intent(HotelPresentacion.this, MainActivity.class);
startActivity(i);
}
public void onSalir(View v){
finish();
}
}
My androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab007"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HotelPresentacion"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.lab007.ReservacionFormulario"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.lab007.MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
LOGCAT
10-25 11:16:38.880: E/AndroidRuntime(4247): FATAL EXCEPTION: main
10-25 11:16:38.880: E/AndroidRuntime(4247): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab007/com.example.lab007.ReservacionFormulario}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.os.Handler.dispatchMessage(Handler.java:99)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.os.Looper.loop(Looper.java:130)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread.main(ActivityThread.java:3687)
10-25 11:16:38.880: E/AndroidRuntime(4247): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 11:16:38.880: E/AndroidRuntime(4247): at java.lang.reflect.Method.invoke(Method.java:507)
10-25 11:16:38.880: E/AndroidRuntime(4247): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
10-25 11:16:38.880: E/AndroidRuntime(4247): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
10-25 11:16:38.880: E/AndroidRuntime(4247): at dalvik.system.NativeStart.main(Native Method)
10-25 11:16:38.880: E/AndroidRuntime(4247): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ListActivity.onContentChanged(ListActivity.java:243)
10-25 11:16:38.880: E/AndroidRuntime(4247): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:212)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.Activity.setContentView(Activity.java:1657)
10-25 11:16:38.880: E/AndroidRuntime(4247): at com.example.lab007.ReservacionFormulario.onCreate(ReservacionFormulario.java:39)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-25 11:16:38.880: E/AndroidRuntime(4247): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
10-25 11:16:38.880: E/AndroidRuntime(4247): ... 11 more
The class ReservacionFormulario.java
package com.example.lab007;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class ReservacionFormulario extends ListActivity{
private ComplejoDBAdapter dbAdapterComplejo;
private ComplejoSpinnerAdapter complejoSpinnerAdapter;
private int modo ;
private long id ;
private Reservacion reserva = new Reservacion(this);
private EditText nombre;
private EditText apellidos;
//private DatePicker fechaInicio;
//private DatePicker fechaFin;
private Spinner complejo ;
private Button boton_guardar;
private Button boton_cancelar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservacion_formulario);
Intent intent = getIntent();
Bundle extra = intent.getExtras();
if (extra == null) return;
nombre = (EditText) findViewById(R.id.nombre);
apellidos = (EditText) findViewById(R.id.apellidos);
//fechaInicio = (DatePicker) findViewById(R.id.);
//fechaInicio = (DatePicker) findViewById(R.id.);
complejo = (Spinner) findViewById(R.id.complejo);
boton_guardar = (Button) findViewById(R.id.boton_guardar);
boton_cancelar = (Button) findViewById(R.id.boton_cancelar);
complejoSpinnerAdapter = new ComplejoSpinnerAdapter(this, Complejo.getAll(this, null));
complejo.setAdapter(complejoSpinnerAdapter);
if (extra.containsKey(ReservacionDBAdapter.C_COL_ID)){
id = extra.getLong(ReservacionDBAdapter.C_COL_ID);
consultar(id);
}
establecerModo(extra.getInt(ReservacionActivity.C_MODO));
boton_guardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
guardar();
}
});
boton_cancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
cancelar();
}
});
}
private void establecerModo(int m)
{
this.modo = m ;
if (modo == ReservacionActivity.C_VISUALIZAR){
this.setTitle(nombre.getText().toString());
this.setEdicion(false);
}
else if (modo == ReservacionActivity.C_CREAR){
this.setTitle("Nuevo reservacion");
this.setEdicion(true);
}
else if (modo == ReservacionActivity.C_EDITAR){
this.setTitle("Editar reservacion");
this.setEdicion(true);
}
}
private void consultar(long id){
reserva = Reservacion.find(this, id);
nombre.setText(reserva.getNombre());
apellidos.setText(reserva.getApellidos());
complejo.setSelection(complejoSpinnerAdapter.getPositionById(reserva.getComplejoId()));
}
private void setEdicion(boolean opcion){
nombre.setEnabled(opcion);
apellidos.setEnabled(opcion);
complejo.setEnabled(opcion);
// Controlamos visibilidad de botonera
LinearLayout v = (LinearLayout) findViewById(R.id.botonera);
if (opcion)
v.setVisibility(View.VISIBLE);
else
v.setVisibility(View.GONE);
}
private void guardar(){
/*verificar si funciona*/
try{
if(nombre.length()<=0){
reserva.setNombre(nombre.getText().toString());
}
}catch(Exception e){
}
reserva.setApellidos(apellidos.getText().toString());
reserva.setComplejoId(complejo.getSelectedItemId());
reserva.save();
if (modo == ReservacionActivity.C_CREAR){
Toast.makeText(ReservacionFormulario.this, "Creado", Toast.LENGTH_SHORT).show();
}
else if (modo == ReservacionActivity.C_EDITAR){
Toast.makeText(ReservacionFormulario.this, "Modificado", Toast.LENGTH_SHORT).show();
}
setResult(RESULT_OK);
finish();
}
private void cancelar(){
setResult(RESULT_CANCELED, null);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
if (modo == ReservacionActivity.C_VISUALIZAR)
getMenuInflater().inflate(R.menu.reservacion_formulario_ver, menu);
else
getMenuInflater().inflate(R.menu.reservacion_formulario_editar, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case R.id.menu_eliminar:
borrar(id);
return true;
case R.id.menu_cancelar:
cancelar();
return true;
case R.id.menu_guardar:
guardar();
return true;
case R.id.menu_editar:
establecerModo(ReservacionActivity.C_EDITAR);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void borrar(final long id){
AlertDialog.Builder dialogEliminar = new AlertDialog.Builder(this);
dialogEliminar.setIcon(android.R.drawable.ic_dialog_alert);
dialogEliminar.setTitle("Eliminar");
dialogEliminar.setMessage("¿Desea eliminar?");
dialogEliminar.setCancelable(false);
dialogEliminar.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int boton) {
reserva.delete();
Toast.makeText(ReservacionFormulario.this, "Eliminado", Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
});
dialogEliminar.setNegativeButton(android.R.string.no, null);
dialogEliminar.show();
}
}
The activity_reservacion_formulario.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<!-- Nombre -->
<TextView
android:id="#+id/label_nombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre" />
<EditText
android:id="#+id/nombre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/label_nombre"
android:maxLength="40"
android:ems="10" />
<!-- Apellidos -->
<TextView
android:id="#+id/label_apellidos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nombre"
android:maxLength="60"
android:text="Apellidos" />
<EditText
android:id="#+id/apellidos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/label_apellidos"
android:ems="10" />
<!-- Fecha de Inicio -->
<!-- <TextView
android:id="#+id/label_fechainicio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/apellidos"
android:text="Fecha de Inicio" />
<DatePicker
android:id="#+id/datePickerInicio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/label_fechainicio" /> -->
<!-- Fecha de Fin -->
<!-- <TextView
android:id="#+id/label_fechafin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/datePickerInicio"
android:text="Fecha de Fin" />
<DatePicker
android:id="#+id/datePickerFin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/label_fechafin" /> -->
<!-- Spinner -->
<TextView
android:id="#+id/label_complejo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/datePickerFin"
android:text="Complejo" />
<Spinner
android:id="#+id/complejo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/label_complejo" />
<TextView
android:id="#+id/label_ciudad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Complejo"
android:layout_below="#+id/complejo" />
<LinearLayout
android:id="#+id/botonera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_below="#+id/datePickerFin"
android:orientation="horizontal" >
<Button
android:id="#+id/boton_cancelar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancelar" />
<Button
android:id="#+id/boton_guardar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Guardar" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
This is the entire project:
Project
I'll appreciante any help for solve my problem. Thanks
Replace
public class ReservacionFormulario extends ListActivity{
with
public class ReservacionFormulario extends Activity{
As you have extended the ListActivity so Android is searching for the a ListView with Id list, but In your XML there is no any such type of ListView.
From the crash log i guess its.
Change ListActivity to Activity

Eclipse "Sorry- The application (Appname) has stopped unexpectedly. Please try again"

Hey im a begginer in android coding and ive been following this series on youtube. Whenever I run my project as an android application and go to the emulator to select it, it gives me "Sorry- The application (Appname) has stopped unexpectedly. Please try again" Eclipse doesnt give me any error line to where the problem is and so it is very frustrating.. Ive been looking on the internet for answers to this, but I havent been able to fix it. I think it has something to do with my Manifest. Whenever i run my application there are errors on my LogCat.
My application is a small app that when selected will first open a logo screen for 3 seconds then it will take you to an interface where there are 2 buttons to choose from. Both buttons lead to this thing that edits text.
Ive posted all my code below and please guys keep in mind when you answer that I am a begginer and might not understand some terms. Thank you!
Here is my LogCat when i try to start it
07-20 20:19:17.382: D/dalvikvm(254): GC_EXTERNAL_ALLOC freed 663 objects / 51912 bytes in 177ms
07-20 20:19:19.791: D/AndroidRuntime(254): Shutting down VM
07-20 20:19:19.801: W/dalvikvm(254): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-20 20:19:19.811: E/AndroidRuntime(254): FATAL EXCEPTION: main
07-20 20:19:19.811: E/AndroidRuntime(254): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.thepasics/com.example.thepasics.Menu}: java.lang.ClassNotFoundException: com.example.thepasics.Menu in loader dalvik.system.PathClassLoader[/data/app/com.example.thepasics-2.apk]
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.os.Looper.loop(Looper.java:123)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-20 20:19:19.811: E/AndroidRuntime(254): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 20:19:19.811: E/AndroidRuntime(254): at java.lang.reflect.Method.invoke(Method.java:521)
07-20 20:19:19.811: E/AndroidRuntime(254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-20 20:19:19.811: E/AndroidRuntime(254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-20 20:19:19.811: E/AndroidRuntime(254): at dalvik.system.NativeStart.main(Native Method)
07-20 20:19:19.811: E/AndroidRuntime(254): Caused by: java.lang.ClassNotFoundException: com.example.thepasics.Menu in loader dalvik.system.PathClassLoader[/data/app/com.example.thepasics-2.apk]
07-20 20:19:19.811: E/AndroidRuntime(254): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
07-20 20:19:19.811: E/AndroidRuntime(254): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
07-20 20:19:19.811: E/AndroidRuntime(254): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-20 20:19:19.811: E/AndroidRuntime(254): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
07-20 20:19:19.811: E/AndroidRuntime(254): ... 11 more
My Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.thepasics"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.thepasics.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="Menu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.thePasics.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".TutorialOne"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.thePasics.TUTORIALONE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
I have 3 Java files which are Menu.java Main.java TutorialOne.java. This one is the Main one
package com.example.thepasics;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class Main extends Activity {
MediaPlayer logoMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
logoMusic = MediaPlayer.create(Main.this, R.raw.music);
logoMusic.start();
Thread logoTimer = new Thread(){
public void run(){
try{
sleep(2000);
Intent menuIntent = new Intent("com.example.thePasics.MENU");
startActivity(menuIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
logoMusic.release();
}
}
This One is the menu.java
package com.example.thepasics;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class menu extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Button sound
final MediaPlayer buttonSound = MediaPlayer.create(menu.this, R.raw.buttonsound);
//Setting up button references
Button tut1 = (Button) findViewById(R.id.button1);
Button tut2 = (Button) findViewById(R.id.button2);
tut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonSound.start();
startActivity(new Intent("com.example.thepasics.TUTORIALONE"));
}
});
tut2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonSound.start();
startActivity(new Intent("com.example.thepasics.TutorialOne"));
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
The third one is the TutorialOne.java
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class TutorialOne extends Activity implements OnCheckedChangeListener{
TextView textOut;
EditText textIn;
RadioGroup gravityG, styleG;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial1);
textOut = (TextView) findViewById(R.id.tvChange);
textIn = (EditText) findViewById(R.id.editText1);
gravityG = (RadioGroup) findViewById(R.id.rgGravity);
gravityG.setOnCheckedChangeListener(this);
styleG = (RadioGroup) findViewById(R.id.rgStyle);
styleG.setOnCheckedChangeListener(this);
Button gen = (Button) findViewById(R.id.bGenerate);
gen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textOut.setText(textIn.getText());
}
});
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.rbLeft:
textOut.setGravity(Gravity.LEFT);
break;
case R.id.rbCenter:
textOut.setGravity(Gravity.CENTER);
break;
case R.id.rbRight:
textOut.setGravity(Gravity.RIGHT);
break;
case R .id.rbNormal:
textOut.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL), Typeface.NORMAL);
break;
case R .id.rbItalic:
textOut.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC), Typeface.ITALIC);
break;
case R .id.rbBold:
textOut.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD), Typeface.BOLD);
break;
}
}
}
My 3 xml files are splash, tutorial1 and main
this one is main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/backgroundwithoutericapp"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Choose a function" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button1"
android:textSize="25dp"
android:textStyle="bold"
android:id="#+id/button1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button2"
android:textSize="25dp"
android:textStyle="bold"
android:id="#+id/button2"/>
</LinearLayout>
second one is splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/background">
</LinearLayout>
third one is tutorial1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/tutorialonebackground"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvStyle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="Style"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvGravity"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="Gravity"
android:textSize="25dp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<RadioButton
android:id="#+id/rbNormal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal" />
<RadioButton
android:id="#+id/rbItalic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Italic" />
<RadioButton
android:id="#+id/rbBold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgGravity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<RadioButton
android:id="#+id/rbLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left" />
<RadioButton
android:id="#+id/rbCenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Center" />
<RadioButton
android:id="#+id/rbRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right" />
</RadioGroup>
</LinearLayout>
<TextView
android:id="#+id/tvChange"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Type in Text and Press the Button Below" />
<Button
android:id="#+id/bGenerate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate" />
</LinearLayout>
You have specified wrong class name in manifest.xml
Replace
<activity
android:name="Menu"
android:label="#string/app_name" >
with
<activity
android:name="com.example.thepasics.menu"
android:label="#string/app_name" >
Your Manifest and menu activity don't match. Your manifest has
<activity
android:name="Menu" ...
which first of all isn't a valid name. It could be either android:name=".Menu" to refer to com.com.example.thepasics.Menu or you could use the fully qualified name (as you did for com.example.thepasics.Main).
In addition, your class is named menu, not Menu - remember it is case sensitive. Java convention has class names starting with a capital letter, so it should probably be corrected to Menu.
Your Menu class is actually called "menu" and not "MENU".
public class menu extends Activity{
Try changing "com.example.thePasics.MENU" to "com.example.thePasics.menu" throughout your app.
I only have looked into your Logcat:
07-20 20:19:19.801: W/dalvikvm(254): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-20 20:19:19.811: E/AndroidRuntime(254): FATAL EXCEPTION: main
07-20 20:19:19.811: E/AndroidRuntime(254): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.thepasics/com.example.thepasics.Menu}: java.lang.ClassNotFoundException: com.example.thepasics.Menu in loader dalvik.system.PathClassLoader[/data/app/com.example.thepasics-2.apk]
Your app is crashing becuase your com.example.thepasics.Menu is not being found, and also use android:name=".Menu" instead of android:name="Menu".

FATAL EXCEPTION: Main java.lang.RuntimeException:

I know there are already numerous entries about how to solve a Fatal Exception, but none of them solved my problem. I am working on a very simple calculator that has nine buttons, an edit text, and a text view. The whole purpose of it is to simply be able to key in a number, hit a button with another number on it, and the product of those will appear in the text view.
<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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:text="#string/number" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:layout_marginLeft="16dp"
android:layout_marginTop="23dp"
android:text="#string/s1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:text="#string/s2" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/textView1"
android:text="#string/s3" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="16dp"
android:text="#string/s4" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button4"
android:layout_alignBottom="#+id/button4"
android:layout_alignLeft="#+id/button2"
android:text="#string/s5" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button5"
android:layout_alignBottom="#+id/button5"
android:layout_alignLeft="#+id/button3"
android:text="#string/s6" />
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button4"
android:layout_below="#+id/button4"
android:layout_marginTop="22dp"
android:text="#string/s7" />
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button7"
android:layout_alignBottom="#+id/button7"
android:layout_alignLeft="#+id/button5"
android:text="#string/s8" />
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button8"
android:layout_alignBottom="#+id/button8"
android:layout_alignLeft="#+id/button6"
android:text="#string/s9" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button8"
android:layout_below="#+id/button8"
android:layout_marginTop="70dp"
/>
</RelativeLayout>
I finally ironed out all the kinks, or so I thought, but now when I try to run the program it stops unexpectedly before even loading:
11-10 11:50:13.198: E/AndroidRuntime(451): FATAL EXCEPTION: main
11-10 11:50:13.198: E/AndroidRuntime(451): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.deitel.multiplicationtables/com.deitel.multiplicationtables.Main}: java.lang.InstantiationException: com.deitel.multiplicationtables.Main
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.os.Looper.loop(Looper.java:123)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-10 11:50:13.198: E/AndroidRuntime(451): at java.lang.reflect.Method.invokeNative(Native Method)
11-10 11:50:13.198: E/AndroidRuntime(451): at java.lang.reflect.Method.invoke(Method.java:507)
11-10 11:50:13.198: E/AndroidRuntime(451): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-10 11:50:13.198: E/AndroidRuntime(451): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-10 11:50:13.198: E/AndroidRuntime(451): at dalvik.system.NativeStart.main(Native Method)
11-10 11:50:13.198: E/AndroidRuntime(451): Caused by: java.lang.InstantiationException: com.deitel.multiplicationtables.Main
11-10 11:50:13.198: E/AndroidRuntime(451): at java.lang.Class.newInstanceImpl(Native Method)
11-10 11:50:13.198: E/AndroidRuntime(451): at java.lang.Class.newInstance(Class.java:1409)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-10 11:50:13.198: E/AndroidRuntime(451): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
11-10 11:50:13.198: E/AndroidRuntime(451): ... 11 more
11-10 11:55:13.367: I/Process(451): Sending signal. PID: 451 SIG: 9
I know it's probably some small over sight, but I can't find what it is that I have messed up on. Any assistance is appreciated!
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.deitel.multiplicationtables"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
JAVA Code:
package com.deitel.multiplicationtables;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
//Implements the listener for an onclick event (implements View.onClickListener)
public abstract class Main extends Activity implements View.OnClickListener{
// creates a button
private Button bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine;
// Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//assigns the resource id of 1 - 9 to each button.
bone = (Button) findViewById(R.id.button1);
btwo = (Button) findViewById(R.id.button2);
bthree = (Button) findViewById(R.id.button3);
bfour = (Button) findViewById(R.id.button4);
bfive = (Button) findViewById(R.id.button5);
bsix = (Button) findViewById(R.id.button6);
bseven = (Button) findViewById(R.id.button7);
beight = (Button) findViewById(R.id.button8);
bnine = (Button) findViewById(R.id.button9);
//Adds the buttons to the onclicklistener
bone.setOnClickListener(this);
btwo.setOnClickListener(this);
bthree.setOnClickListener(this);
bfour.setOnClickListener(this);
bfive.setOnClickListener(this);
bsix.setOnClickListener(this);
bseven.setOnClickListener(this);
beight.setOnClickListener(this);
bnine.setOnClickListener(this);
}
//creates a method (or action) for when the button is clicked.
public void onclick(View view)
{
//Makes a variable for the entered number
Double amount = 0.0;
Double product = 0.0;
Double variable = 0.0;
// constants
final double one = 1.0;
final double two = 2.0;
final double three = 3.0;
final double four = 4.0;
final double five = 5.0;
final double six = 6.0;
final double seven = 7.0;
final double eight = 8.0;
final double nine = 9.0;
if (view.getId() == R.id.button1)
{
variable = one;
}
if (view.getId() == R.id.button2)
{
variable = two;
}
if (view.getId()== R.id.button3)
{
variable = three;
}
if (view.getId() == R.id.button4)
{
variable = four;
}
if (view.getId() == R.id.button5)
{
variable = five;
}
if (view.getId()== R.id.button6)
{
variable = six;
}
if (view.getId() == R.id.button7)
{
variable = seven;
}
if (view.getId() == R.id.button8)
{
variable = eight;
}
if (view.getId()== R.id.button9)
{
variable = nine;
}
//creates an editext and assigns the resource id of the xml edittext.
EditText number = (EditText)findViewById(R.id.editText1);
//Receives the input from the edittext, converts it to a double (number).
amount = Double.parseDouble(number.getText().toString());
//Calculates the product
product = variable * amount;
//Creates a textview object, assigns the xml r.id, and then changes the text to report the amount.
TextView t = (TextView)findViewById(R.id.textView2);
t.setText("Your product is: " + product);
}
}
Remove abstract keyword from your class and it should work
The log clearly says
Caused by: java.lang.InstantiationException: com.deitel.multiplicationtables.Main
check your Main class, it should not be abstract.

java.lang.NullPointerException when trying to access SQLite database

I am trying to create a login page which checks a SQLite database for the users details, and if they are present, they are advanced to the main page of the application. I keep getting the java.lang.NullPointerException and do not know what I am doing wrong. Please can you advise on where the issues are in the code?
Login.java:
package com.B00512756.angertwo;
public class Login extends Activity implements OnClickListener{
public static final String DATABASE_NAME = "login_database.db";
public static final String USER_INFO_TABLE = "user_information";
public static final String COLUMN_ID = "UserID";
public static final String COLUMN_RATING = "UserName";
public static final String COLUMN_NAME = "Password";
public SQLiteDatabase regDB;
public EditText txtUserName;
public EditText txtPassword;
public static Button btnLogin;
public static Button btnCancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
//btnLogin=(Button)this.findViewById(R.id.btnLogin);
Button Login = (Button) findViewById(R.id.btnLogin);
Button Register = (Button) findViewById(R.id.btnregister);
Button Cancel = (Button) findViewById(R.id.btnCancel);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Registration.class);
startActivityForResult(myIntent, 0);
finish();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
android.os.Process.killProcess(android.os.Process.myPid());
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(COLUMN_ID);
int iRating = c.getColumnIndex(COLUMN_RATING);
int iName = c.getColumnIndex(COLUMN_NAME);
c.moveToLast();
for (int i = c.getCount() - 1; i >= 0; i--) {
// Get the data
result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
if("select * from USER_INFO_TABLE where UserName =" + "\""+ txtUserName + "\""+" and Password="+ "\""+ txtPassword != null);
{ Intent j = new Intent();
j.setClassName("com.B00512756.angertwo",
"com.B00512756.angertwo.AngerprototypetwoActivity");
startActivity(j);}
// Move the cursor
c.moveToPrevious();
//return result;
}
c.close();
}
});
}
private SQLiteDatabase getWritableDatabase() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Loginpage.xml:
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="User Name: "
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:text=""
android:id="#+id/txtUname"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password: "
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:text=""
android:id="#+id/txtPwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true">
</EditText>
</TableRow>
<TableRow>
<Button
android:text="Login"
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Register"
android:id="#+id/btnregister"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Cancel"
android:id="#+id/btnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</TableRow>
</TableLayout>
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.B00512756.angertwo"
android:versionCode="1"
android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="8" />
<application android:name=".AppState" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Login"
android:label="#string/main_title">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login" android:label="#string/begin_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question1" android:label="#string/question_one"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question2" android:label="#string/question_two"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question3" android:label="#string/question_three"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question4" android:label="#string/question_four"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Question5" android:label="#string/question_five"
android:theme="#android:style/Theme"></activity>
<!-- <activity android:name=".AngerprototypetwoActivity" android:label="#string/main_title"
android:theme="#android:style/Theme"></activity> -->
<activity android:name=".nextQ1" android:id="#+id/next_Q1_button"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strategies" android:label="#string/strategies_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Contact" android:label="#string/begin_label"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strat_What_Is_Anger" android:label="#string/strategies_label_what_is_anger"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Strat_Use_Distraction" android:label="#string/strategies_label_distraction"
android:theme="#android:style/Theme"></activity>
<activity android:name=".Registration" android:label="#string/registration"
android:theme="#android:style/Theme"></activity>
</application>
</manifest>
Logcat:
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): FATAL EXCEPTION: main
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): java.lang.NullPointerException
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.B00512756.angertwo.Login$3.onClick(Login.java:76)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.view.View.performClick(View.java:2408)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.view.View$PerformClick.run(View.java:8816)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Handler.handleCallback(Handler.java:587)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Handler.dispatchMessage(Handler.java:92)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.os.Looper.loop(Looper.java:123)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at java.lang.reflect.Method.invokeNative(Native Method)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at java.lang.reflect.Method.invoke(Method.java:521)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at dalvik.system.NativeStart.main(Native Method)
05-19 17:08:17.121: WARN/ActivityManager(58): Force finishing activity com.B00512756.angertwo/.Login
05-19 17:08:17.641: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
05-19 17:08:19.731: INFO/Process(27481): Sending signal. PID: 27481 SIG: 9
05-19 17:08:19.751: INFO/WindowManager(58): WIN DEATH: Window{4507d5b0 com.B00512756.angertwo/com.B00512756.angertwo.Login paused=false}
05-19 17:08:19.751: INFO/ActivityManager(58): Process com.B00512756.angertwo (pid 27481) has died.
05-19 17:08:19.921: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 27481 uid 10045
05-19 17:08:20.341: DEBUG/dalvikvm(117): GC_EXTERNAL_ALLOC freed 484 objects / 27832 bytes in 383ms
05-19 17:08:24.590: DEBUG/dalvikvm(197): GC_EXPLICIT freed 100 objects / 4336 bytes in 127ms
05-19 17:08:28.610: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{4505c768 com.B00512756.angertwo/.Login}
05-19 17:08:29.650: DEBUG/dalvikvm(264): GC_EXPLICIT freed 58 objects / 2800 bytes in 140ms
05-19 17:08:33.513: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
Additional info:
Login.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("null")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = txtUserName.getText().toString();
String pwd = txtPassword.getText().toString();
SQLiteDatabase regDB = null;
//String[] columns = new String[]{COLUMN_ID, COLUMN_RATING, COLUMN_NAME };
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
if(null!=c){
c.moveToFirst();
System.out.println("Cursor Size"+c.getCount());
}
String result = "";
int iRow = c.getColumnIndex(COLUMN_ID);
int iRating = c.getColumnIndex(COLUMN_RATING);
int iName = c.getColumnIndex(COLUMN_NAME);
c.moveToLast();
for (int i = c.getCount() - 1; i >= 0; i--) {
// Get the data
result = result + c.getString(iRow) + " " + c.getString(iRating) + " " + c.getString(iName) + "\n" ;
if("select * from USER_INFO_TABLE where UserName =" + "\""+ name + "\""+" and Password="+ "\""+ pwd != null );
{ Intent j = new Intent();
j.setClassName("com.B00512756.angertwo",
"com.B00512756.angertwo.AngerprototypetwoActivity");
startActivity(j);}
// Move the cursor
c.moveToPrevious();
//return result;
}
c.close();
}
});
Null error is thrown at this line:
Cursor c = regDB.query(USER_INFO_TABLE, new String[] {
COLUMN_ID, COLUMN_RATING, COLUMN_NAME}, null, null, null, null, null);
You help is much appreciated :)
It's here:
05-19 17:08:17.111: ERROR/AndroidRuntime(27481): at com.B00512756.angertwo.Login$3.onClick(Login.java:76)
Find the source for Login.java, go to line 76, and see what object instances are de-referenced. One of those is null.

Categories