Camera Application by Callling another class - java

I am working on a Flashlight project. I wanna do this by using another class.
Here is my mainactivity.java file:
package com.efsunderin.callcamera;
import android.hardware.Camera;
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;
public class MainActivity extends Activity {
Button bFlash;
Button cFlash;
MyCamera bnmcamera;
Camera camera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});
cFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.turnOffFlash();
}
});
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
#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;
}
}
In this activity I am calling the class below:
package com.efsunderin.callcamera;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
public class MyCamera {
Camera camera;
Parameters params;
public void getCamera() {
camera.open();
params = camera.getParameters();
camera.startPreview();
}
public void turnOnFlash() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
public void turnOffFlash() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.startPreview();
}
}
But it's not working, the system shutdown the app when I touch the button to turn on flash. What am I doing wrong? Please help. thanks.
Here is logcat *output:*
08-31 08:53:22.157: D/AndroidRuntime(287): CheckJNI is ON
08-31 08:53:22.347: D/AndroidRuntime(287): --- registering native functions ---
08-31 08:53:23.247: D/dalvikvm(218): GC_EXPLICIT freed 406 objects / 23512 bytes in 68ms
08-31 08:53:23.367: D/PackageParser(58): Scanning package: /data/app/vmdl50609.tmp
08-31 08:53:23.586: I/PackageManager(58): Removing non-system package:com.eeecoder.callcamera
08-31 08:53:23.586: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:23.777: D/PackageManager(58): Scanning package com.eeecoder.callcamera
08-31 08:53:23.777: I/PackageManager(58): Package com.eeecoder.callcamera codePath changed from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk; Retaining data and using new
08-31 08:53:23.787: I/PackageManager(58): /data/app/com.eeecoder.callcamera-2.apk changed; unpacking
08-31 08:53:23.807: D/installd(34): DexInv: --- BEGIN '/data/app/com.eeecoder.callcamera-2.apk' ---
08-31 08:53:25.380: D/dalvikvm(294): DexOpt: load 205ms, verify 971ms, opt 42ms
08-31 08:53:25.427: D/installd(34): DexInv: --- END '/data/app/com.eeecoder.callcamera-2.apk' (success) ---
08-31 08:53:25.427: W/PackageManager(58): Code path for pkg : com.eeecoder.callcamera changing from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.427: W/PackageManager(58): Resource path for pkg : com.eeecoder.callcamera changing from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.427: D/PackageManager(58): Activities: com.eeecoder.callcamera.MainActivity
08-31 08:53:25.447: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:25.667: I/installd(34): move /data/dalvik-cache/data#app#com.eeecoder.callcamera-2.apk#classes.dex -> /data/dalvik-cache/data#app#com.eeecoder.callcamera-2.apk#classes.dex
08-31 08:53:25.667: D/PackageManager(58): New package installed in /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.897: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:26.077: D/dalvikvm(58): GC_EXPLICIT freed 12492 objects / 745576 bytes in 179ms
08-31 08:53:26.277: D/dalvikvm(123): GC_EXPLICIT freed 7018 objects / 337856 bytes in 232ms
08-31 08:53:26.857: W/RecognitionManagerService(58): no available voice recognition services found
08-31 08:53:27.067: D/dalvikvm(150): GC_EXPLICIT freed 3878 objects / 211624 bytes in 638ms
08-31 08:53:27.212: D/dalvikvm(58): GC_EXPLICIT freed 5013 objects / 274168 bytes in 119ms
08-31 08:53:27.217: I/installd(34): unlink /data/dalvik-cache/data#app#com.eeecoder.callcamera-1.apk#classes.dex
08-31 08:53:27.267: D/AndroidRuntime(287): Shutting down VM
08-31 08:53:27.287: D/dalvikvm(287): Debugger has detached; object registry had 1 entries
08-31 08:53:27.307: I/AndroidRuntime(287): NOTE: attach of thread 'Binder Thread #3' failed
08-31 08:53:27.857: D/AndroidRuntime(299): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
08-31 08:53:27.857: D/AndroidRuntime(299): CheckJNI is ON
08-31 08:53:28.127: D/AndroidRuntime(299): --- registering native functions ---
08-31 08:53:29.177: I/ActivityManager(58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.eeecoder.callcamera/.MainActivity }
08-31 08:53:29.267: D/AndroidRuntime(299): Shutting down VM
08-31 08:53:29.297: D/dalvikvm(299): Debugger has detached; object registry had 1 entries
08-31 08:53:29.337: I/ActivityManager(58): Start proc com.eeecoder.callcamera for activity com.eeecoder.callcamera/.MainActivity: pid=306 uid=10049 gids={1006}
08-31 08:53:29.387: I/dalvikvm(299): JNI: AttachCurrentThread (from ???.???)
08-31 08:53:29.387: I/AndroidRuntime(299): NOTE: attach of thread 'Binder Thread #3' failed
08-31 08:53:30.257: I/ActivityManager(58): Displayed activity com.eeecoder.callcamera/.MainActivity: 989 ms (total 989 ms)
08-31 08:53:35.357: D/dalvikvm(123): GC_EXPLICIT freed 965 objects / 55776 bytes in 68ms
08-31 08:53:40.367: D/dalvikvm(218): GC_EXPLICIT freed 117 objects / 5144 bytes in 72ms
08-31 08:53:45.377: D/dalvikvm(257): GC_EXPLICIT freed 759 objects / 55000 bytes in 80ms
08-31 08:54:31.157: D/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
Here is error log output when I touch the button it gives these output and stopped by the system :
error log:
08-31 09:55:19.347: E/AndroidRuntime(357): FATAL EXCEPTION: main
08-31 09:55:19.347: E/AndroidRuntime(357): java.lang.NullPointerException
08-31 09:55:19.347: E/AndroidRuntime(357): at com.eeecoder.callcamera.MyCamera.getCamera(MyCamera.java:24)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.eeecoder.callcamera.MainActivity$1.onClick(MainActivity.java:35)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.view.View.performClick(View.java:2408)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.view.View$PerformClick.run(View.java:8816)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Handler.handleCallback(Handler.java:587)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Looper.loop(Looper.java:123)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-31 09:55:19.347: E/AndroidRuntime(357): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 09:55:19.347: E/AndroidRuntime(357): at java.lang.reflect.Method.invoke(Method.java:521)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-31 09:55:19.347: E/AndroidRuntime(357): at dalvik.system.NativeStart.main(Native Method)
I initialized required objects, but it still gives NullPointerException, why does it give this error? I don't understand. Please take a look at error log output.

