app crashing after clicking button x times - java
hi guys i have a problem. when i run my app, one activity crash after i press the buttons x times. sometimes it works, sometimes not. please help. don't know what to do.strong text
08-08 09:19:57.087: E/AndroidRuntime(2772): FATAL EXCEPTION: main
08-08 09:19:57.087: E/AndroidRuntime(2772): Process: org.nolodigas, PID: 2772
08-08 09:19:57.087: E/AndroidRuntime(2772): java.lang.IllegalStateException: Could not execute method of the activity
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3823)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View.performClick(View.java:4438)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$PerformClick.run(View.java:18422)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.handleCallback(Handler.java:733)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Looper.loop(Looper.java:136)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-08 09:19:57.087: E/AndroidRuntime(2772): at dalvik.system.NativeStart.main(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.reflect.InvocationTargetException
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3818)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 11 more
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=121; index=123
08-08 09:19:57.087: E/AndroidRuntime(2772): at org.nolodigas.Jugar.okButton(Jugar.java:104)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 14 more
there is my logcat. i can't find the error . here is my java code
public class Jugar extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
TextView textViewTime;
ImageView img;
int cont=0;
private int mCounter = 0;
private int[] a = {
R.drawable.casa,R.drawable.cantar,R.drawable.agua,R.drawable.anciana,R.drawable.arbol,R.drawable.mochila,R.drawable.auto,R.drawable.azucar,R.drawable.libro,R.drawable.empresa,R.drawable.control,R.drawable.computadora,R.drawable.boca,
R.drawable.boliche,R.drawable.campo,R.drawable.cantar,R.drawable.cargador,R.drawable.casa,R.drawable.casamiento,R.drawable.cerveza,R.drawable.cocina,R.drawable.concierto,R.drawable.control,R.drawable.cuaderno,R.drawable.cuerpo,R.drawable.deporte,R.drawable.dj,
R.drawable.doctor,R.drawable.droga,R.drawable.edificio,R.drawable.empresa,R.drawable.escritor,R.drawable.famoso,R.drawable.ganso,R.drawable.gato,R.drawable.gente,R.drawable.ginobili,R.drawable.grande,R.drawable.hospital,R.drawable.hotel,
R.drawable.huerfano,R.drawable.ingeniero,R.drawable.jugo,R.drawable.libreria,R.drawable.libro,R.drawable.mesa,R.drawable.mochila,R.drawable.museo,R.drawable.musica,R.drawable.naranja,R.drawable.nieve,R.drawable.ovni,R.drawable.paris,
R.drawable.pasto,R.drawable.pelo,R.drawable.pelota,R.drawable.pendrive,R.drawable.periodista,R.drawable.perro,R.drawable.piramide,R.drawable.pistola,R.drawable.planeta,R.drawable.playa,R.drawable.sirena,R.drawable.abogado,R.drawable.esqui,R.drawable.funda,R.drawable.disco,
R.drawable.pornografia,R.drawable.profesor,R.drawable.puerta,R.drawable.radio,R.drawable.rio,R.drawable.roma,R.drawable.ropa,R.drawable.sillon,R.drawable.superheroe,R.drawable.taza,R.drawable.luz,R.drawable.lapiz,R.drawable.ron,R.drawable.fernet,R.drawable.bariloche,R.drawable.garage,R.drawable.alarma,
R.drawable.tela,R.drawable.televisor,R.drawable.unia,R.drawable.ventana,R.drawable.ventilador,R.drawable.viajar,R.drawable.zapatillas,R.drawable.pelea,R.drawable.panda,R.drawable.cable,R.drawable.tinelli,R.drawable.manzana,R.drawable.ftutilla,R.drawable.leche,R.drawable.fotocopia,
R.drawable.mono,R.drawable.piano,R.drawable.guitarra,R.drawable.bateria,R.drawable.camara,R.drawable.bombon,R.drawable.tren,R.drawable.pintura,R.drawable.aldea,R.drawable.grito,R.drawable.bandera,R.drawable.messi,R.drawable.aguero,R.drawable.legrand,R.drawable.zuckerberg,R.drawable.billetera,R.drawable.guepardo,R.drawable.elefante,R.drawable.calle,R.drawable.gimnasio,R.drawable.argentina,
};
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.jugar);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
textViewTime = (TextView) findViewById(R.id.texto1);
textViewTime.setText("01:00");
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
protected void setOrientation() {
int current = getRequestedOrientation();
// only switch the orientation if not in portrait
if ( current != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ) {
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
public void lanzarJugar(View v) {
}
#Override
public void onClick(View v) {
mCounter=0;
mSwitcher.setText(String.valueOf(mCounter));
final CounterClass timer = new CounterClass(60000, 1000);
timer.start();
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void noButton(View v){
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void okButton(View v) {
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
mCounter++;
updateCounter();
cont++;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint({ "NewApi", "DefaultLocale" })
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String ms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(ms);
textViewTime.setText(ms);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
textViewTime.setText("Tiempo!");
}
}
}
In the code line below, you are generating a random number and picking an Resource Integer. But the index you are trying to get from array doesn't exist. So you are getting IndexOutOfBounds exception.
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
Error is in okButton method here:
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
rando is returning a value out bounds of a array.
Your array contains only 121 elements. Hence, whenever the random number generated is within 0-120 range, the app functions properly. But whenever the number falls between 121-124, it crashes due to IndexOutOfBounds exception. Either add more items to the array or use the following code:
int rando = (int) (Math.random() * 121);
Drawable d = getResources().getDrawable(a[rando]);
Related
Android Application "Source Not Found" java.lang.runtimeexception
I switched from running my app on a phone to a nexus 10 tablet and now it says "unfortunately the application has stopped." The tablet is running 4.4.2, my target api is set to 19 in the manifest. When I run it in debug mode I get Source Not Found. I tried clicking edit source lookup path and adding my project and had no luck. I've looked all over the internet and haven't had any luck solving this problem. Any suggestions would be a big help. "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException" Edit: MainActivity: package com.looper.video; public class MainActivity extends Activity { private VideoView video; private MediaController ctlr; final Uri firstVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife); final Uri secondVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife1); private String videosPath = Environment.getExternalStorageDirectory() + "/videos/"; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); File folder = new File(videosPath); File[] customFiles = folder.listFiles(); List<String> customFileNames = new ArrayList<String>(); for(File file : customFiles) { customFileNames.add(file.getName()); } ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, customFileNames); spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item ); Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles); spinner.setAdapter(spinnerArrayAdapter); video = (VideoView)findViewById(R.id.videoView1); ctlr = new MediaController(this); final Button firstVideoBtn = (Button) findViewById(R.id.firstVideoBtn); firstVideoBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click playFirstVideo(); } }); final Button secondVideoBtn = (Button) findViewById(R.id.secondVideoBtn); secondVideoBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click playSecondVideo(); } }); } public void playFeatured(View v) { try { Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles); String strPath = videosPath + spinner.getSelectedItem().toString(); Toast.makeText(this, strPath, Toast.LENGTH_LONG).show(); //Uri path = Uri.parse(videosPath + spinner.getSelectedItem().toString()); video.setVideoPath(strPath); ctlr.setMediaPlayer(video); video.setMediaController(ctlr); video.requestFocus(); video.start(); video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { #Override public void onCompletion(MediaPlayer vmp) { playSecondVideo(); } }); } catch(Exception e) { System.out.println(e.getMessage()); } } public void playFirstVideo() { video.setVideoURI(firstVideoPath); ctlr.setMediaPlayer(video); video.setMediaController(ctlr); video.requestFocus(); video.start(); video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { #Override public void onCompletion(MediaPlayer vmp) { playSecondVideo(); } }); } public void playSecondVideo() { SharedPreferences sp = getSharedPreferences("schedule", Context.MODE_PRIVATE); //SimpleDateFormat sdf = new SimpleDateFormat("hh:mm"); String startTime = sp.getString("startTime", ""); String endTime = sp.getString("endTime", ""); /* //SimpleDateFormat parser = new SimpleDateFormat("HH:mm"); //Date dateStartTime = parser.parse(startTime); //Date dateEndTime = parser.parse(endTime); Date now = new Date(); try { if (userDate.after(ten) && userDate.before(eighteen)) { } } catch (ParseException e) { // Invalid date was entered } System.out.println("Now:"+now); System.out.println("Start"+startTime); System.out.println("End:"+endTime); //if(now.before(dateEndTime) && now.after(dateStartTime)){ //disableAll(); //} else { * */ video.setVideoURI(secondVideoPath); ctlr.setMediaPlayer(video); video.setMediaController(ctlr); video.requestFocus(); video.start(); video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { #Override public void onCompletion(MediaPlayer vmp) { playSecondVideo(); } }); //} } public void admin(View view) { //MySQLiteHelper db = new MySQLiteHelper(this); //final String password = db.getUser(7).getPassword(); //db.close(); final AlertDialog.Builder alert = new AlertDialog.Builder(this); final EditText pass = new EditText(this); alert.setView(pass); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = pass.getText().toString().trim(); SharedPreferences sp1 = getSharedPreferences("Login", 0); //String username = sp1.getString("UserName", ""); String password = sp1.getString("Password", ""); if(value.equals(password)) { Intent intent = new Intent(getBaseContext(),Admin.class); startActivity(intent); } //Toast.makeText(getApplicationContext(), password + " " + value, Toast.LENGTH_SHORT).show(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); alert.show(); } #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } #Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void disableAll(){ Button firstVideoBtn = (Button)findViewById(R.id.firstVideoBtn); firstVideoBtn.setEnabled(false); Button secondVideoBtn = (Button)findViewById(R.id.secondVideoBtn); secondVideoBtn.setEnabled(false); Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles); spinner.setEnabled(false); Button btnPlay = (Button)findViewById(R.id.btnPlayFeatured); btnPlay.setEnabled(false); VideoView videoView = (VideoView)findViewById(R.id.videoView1); videoView.setEnabled(false); } } Full logcat: D/dalvikvm(2817): GC_FOR_ALLOC freed 58K, 4% free 3441K/3568K, paused 20ms, total 20ms 10-08 15:23:17.965: D/dalvikvm(2817): GC_FOR_ALLOC freed 2K, 4% free 3505K/3632K, paused 7ms, total 7ms 10-08 15:23:17.975: I/dalvikvm-heap(2817): Grow heap (frag case) to 8.739MB for 5515216-byte allocation 10-08 15:23:17.985: D/dalvikvm(2817): GC_FOR_ALLOC freed <1K, 2% free 8891K/9020K, paused 7ms, total 7ms 10-08 15:23:18.055: D/AndroidRuntime(2817): Shutting down VM 10-08 15:23:18.055: W/dalvikvm(2817): threadid=1: thread exiting with uncaught exception (group=0x4155eba8) 10-08 15:23:18.055: E/AndroidRuntime(2817): FATAL EXCEPTION: main 10-08 15:23:18.055: E/AndroidRuntime(2817): Process: com.looper.video, PID: 2817 10-08 15:23:18.055: E/AndroidRuntime(2817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.access$800(ActivityThread.java:135) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Handler.dispatchMessage(Handler.java:102) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Looper.loop(Looper.java:136) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.main(ActivityThread.java:5017) 10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invokeNative(Native Method) 10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invoke(Method.java:515) 10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 10-08 15:23:18.055: E/AndroidRuntime(2817): at dalvik.system.NativeStart.main(Native Method) 10-08 15:23:18.055: E/AndroidRuntime(2817): Caused by: java.lang.NullPointerException 10-08 15:23:18.055: E/AndroidRuntime(2817): at com.looper.video.MainActivity.onCreate(MainActivity.java:52) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Activity.performCreate(Activity.java:5231) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 10-08 15:23:18.055: E/AndroidRuntime(2817): ... 11 more
Retrieve SQLite data in edit text from Spinner selected item in Android
I have spinner in Activity and edittext's. When i run the app I'm getting warning of nullPointerException.I dosen't retrieve the SQLite data in edit text in onCreate().Can someone help me. Here is my code. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.delete_entry); databaseHelper = new DatabaseHelper(this); databaseHelper.onOpen(db); spinner_searchByEmpName = (Spinner)findViewById(R.id.searchByEmpName); loadSerachBYProject() ; spinner_searchByEmpName.setOnItemSelectedListener(new OnItemSelectedListener() { #Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub selectedEmployeeName = spinner_searchByEmpName.getSelectedItem().toString().trim(); System.out.println("selectedProjectName " + selectedEmployeeName); } #Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); etEmpName=(EditText)findViewById(R.id.Delete_editText_StaffEmployee_Name); etDepartment=(EditText)findViewById(R.id.Delete_editText_Department); etDesignation=(EditText)findViewById(R.id.Delete_editText_Designation); try { Cursor cursor = db.rawQuery("SELECT staff_employee_id, staff_emp_name, department, designation FROM employee_details WHERE staff_emp_name = ?", new String[] { "" + selectedEmployeeName }); etEmpName.setText(cursor.getString(cursor .getColumnIndex("staff_emp_name"))); etDepartment.setText(cursor.getString(cursor .getColumnIndex("department"))); etDesignation.setText(cursor.getString(cursor .getColumnIndex("designation"))); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } private void loadSerachBYProject() { DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext()); // Spinner Drop down elements List<String> projectsName = databaseHelper.getAllEmployeeName(); // Creating adapter for spinner ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, projectsName); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinner_searchByEmpName.setAdapter(dataAdapter); } } Thanks in Advance. Here is My Log cat error info 06-26 18:08:09.073: W/System.err(601): java.lang.NullPointerException 06-26 18:08:09.083: W/System.err(601): at com.employee_review.Update_Entry.onCreate(Update_Entry.java:68) 06-26 18:08:09.083: W/System.err(601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 06-26 18:08:09.103: W/System.err(601): at android.os.Handler.dispatchMessage(Handler.java:99) 06-26 18:08:09.103: W/System.err(601): at android.os.Looper.loop(Looper.java:123) 06-26 18:08:09.113: W/System.err(601): at android.app.ActivityThread.main(ActivityThread.java:3683) 06-26 18:08:09.123: W/System.err(601): at java.lang.reflect.Method.invokeNative(Native Method) 06-26 18:08:09.133: W/System.err(601): at java.lang.reflect.Method.invoke(Method.java:507) 06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 06-26 18:08:09.133: W/System.err(601): at dalvik.system.NativeStart.main(Native Method)
Try this , i guess if(cursor!=null){ etEmpName.setText(cursor.getString(cursor .getColumnIndex("staff_emp_name"))); etDepartment.setText(cursor.getString(cursor .getColumnIndex("department"))); etDesignation.setText(cursor.getString(cursor .getColumnIndex("designation"))); }
db is never initialized. It must be initialized in onCreate(), as that's the first method that is run in an Activity. I see this: databaseHelper = new DatabaseHelper(this); databaseHelper.onOpen(db); I'm guessing you really should have this: databaseHelper = new DatabaseHelper(this); db=databaseHelper.getReadableDatabase();
NPE accessing Application method from AlerDialog OnClick method
Building on a theme from yesterday...I'm getting an NPE accessing a method in a singleton Application class from within an AlertDialog. Activity SavedMealsActivity sets OnLongClickListenerSavedMeals as the listener for a series of TextViews in a ScrollView. OnLongClickListenerSavedMeals is defined as a separate class. OnLongClickListenerSavedMeals displays an AlertDialog which gives the option of going to a different Activity, but it first needs to fire the methods of an Application class which is defined as a singleton (MealTimerApplication). This is the first line of the onClick method (line 25 in the first code sample below), and it throws the NPE because the activity is null at the time. I've tried passing in the activity from the calling Activity (SavedMealsActivity) but for some reason it's not working as I'd hoped. Any ideas? OnLongClick listener class - OnLongClickListenerSavedMeals: public class OnLongClickListenerSavedMeals implements OnLongClickListener { Context context; String id; private Activity activity; public OnLongClickListenerSavedMeals(Activity activity) { this.activity = activity; this.context = activity; } #Override public boolean onLongClick(View view){ // TODO Auto-generated method stub this.context = context; id = view.getTag().toString(); final CharSequence[] items = { "Edit", "Delete" }; //Set activity to allow context to be used in the OnClickListener/onClick method below this.activity = activity; new AlertDialog.Builder(context).setTitle("Meal Item") .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { //Set the global meal_id variable and invoke the MealActivity ((MealTimerApplication) activity.getApplication()).setMealId(Long.getLong(id)); Intent myIntent = new Intent(activity.getBaseContext(),MealActivity.class); activity.startActivityForResult(myIntent, 0); } else if (item == 1) { boolean deleteSuccessful = new TableControllerMeal(context).delete(id); if (deleteSuccessful){ Toast.makeText(context, "Record was deleted.", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "Unable to delete record.", Toast.LENGTH_SHORT).show(); } ((SavedMealsActivity) context).readRecords(); } dialog.dismiss(); } }).show(); return false; } Calling Activity - SavedMealsActivity: public class SavedMealsActivity extends Activity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_saved_meals); //Read saved meal records from the database and display them readRecords(); } public void readRecords() { LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords); linearLayoutRecords.removeAllViews(); List<meal> meal = new TableControllerMeal(this).read(); if (meal.size() > 0) { for (meal obj : meal) { long id = obj.id; String MealDesc = obj.meal_desc; int MealMinutes = obj.meal_ready_time; String textViewContents = MealDesc + " - ready at " + Utilities.formatTime(MealMinutes); TextView textViewItem = new TextView(this); textViewItem.setPadding(0, 10, 0, 10); textViewItem.setText(textViewContents); textViewItem.setTag(Long.toString(id)); textViewItem.setOnLongClickListener(new OnLongClickListenerSavedMeals(this)); linearLayoutRecords.addView(textViewItem); } } else { TextView Item = new TextView(this); Item.setPadding(8, 8, 8, 8); Item.setText("No records yet."); linearLayoutRecords.addView(Item); } } Application class: public class MealTimerApplication extends Application { private static MealTimerApplication singleton; private long mealId = 0; // Returns the application instance public static MealTimerApplication getInstance() { return singleton; } public final void onCreate() { super.onCreate(); singleton = this; } public void setMealId(long mealId) { this.mealId = mealId; } public long getMealId() { return this.mealId; } } Logcat: 05-28 16:48:03.637: E/AndroidRuntime(4241): java.lang.NullPointerException 05-28 16:48:03.637: E/AndroidRuntime(4241): at com.ian.mealtimer.OnLongClickListenerSavedMeals$1.onClick(OnLongClickListenerSavedMeals.java:39) 05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AdapterView.performItemClick(AdapterView.java:299) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView.performItemClick(AbsListView.java:1113) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$3.run(AbsListView.java:3638) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.handleCallback(Handler.java:733) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.dispatchMessage(Handler.java:95) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Looper.loop(Looper.java:136) 05-28 16:48:03.637: E/AndroidRuntime(4241): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invokeNative(Native Method) 05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invoke(Method.java:515) 05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-28 16:48:03.637: E/AndroidRuntime(4241): at dalvik.system.NativeStart.main(Native Method)
You get NPE because of autoboxing. Long.getLong(String) is not what you actually you need, check its description: Returns the Long value of the system property identified by string. It definitely returns null in your case. Moreover it returns null reference to Long object, but your MealTimerApplication.setMealId expects argument with primitive type long. Here is the point where auto-boxing implicitly trying to cast your Long object returned by getLong method to the long primitive. But as value was null auto-boxing fails and you get NPE. You should just use Long.valueOf(String) instead of Long.getLong(String).
Android Application Crashes when Creating custom class object
I'm working on my first android app and I'm having trouble creating an object of a class I have programmed in java using the onCreate function of an activity. The activity starts great when I do not instantiate the object, but when I attempt to create the object the app crashes when switching to the activity. The onCreate function looks like this... protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_entry); // Show the Up button in the action bar. setupActionBar(); ForceTable testTable = new ForceTable(); Double factor = testTable.returnValue(forceTypes.newtons, forceTypes.newtons); } ForceTable is the class I have programmed, its code looks this... public class ForceTable { private double[][] forceTable; protected enum forceTypes {newtons(0), pounds(1), kilopond(2); public int num; private forceTypes(int num) { this.num = num; } }; protected final class values{ private final static double zeroZero = 1.00; private final static double zeroOne = 4.44872162; private final static double zeroTwo = 9.80665; private final static double oneZero = .224808943; private final static double oneOne = 1.00; private final static double oneTwo = 2.20462262; private final static double twoZero = .10197164; private final static double twoOne = .45359237; private final static double twoTwo = 1.00; } public ForceTable() { this.makeTable(); } private void makeTable() { forceTable[0][0] = values.zeroZero; forceTable[0][1] = values.zeroOne; forceTable[0][2] = values.zeroTwo; forceTable[1][0] = values.oneZero; forceTable[1][1] = values.oneOne; forceTable[1][2] = values.oneTwo; forceTable[2][0] = values.twoZero; forceTable[2][1] = values.twoOne; forceTable[2][2] = values.twoTwo; } public double returnValue(forceTypes ifYouHave, forceTypes thenYouHave){ double factor = forceTable[thenYouHave.num][ifYouHave.num]; return factor; } } It's been a very long time since I have programmed in Java, and since the activity starts fine without instantiating it must be my Java code for ForceTable. Anybody notice something wrong? There's a good chance it's something easy that I'm not brushed up on... Here is the logcat 08-08 18:08:13.206: E/(9801): : Can't open file for reading 08-08 18:08:13.206: E/(9801): : Can't open file for reading 08-08 18:10:34.045: W/dalvikvm(9801): threadid=1: thread exiting with uncaught exception (group=0x4136b438) 08-08 18:10:34.045: E/AndroidRuntime(9801): FATAL EXCEPTION: main 08-08 18:10:34.045: E/AndroidRuntime(9801): java.lang.RuntimeException: Unable to start activity ComponentInfo{khandy.application.convertible/khandy.application.convertible.EntryActivity}: java.lang.NullPointerException 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.access$700(ActivityThread.java:143) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Handler.dispatchMessage(Handler.java:99) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Looper.loop(Looper.java:137) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.main(ActivityThread.java:4950) 08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invokeNative(Native Method) 08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invoke(Method.java:511) 08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004) 08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771) 08-08 18:10:34.045: E/AndroidRuntime(9801): at dalvik.system.NativeStart.main(Native Method) 08-08 18:10:34.045: E/AndroidRuntime(9801): Caused by: java.lang.NullPointerException 08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.makeTable(ForceTable.java:34) 08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.(ForceTable.java:29) 08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.EntryActivity.onCreate(EntryActivity.java:21) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Activity.performCreate(Activity.java:5179) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) 08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074) 08-08 18:10:34.045: E/AndroidRuntime(9801): ... 11 more
You probably get a NullPointerException at this line forceTable[0][0] = values.zeroZero; because you try to access the array without creating it first. Before accessing it, create it like that forceTable = new double[][]; forceTable[0][0] = values.zeroZero; And please ALWAYS post the logcat output! It just makes it so much easier to find the problem.
I think the problem is when your makeTable function is called. can you allocate space for your forceTable array.. I mean do a new for double[][] forceTable;
You are missing privatetable = new double[n] [m] ; You can put it in the constructor of the second class!
Android ListView with 2 TextViews and 1 Button
I'm trying to create a ListView with 2 TextViews and 1 Button. When the users click in the button the activity will finish(); and pass the result to another view. I followed this tutorial . But for some reason when i click to start that activity my application crashes! Here is the 3 files from my app that are relevant. List Structure Data: public class formulasListData { private String formulasName; private String formulasDefinition; public formulasListData(String formulasName, String formulasDefinition) { super(); this.formulasName = formulasName; this.formulasDefinition = formulasDefinition; } public String getFormulasName() { return formulasName; } public void setFormulasName(String formulasName) { this.formulasName = formulasName; } public String getFormulasDefinition() { return formulasDefinition; } public void setFormulasDefinition(String formulasDefinition) { this.formulasDefinition = formulasDefinition; } } The List Adapter: public class formulasListAdapter extends BaseAdapter implements OnClickListener { private Context context; private List<formulasListData> formulasList; public formulasListAdapter(Context context, List<formulasListData> formulasList) { this.context = context; this.formulasList = formulasList; } #Override public int getCount() { return formulasList.size(); } #Override public Object getItem(int position) { return formulasList.get(position); } #Override public long getItemId(int position) { return position; } #Override public View getView(int position, View rowView, ViewGroup parent) { formulasListData entry = formulasList.get(position); if(rowView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.formulas_row, null); } TextView formulasName = (TextView) rowView.findViewById(R.id.formulas_name); formulasName.setText(entry.getFormulasName()); TextView formulasDefinition = (TextView) rowView.findViewById(R.id.formulas_definition); formulasDefinition.setText(entry.getFormulasDefinition()); Button btnSelect = (Button) rowView.findViewById(R.id.selectFormula); btnSelect.setFocusableInTouchMode(false); btnSelect.setFocusable(false); btnSelect.setOnClickListener(this); btnSelect.setTag(entry); return rowView; } #Override public void onClick(View view) { formulasListData entry = (formulasListData) view.getTag(); } } And the activity that should display the list. public class FormulasList extends Activity { private static final int FORMULA_0 = 0; private static final int FORMULA_1 = 1; private static final int FORMULA_2 = 2; private static final int FORMULA_3 = 3; private static final int FORMULA_4 = 4; private static final int FORMULA_5 = 5; private static final int FORMULA_6 = 6; // private static final int FORMULA_7 = 7; public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); ListView formulasListView = (ListView) findViewById(R.id.formulas_list); formulasListView.setClickable(true); final List<formulasListData> formulasList = new ArrayList<formulasListData>(); final String[] formulasName = new String[] {"Circunference of a Circle:", "Area of a Circle:", "Volume of a Sphere:", "Area Triangle:", "Area Square:", "Volume of a Cube:", "Pithagorean Theorem:"}; final String[] formulasDefinition = new String[] {"2 × π × r", "π × r²", "(4/3) × π × r³", "(b × h)/2", "side²", "side³", "a² + b² = c²"}; // formulasList.add(new formulasListData(formulasName, formulasDefinition)); formulasList.add(new formulasListData(formulasName[0], formulasDefinition[0])); formulasList.add(new formulasListData(formulasName[1], formulasDefinition[1])); formulasList.add(new formulasListData(formulasName[2], formulasDefinition[2])); formulasList.add(new formulasListData(formulasName[3], formulasDefinition[3])); formulasList.add(new formulasListData(formulasName[4], formulasDefinition[4])); formulasList.add(new formulasListData(formulasName[5], formulasDefinition[5])); formulasList.add(new formulasListData(formulasName[6], formulasDefinition[6])); SharedPreferences settings = getSharedPreferences(SettingsActivity.PREF_NAME, MODE_PRIVATE); SettingsActivity.newTheme = settings.getInt("themeCustom", 0); if(SettingsActivity.newTheme == SettingsActivity.THEME_DARK) { setTheme(R.style.DarkTheme); } else if(SettingsActivity.newTheme == SettingsActivity.THEME_LIGHT){ setTheme(R.style.LightTheme); } else if(SettingsActivity.newTheme == SettingsActivity.THEME_COLORS) { setTheme(R.style.ColorsTheme); } else { setTheme(R.style.AppTheme); } setContentView(R.layout.activity_formulas); formulasListAdapter adapter = new formulasListAdapter(this, formulasList); formulasListView.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> arg0, View view, int position,long index) { Intent intent= getIntent(); Bundle b = new Bundle(); switch (position) { case FORMULA_0: b.putString("key0", formulasDefinition[0]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_1: b.putString("key0", formulasDefinition[1]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_2: b.putString("key0", formulasDefinition[2]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_3: b.putString("key0", formulasDefinition[3]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_4: b.putString("key0", formulasDefinition[4]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_5: b.putString("key0", formulasDefinition[5]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; case FORMULA_6: b.putString("key0", formulasDefinition[6]); intent.putExtras(b); setResult(RESULT_OK, intent); finish(); break; default: break; } } }); formulasListView.setAdapter(adapter); } } Thank you very much!! EDIT: Here is the LogCat 05-01 20:06:54.436: D/libEGL(4820): loaded /system/lib/egl/libEGL_tegra.so 05-01 20:06:54.456: D/libEGL(4820): loaded /system/lib/egl/libGLESv1_CM_tegra.so 05-01 20:06:54.466: D/libEGL(4820): loaded /system/lib/egl/libGLESv2_tegra.so 05-01 20:06:54.486: D/OpenGLRenderer(4820): Enabling debug mode 0 05-01 20:06:54.536: D/dalvikvm(4820): GC_CONCURRENT freed 170K, 4% free 7509K/7808K, paused 4ms+10ms, total 38ms 05-01 20:06:59.976: D/AndroidRuntime(4820): Shutting down VM 05-01 20:06:59.976: W/dalvikvm(4820): threadid=1: thread exiting with uncaught exception (group=0x40cde930) 05-01 20:06:59.976: E/AndroidRuntime(4820): FATAL EXCEPTION: main 05-01 20:06:59.976: E/AndroidRuntime(4820): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabilheri.marcuscalculatorv2/com.gabilheri.marcuscalculatorv2.FormulasList}: java.lang.NullPointerException 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Handler.dispatchMessage(Handler.java:99) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.os.Looper.loop(Looper.java:137) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invokeNative(Native Method) 05-01 20:06:59.976: E/AndroidRuntime(4820): at java.lang.reflect.Method.invoke(Method.java:511) 05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-01 20:06:59.976: E/AndroidRuntime(4820): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-01 20:06:59.976: E/AndroidRuntime(4820): at dalvik.system.NativeStart.main(Native Method) 05-01 20:06:59.976: E/AndroidRuntime(4820): Caused by: java.lang.NullPointerException 05-01 20:06:59.976: E/AndroidRuntime(4820): at com.gabilheri.marcuscalculatorv2.FormulasList.onCreate(FormulasList.java:30) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Activity.performCreate(Activity.java:5104) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-01 20:06:59.976: E/AndroidRuntime(4820): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-01 20:06:59.976: E/AndroidRuntime(4820): ... 11 more
Try moving setContentView(R.layout.activity_formulas); To the start of the method. Right after the super call. You are trying to use gui controls before initializing the activity layout