I am trying to show SD Card image into ImageView and getting OutOfMemory error.
Please let me know How can i show SDCard's images into ImageView (no matter how big they are.)
I know we can use, these properties to control on it, but i am looking for the best solution :
android:hardwareAccelerated="false"
android:largeHeap="true"
Logcat:
08-05 11:27:34.530: E/AndroidRuntime(8158): FATAL EXCEPTION: main
08-05 11:27:34.530: E/AndroidRuntime(8158): java.lang.OutOfMemoryError
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:650)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:389)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:449)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.physic.UploadActivity.previewMedia(UploadActivity.java:171)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.physic.UploadActivity.onCreate(UploadActivity.java:109)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.Activity.performCreate(Activity.java:5191)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.os.Looper.loop(Looper.java:137)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.main(ActivityThread.java:4921)
08-05 11:27:34.530: E/AndroidRuntime(8158): at java.lang.reflect.Method.invokeNative(Native Method)
08-05 11:27:34.530: E/AndroidRuntime(8158): at java.lang.reflect.Method.invoke(Method.java:511)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
08-05 11:27:34.530: E/AndroidRuntime(8158): at dalvik.system.NativeStart.main(Native Method)
Code:
/**
* Displaying captured image/video on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
final Bitmap bitmap = BitmapFactory.decodeFile(filePath);
ExifInterface exif = null;
try {
exif = new ExifInterface(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bmRotated = rotateBitmap(bitmap, orientation);
imgPreview.setImageBitmap(bmRotated);
} else {
imgPreview.setVisibility(View.GONE);
}
}
Using Picasso Lib:
Picasso.with(UploadActivity.this)
.load(new File(filePath)).rotate(90)
.fit().centerInside()
.error(R.drawable.ic_launcher)
.placeholder(R.drawable.ic_launcher)
.into(imgPreview);
And even tried with this:
.transform(transformation)
Log:
Log.d("file:", filePath);
D/file:(6201): /storage/sdcard0/Pictures/Testing/LICPolicy20150805120029.jpg
Tried with Picasso lib but not showing image preview ..
OutOfMemoryException occur when your image is too large and your device is not able to render it so what you can do is to down scale the image according to your need below is the code for downscaling
public static Bitmap compressed_Bitmap(Bitmap bitmap) {
final int maxSize = 700;
int outWidth;
int outHeight;
int inWidth = bitmap.getWidth();
int inHeight = bitmap.getHeight();
if (inWidth > inHeight) {
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
return resizedBitmap;
}
Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1
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]);
I am trying to use a AlertDialog in my application, but it requires an input to be given. So i was forced to create an interface and override the onAttach() method within my custom DialogFragment class. Once i properly set everything in both the Dialog class and MainActivity, i tried to run my app and it gave me a runtime exception referring to nullpointer among other things. im not sure why this is and i am in need of assistance, please help. Below you will wind the Override of my interface method, the place where my .show() method is called, the code for my DialogFragment class, and my error log lastly.
public class MainActivity extends FragmentActivity implements CDia_exp.NDListener
{
//Integers and Strings for performing calculations
int a;
int b;
static int deci_cnt;
int cnt;
int temp;
Double exp_x;
Double exp;
Double [] num_trk;
String [] op_trk;
String num_hold;
String op_hold;
String del_hold;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//....Lots of other code here.......
//Exp_x Button
opSet[6].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(num_hold != "")
{
cDia_exp.show(getSupportFragmentManager(), "exp_x");
del_hold = tViews[0].getText().toString();
for(int x = num_hold.length() - 1; x >= 0; x--)
{
del_hold = del_hold.substring(0, del_hold.length() - 1);
}
num_hold = exp.toString();
tViews[0].setText(del_hold + num_hold);
return;
}
else
{
return;
}
}
});
}
//Objects and Overrides for calling foreign functions
CTrim cTrim = new CTrim();
CDia cDia = new CDia();
CDia_exp cDia_exp = new CDia_exp();
EditText exp_inp = (EditText) findViewById(R.id.exp_inp);
#Override
public void onDPClick(DialogFragment dialog)
{
exp = Double.parseDouble(num_hold);
exp_x = Double.parseDouble(exp_inp.getText().toString());
for(double x = exp_x; x > 0; x--)
{
exp *= exp;
}
}
#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;
}
}
My Custom DialogFragment class
package com.example.musicalc;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
public class CDia_exp extends DialogFragment
{
public interface NDListener
{
public void onDPClick(DialogFragment dialog);
}
NDListener expListener;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
expListener = (NDListener) activity;
}
catch(ClassCastException e)
{
throw new ClassCastException(activity.toString() + "does not implement NDListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder aDia = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
aDia.setView(inflater.inflate(R.layout.calc_dia, null)).setPositiveButton(R.string.diaOk_b, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
expListener.onDPClick(CDia_exp.this);
}
}).setNegativeButton(R.string.cancel_b, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
getDialog().cancel();
}
});
return aDia.create();
}
}
And Now the Error Log
07-20 14:23:43.599: E/Trace(24173): error opening trace file: No such file or directory (2)
07-20 14:23:43.622: D/AndroidRuntime(24173): Shutting down VM
07-20 14:23:43.622: W/dalvikvm(24173): threadid=1: thread exiting with uncaught exception (group=0x4137d2a0)
07-20 14:23:43.653: E/AndroidRuntime(24173): FATAL EXCEPTION: main
07-20 14:23:43.653: E/AndroidRuntime(24173): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.musicalc/com.example.musicalc.MainActivity}: java.lang.NullPointerException
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2060)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.access$700(ActivityThread.java:141)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.os.Looper.loop(Looper.java:137)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.main(ActivityThread.java:5059)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
07-20 14:23:43.653: E/AndroidRuntime(24173): at dalvik.system.NativeStart.main(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): Caused by: java.lang.NullPointerException
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.Activity.findViewById(Activity.java:1851)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.example.musicalc.MainActivity.<init>(MainActivity.java:43)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.Class.newInstanceImpl(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.Class.newInstance(Class.java:1319)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2051)
07-20 14:23:43.653: E/AndroidRuntime(24173): ... 11 more
07-20 14:25:56.817: E/Trace(24308): error opening trace file: No such file or directory (2)
07-20 14:25:56.934: D/AndroidRuntime(24308): Shutting down VM
07-20 14:25:56.934: W/dalvikvm(24308): threadid=1: thread exiting with uncaught exception (group=0x4137d2a0)
07-20 14:25:57.013: E/AndroidRuntime(24308): FATAL EXCEPTION: main
07-20 14:25:57.013: E/AndroidRuntime(24308): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.musicalc/com.example.musicalc.MainActivity}: java.lang.NullPointerException
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2060)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.access$700(ActivityThread.java:141)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.os.Looper.loop(Looper.java:137)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.main(ActivityThread.java:5059)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
07-20 14:25:57.013: E/AndroidRuntime(24308): at dalvik.system.NativeStart.main(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): Caused by: java.lang.NullPointerException
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.Activity.findViewById(Activity.java:1851)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.example.musicalc.MainActivity.<init>(MainActivity.java:803)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.Class.newInstanceImpl(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.Class.newInstance(Class.java:1319)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2051)
07-20 14:25:57.013: E/AndroidRuntime(24308): ... 11 more
Thanks to some experimentation and some research on stackoverflow i have located the answer.
The problem is that the compiler was having trouble locating the view either because it is in a separate xml file from my activity_main.xml file or because i was creating my dialog within a separate class from my MainActiviy.java.
To solve this i created my dialog within my MainActivity.java class outside of the onCreate method. Also i created a layout inflater to inflate my layout within a View in my MainActivity, which was key because the LayoutInflater provided a way to directly call my EditText into code.
The code that fixed the nullpointer when declaring my EditText is as follows:
LayoutInflater inflater = LayoutInflater.from(this);
//Inflater "inflates" layout into View as a value
final View infV = inflater.inflate(R.layout.calc_dia, null);
//Use layout value inflated in View "infV" to find EditText
final EditText eDTemp = (EditText) infV.findViewById(R.id.expInp);
***The full code for the dialog is as follows****:
public void showCD()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View infV = inflater.inflate(R.layout.calc_dia, null);
final EditText eDTemp = (EditText)infV.findViewById(R.id.expInp);
TextView tView0 = (TextView)findViewById(R.id.calcView);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(infV).setPositiveButton("Ok", new
DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}}).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
builder.show();
}
When you are ready for the dialog to appear, simply call the function that contains it.
I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.