You have not initialized your variables bnmCamera and camera.
MyCamera bnmcamera;
Camera camera;
initialize those variables and then use it.
if you use variables without initializing it will give you NullPointerException.
I think you want to do this:(You have not used camera object anywhere)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
//initialize bnmcamera
bnmcamera = new MyCamera();
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});
cFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.turnOffFlash();
}
});
}
Camera class:
You dont have start camera preview every time. and if you want do do that you have stop preview if it is already started release the camera and then start again.
check this link Camera Preview Demo
EDIT:
try this:
public void getCamera() {
camera = camera.open();
params = camera.getParameters();
camera.startPreview();
}
public void turnOnFlash() {
if(camera != null){
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}else{
Log.e("CHECK","Camera null");
}
}
do this check in all functions.

You forgot to create object first before calling the method.
here you go:
private MyCamera=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
**MyCamera bnmcamera=new MyCamera();**
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});

Related

my application crashes when i start new thread [duplicate]

This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.

code with thread crashes at startup (android beginner)

I am trying to make an application that passes through the audio samples obtained at the microphone to the speaker. This is the source code:
public class MainActivity extends Activity {
AudioManager am = null;
AudioRecord record =null;
AudioTrack track =null;
final int SAMPLE_FREQUENCY = 44100;
final int SIZE_OF_RECORD_ARRAY = 1024;
boolean isPlaying = false;
class MyThread extends Thread{
#Override
public void run(){
recordAndPlay();
}
}
MyThread newThread;
private void init() {
int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, min);
int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
init();
newThread.start();
}
#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;
}
private void recordAndPlay() {
short[] lin = new short[SIZE_OF_RECORD_ARRAY];
int num = 0;
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
record.startRecording();
track.play();
while (true) {
num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
track.write(lin, 0, num);
}
}
public void passStop(View view){
Button playBtn = (Button) findViewById(R.id.playBtn);
// /*
if(!isPlaying){
record.startRecording();
track.play();
isPlaying = true;
playBtn.setText("Pause");
}
if(isPlaying){
record.stop();
track.pause();
isPlaying=false;
playBtn.setText("Pass through");
}
// */
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy(){
newThread.stop();
}
}
Unfortunately, this program stops as soon as I try to run it through eclipse. This is wht I get in the logcat but I am not sure what it all means:
08-19 18:58:43.365: D/AndroidRuntime(27915): Shutting down VM
08-19 18:58:43.365: W/dalvikvm(27915): threadid=1: thread exiting with uncaught exception (group=0x4161f700)
08-19 18:58:43.365: E/AndroidRuntime(27915): FATAL EXCEPTION: main
08-19 18:58:43.365: E/AndroidRuntime(27915): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mypassthrough/com.example.mypassthrough.MainActivity}: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Looper.loop(Looper.java:137)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-19 18:58:43.365: E/AndroidRuntime(27915): at dalvik.system.NativeStart.main(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): Caused by: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.example.mypassthrough.MainActivity.onCreate(MainActivity.java:46)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Activity.performCreate(Activity.java:5133)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-19 18:58:43.365: E/AndroidRuntime(27915): ... 11 more
What could be the reason for this code crashing, and how can it be debugged? I am pretty sure it has something to do with Thread, because my other versions of this code where I have not included Thread at all do not crash on startup.
Variable newThread is not initialized in oncreate() method that's why it is giving nullpointer exception
add this in your init() method it will work
newThread=new Thread();
You are getting a null pointer exception because newThread has not been initialized yet and it is null when you try to start it. The thread doesn't have anything to do also. You should look at implementing a runnable, handler, and timer into your activity instead of a thread.
Use sub class with extending AsyncTask Class
class TestActivity extends AsyncTask <String, Void, String > {
protected String doInBackground(String... urls) {
// execution
}
protected void onPostExecute(String result) {
// post execution
}
protected void onPreExecute() {
super.onPreExecute();
// initial activities
}
}

