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.
Related
I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.
I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody
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();
}
});
I'm trying to make a connection between my galaxy tab and my laptop. So I'm trying to run server activity on my laptop and client activity on my tab, but it doesn't work. Here is the server and client code. Where is the mistake?
SERVER:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView)findViewById(R.id.textView1);
int port = 12345;
byte [] message = new byte [1500];
DatagramPacket p = new DatagramPacket (message,message.length);
try {
InetAddress serveraddr = InetAddress.getByName("192.168.1.116");
DatagramSocket s = new DatagramSocket (port,serveraddr);
while (true){
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENT:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String msg = edt.getText().toString();
int port = 12345;
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("192.168.1.116");
int msg_lenght = msg.length();
byte []message = msg.getBytes();
DatagramPacket p = new DatagramPacket(message,msg_lenght,local,port);
s.send(p);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Here is the log:
09-17 23:49:55.190: D/dalvikvm(5892): Late-enabling CheckJNI 09-17
23:49:55.690: D/CLIPBOARD(5892): Hide Clipboard dialog at Starting
input: finished by someone else... ! 09-17 23:49:59.590:
D/AndroidRuntime(5892): Shutting down VM 09-17 23:49:59.590:
W/dalvikvm(5892): threadid=1: thread exiting with uncaught exception
(group=0x40c4f1f8) 09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL
EXCEPTION: main 09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
libcore.io.IoBridge.sendto(IoBridge.java:463) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
java.net.DatagramSocket.send(DatagramSocket.java:307) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
com.example.udpclient.MainActivity$1.onClick(MainActivity.java:36)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
android.view.View.performClick(View.java:3620) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.view.View$PerformClick.run(View.java:14322) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.handleCallback(Handler.java:605) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Handler.dispatchMessage(Handler.java:92) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
android.os.Looper.loop(Looper.java:137) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
android.app.ActivityThread.main(ActivityThread.java:4507) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invokeNative(Native Method) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
java.lang.reflect.Method.invoke(Method.java:511) 09-17 23:49:59.590:
E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
09-17 23:49:59.590: E/AndroidRuntime(5892): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 09-17
23:49:59.590: E/AndroidRuntime(5892): at
dalvik.system.NativeStart.main(Native Method) 09-17 23:50:34.320:
I/Process(5892): Sending signal. PID: 5892 SIG: 9
09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException
09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
You shouldn't do network or time intensiv operations in ui thread
See also:
Android: NoClassDefFoundError for some app users or
android developers information
Checkout:
activity.runOnUi
You have an infinite loop in onCreate of the Server. You shouldn't! Create a thread for polling the socket.
you cannot send udp packets on ui thread, so a new seperate thread must be created.
Just a quick solution...
create a udpOutputData string:
String udpOutputData;
create a new thread in your code:
//-----UDP send thread
Thread udpSendThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (sendUdp == true) {
try {
// get server name
InetAddress serverAddr = InetAddress.getByName(outputIP);
Log.d("UDP", "C: Connecting...");
// create new UDP socket
DatagramSocket socket = new DatagramSocket();
// prepare data to be sent
byte[] buf = udpOutputData.getBytes();
// create a UDP packet with data and its destination ip & port
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort);
Log.d("UDP", "C: Sending: '" + new String(buf) + "'");
// send the UDP packet
socket.send(packet);
socket.close();
Log.d("UDP", "C: Sent.");
Log.d("UDP", "C: Done.");
}
catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendUdp = false;
}
}
}
});
create a method to call everytime you want to send some udp data:
public void sendUdp(String udpMsg) {
udpOutputData = udpMsg;
sendUdp = true;
}
call the method and pass a string for the output data everytime you want to send a udp packet:
String s = "hello from app";
sendUdp(s);
Have 2 problems with your code
Work with Network on Main thread (UI Thread)
09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL EXCEPTION: main
09-17 23:49:59.590: E/AndroidRuntime(5892):
android.os.NetworkOnMainThreadException
Loop while(true) on the Main thread:
while(true) {
s.receive(p);
String text = new String (message,0,p.getLength());
txt.setText(text);
}
I am new to android programming.I have been trying to establish connection between two emulators.While my server emulator is up and running,client has a problem.Here is the code and logcat error description.Please tell me the error in this.
public class SocketClient extends Activity
{
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
public void connect()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
System.out.println("Here");
}
catch (IOException e1)
{
e1.printStackTrace();
System.out.println("Here too");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
connect();
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception e)
{
tv.setText("Error3");
e.printStackTrace();
}
}
}
);
}
}
The logcat error is
01-31 04:42:51.170: W/dalvikvm(529): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-31 04:42:51.187: E/AndroidRuntime(529): FATAL EXCEPTION: main
01-31 04:42:51.187: E/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ServerClient/com.app.ServerClient.SocketClient}: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:137)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 04:42:51.187: E/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): Caused by: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.connect(SocketClient.java:25)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.onCreate(SocketClient.java:48)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Activity.performCreate(Activity.java:4465)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-31 04:42:51.187: E/AndroidRuntime(529): ... 11 more
Thanks in advance.
Thank You David and Jitendra.
I corrected the error and I get a nullPointerException in one part of the code.What did I do wrong?
public void onClick(View v)
{
try // The error is in this block
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception f) // I get the error here. java.lang.NullPointerException
{
tv.setText("Error3");
tv.setText(f.toString());
f.printStackTrace();
}
}
Your error is on this line:
tv.setText((CharSequence) serverAddr);
serverAddr is of type InetAddress, and you're trying to cast it to a CharSequence which cannot be done. Perhaps you meant:
tv.setText(serverIpAddress);
Exception is in following line:
tv.setText((CharSequence) serverAddr);
and it is because you are trying to cast serverAddr into CharSequence.
If you really want to print serverAddr use
tv.setText((CharSequence) serverAddr.toString());