Force Closes on Opening Activity

I am working on an app where you touch the screen and the basketball moves there. I am almost there except it force closes when you open this mini-app from a list of activities to start. After scanning through several times I could not find anything.
This is my Java Class and after is the Logcat:
package com.frostbytedev.addsub;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewExample extends Activity implements OnTouchListener {
OurView v;
Bitmap ball;
float x = 0;
float y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new OurView(this);
setContentView(v);
v.setOnTouchListener(this);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.bball);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isItOkay = false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isItOkay) {
if(!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 150);
c.drawBitmap(ball, x-(ball.getWidth()/2), y-(ball.getHeight()/2), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause(){
isItOkay = false;
while(true){
try{
t.join();
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void resume() {
isItOkay = true;
t = new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
return false;
}
}
Logcat:
05-09 19:24:35.730: D/libEGL(8218): loaded /system/lib/egl/libEGL_adreno200.so
05-09 19:24:35.740: D/libEGL(8218): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-09 19:24:35.750: D/libEGL(8218): loaded /system/lib/egl/libGLESv2_adreno200.so
05-09 19:24:35.800: D/OpenGLRenderer(8218): Enabling debug mode 0
05-09 19:24:44.658: D/AndroidRuntime(8218): Shutting down VM
05-09 19:24:44.658: W/dalvikvm(8218): threadid=1: thread exiting with uncaught exception (group=0x40a7a930)
05-09 19:24:44.668: E/AndroidRuntime(8218): FATAL EXCEPTION: main
05-09 19:24:44.668: E/AndroidRuntime(8218): java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.frostbytedev.addsub.Menu.onListItemClick(Menu.java:25)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView.performItemClick(AbsListView.java:1102)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2751)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView$1.run(AbsListView.java:3426)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Handler.handleCallback(Handler.java:725)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Looper.loop(Looper.java:137)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.app.ActivityThread.main(ActivityThread.java:5237)
05-09 19:24:44.668: E/AndroidRuntime(8218): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 19:24:44.668: E/AndroidRuntime(8218): at java.lang.reflect.Method.invoke(Method.java:511)
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
05-09 19:24:44.668: E/AndroidRuntime(8218): at dalvik.system.NativeStart.main(Native Method)

If condition causing program to force close

I am doing an android app and i was thinking of creating a theme option. Well all I was thinking of doing was to allow the user to click on a image button which represented a theme. And when he clicks on it I start a new activity i.e i direct him to the home page. Also i have created a few integer variables which are set to 1 when the user clicks on a button.
Then in the other classes all i do is check if the variables are 1 or not and depending on that i apply the theme. By theme i mean i just change the background wallpaper. But this is not working. I mean the code works but if use an if loop to check the variable values and then apply the effects it causes an error.
Here's the complete code:
package com.example.themetest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements OnClickListener{
ImageButton ib1;
ImageButton ib2;
int water=0;
int fire=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib1 = (ImageButton) findViewById(R.id.imageButton1);
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib1.setOnClickListener(this);
ib2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
}
Here's the other class where i check which variable is set to 1 and apply the effect.
package com.example.themetest;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.LinearLayout;
public class Theme extends Activity{
MainActivity main;
Resources res;
Drawable drawable;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(main.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(main.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}
}
I can change the wallpaper without using the if loop, but i want to do it this way which is not working. Can anyone please tell me why?
Log cat:
01-15 12:08:23.339: D/dalvikvm(273): GC_EXTERNAL_ALLOC freed 767 objects / 55936 bytes in 235ms
01-15 12:08:25.539: D/AndroidRuntime(273): Shutting down VM
01-15 12:08:25.539: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-15 12:08:25.559: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-15 12:08:25.559: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.themetest/com.example.themetest.Theme}: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-15 12:08:25.559: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-15 12:08:25.559: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-15 12:08:25.559: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-15 12:08:25.559: E/AndroidRuntime(273): at com.example.themetest.Theme.onCreate(Theme.java:29)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-15 12:08:25.559: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-15 12:08:25.559: E/AndroidRuntime(273): ... 11 more
01-15 12:08:31.089: I/Process(273): Sending signal. PID: 273 SIG: 9
I think the better way to do this is pass the name or code of the theme user selected along with the intent.
This might help: Passing data through Intent and receiving it
You cannot access other activities variables this way, a better way (for example) is to use a constant class..
public class Constants {
public static int water=0;
public staticint fire=0;
}
MainActivity:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.imageButton1:
Constants.water = 1;
Intent wi = new Intent("com.example.themetest.THEME");
startActivity(wi);
break;
case R.id.imageButton2:
Constants.fire = 1;
Intent fi = new Intent("com.example.themetest.THEME");
startActivity(fi);
break;
}
}
Theme:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theme);
if(Constants.water==1){
res = getResources();
drawable = res.getDrawable(R.drawable.water_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else if(Constants.fire==1){
res = getResources();
drawable = res.getDrawable(R.drawable.fire_theme);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
else{
res = getResources();
drawable = res.getDrawable(R.drawable.ic_launcher);
linearLayout = (LinearLayout)findViewById(R.id.ll);
linearLayout.setBackgroundDrawable(drawable);
}
}

Lower version app not running in the Higher version in android

I have made my application using android SDK 2.2 version and now when I am running my app on android SDK 4.0.3 it's not running.
I have given the min and the max sdk in the manifest file.
I am new in android and want to run my app for the lower and higher versions both. Can anybody tell me how can I do this. Any help is appreciated.
Code for splash class
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// thread for displaying the SplashScreen
splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
stop();
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(splashTread){
splashTread.notifyAll();
}
}
return true;
}
}
EDIT: My logcat
06-07 10:24:18.710: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:18.760: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:18.890: D/dalvikvm(1461): GC_FOR_ALLOC freed 45K, 4% free 6541K/6787K, paused 74ms
06-07 10:24:18.900: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.333MB for 921616-byte allocation
06-07 10:24:19.010: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.100: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:19.140: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 5% free 7440K/7751K, paused 5ms+5ms
06-07 10:24:19.240: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7440K/7751K, paused 97ms
06-07 10:24:19.240: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.723MB for 409936-byte allocation
06-07 10:24:19.320: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7841K/8199K, paused 61ms
06-07 10:24:19.589: D/gralloc_goldfish(1461): Emulator without GPU emulation detected.
06-07 10:24:19.669: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.779: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:24.600: W/dalvikvm(1461): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
06-07 10:24:24.600: E/AndroidRuntime(1461): FATAL EXCEPTION: Thread-78
06-07 10:24:24.600: E/AndroidRuntime(1461): java.lang.UnsupportedOperationException
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1076)
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1063)
06-07 10:24:24.600: E/AndroidRuntime(1461): at com.Cricket_trivia.in.SplashScreen$1.run(SplashScreen.java:40)
06-07 10:24:26.209: D/dalvikvm(1461): GC_FOR_ALLOC freed 1037K, 15% free 7022K/8199K, paused 62ms
06-07 10:24:26.209: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.509MB for 614416-byte allocation
06-07 10:24:26.440: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 8% free 7621K/8199K, paused 4ms+5ms
06-07 10:24:26.610: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:26.640: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
The reason why your app is crashing on 4.0.3 but not 2.2 is most likely because you are performing an expensive operation on the UI thread. Blocking the UI thread is very bad practice... don't do it!! Previous versions of Android (i.e. pre-ICS versions) didn't care when you did this and let your app run as is. In 4.0 and above, however, the OS checks against this and crashes your app if you ever perform a potentially expensive operation on the UI thread (such as a network connection, etc.).
You have provided basically no information on what the problem is in your question, so that's all I can really do to help you out.
Edit:
Does something like this work?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
}
return true;
}
Don't you threads because it is creating the problem in the higher version. Use the code below to show the splash screen.
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
MyCount counter = new MyCount(4000, 4000);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long csecond, long countDownInterval)
{
super(csecond, countDownInterval);
}
#Override
public void onFinish() {
finish();
Intent intent = new Intent();
intent.setClass(SplashScreen.this, K_trivia_cricketActivity.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}
}
I think it will work for you

Categories