unexpedtedly close application - java

When i run my application i get unfortunately stop app message, following is my code. Please take a look.
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.dublayout);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/javacodegeeksRecording.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
addListenerButton();
}
private void addListenerButton() {
recbtn = (Button)findViewById(R.id.recbut);
recbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
}
public void start(View view){
if (recbtn.getText() == getString(R.string.recBtn)){
try {
myRecorder.prepare();
myRecorder.start();
recbtn.setText(getString(R.string.stopBtn));
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
else{
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
recbtn.setText(getString(R.string.recBtn));
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
}
it is not recording i tried everything still i cannot get it working sorry but i am still new to this kind of language.
In logcat it says:
02-05 08:01:09.853: D/OpenGLRenderer(1565): TextureCache::get: create
texture(0xb87af490): name, size, mSize = 22, 9216, 9149524 02-05
08:01:19.125: E/MediaRecorder(1565): stop called in an invalid state:
4 02-05 08:01:19.125: W/System.err(1565):
java.lang.IllegalStateException 02-05 08:01:19.129:
W/System.err(1565): at android.media.MediaRecorder.stop(Native
Method) 02-05 08:01:19.129: W/System.err(1565): at
com.example.mixpad.DubActivity.start(DubActivity.java:136) 02-05
08:01:19.129: W/System.err(1565): at
com.example.mixpad.DubActivity$2.onClick(DubActivity.java:99) 02-05
08:01:19.129: W/System.err(1565): at
android.view.View.performClick(View.java:4084) 02-05 08:01:19.133:
W/System.err(1565): at
android.view.View$PerformClick.run(View.java:16966) 02-05
08:01:19.137: W/System.err(1565): at
android.os.Handler.handleCallback(Handler.java:615) 02-05
08:01:19.137: W/System.err(1565): at
android.os.Handler.dispatchMessage(Handler.java:92) 02-05
08:01:19.141: W/System.err(1565): at
android.os.Looper.loop(Looper.java:137) 02-05 08:01:19.141:
W/System.err(1565): at
android.app.ActivityThread.main(ActivityThread.java:4745) 02-05
08:01:19.141: W/System.err(1565): at
java.lang.reflect.Method.invokeNative(Native Method) 02-05
08:01:19.145: W/System.err(1565): at
java.lang.reflect.Method.invoke(Method.java:511) 02-05 08:01:19.145:
W/System.err(1565): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-05 08:01:19.145: W/System.err(1565): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 02-05
08:01:19.149: W/System.err(1565): at
dalvik.system.NativeStart.main(Native Method)
can anyone help please

In your start(...) method...
if (recbtn.getText() == getString(R.string.recBtn))
You can't compare strings in Java using ==. You need to use equals(...).
Your problem is using == will always fail which means the else condition will always be called and myRecorder.stop(); will throw the IllegalStateException as your MediaRecorder has never been prepared / started.
Change that line to...
if (recbtn.getText().equals(getString(R.string.recBtn)))

Related

Cannot update text in EditText inside onActivityResult

I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
            at android.app.ActivityThread.access$1100(ActivityThread.java:150)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...

Android IllegalStateException when recording audio on some devices

I want my program to record audio for 10 seconds and then stop and store my record in file storage, everything works fine on my Nexus 4 and Galaxy S 5, but when i test it in Galaxy S3 it crushes and raise error
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/AudioCaptureDemo﹕ prepare() failed
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/MediaRecorder﹕ start called in an invalid state: 4
10-02 02:13:44.942 1279-1279/com.taptester.tappapp D/AndroidRuntime﹕ Shutting down VM
10-02 02:13:44.942 1279-1279/com.taptester.tappapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a12ba8)
10-02 02:13:44.952 1279-1279/com.taptester.tappapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.taptester.tappapp, PID: 1279
java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.taptester.tappapp.MainActivity.startRecording(MainActivity.java:203)
at com.taptester.tappapp.MainActivity.access$300(MainActivity.java:62)
at com.taptester.tappapp.MainActivity$6.onFinish(MainActivity.java:825)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
First i thought the error is in the file name, I'm declaring it like this:
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory() + File.separator
+ Environment.DIRECTORY_DCIM + File.separator + "MyMemo.3gp";
//Environment.getExternalStorageDirectory().getAbsolutePath();
//mFileName += "/MyMemo.3gp";
}
Then i make a record like this:
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
Then i call the "StartRecording" method like this:
else if(command.equals("2")) {
startRecording();
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
CountDownTimer start = new CountDownTimer(timer, 1000) {
#Override
public void onTick(long l) {
Toast.makeText(getApplicationContext(), "Recording!!!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
stopRecording();
}
}.start();
you are not supposed to call mRecorder.start(); when mRecorder.prepare(); fails.
this is what caused the Illegal State Exception to be thrown.
Not all devices support all the encoding formats.
try changing these mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
and mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
change the format and Encoder to a file format and encoding format your s3 device supports.
for a start, change your encoding setting to default settings as follows and try if it works.
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

java.lang.IllegalStateException in MediaPlayer.isplaying() method

public static MediaPlayer mp=null;
public static void playGeneric(int name, final ImageButton button,final ImageButton pervious,Context context) {
button.setEnabled(false);
button.setClickable(false);
pervious.setEnabled(false);
pervious.setClickable(false);
try{
if(mp != null && mp.isPlaying())
{
mp.stop();
mp.release();
mp = null;
mp=MediaPlayer.create(context, name);
mp.start();
}
else
{
mp = MediaPlayer.create(context, name);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
//mp.prepare();
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
System.out.println("Object released");
button.setEnabled(true);
button.setClickable(true);
pervious.setEnabled(true);
pervious.setClickable(true);
}
});
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.getMessage();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.getMessage();
}
}
give me java.lang.IllegalStateException on mp.isplaying() method.
I want to stop music if it's playing and play another song one after another.
logcat:
10-14 15:12:05.474: E/MediaPlayer(15411): prepareAsync called in state 8
10-14 15:12:05.474: W/System.err(15411): java.lang.IllegalStateException
10-14 15:12:05.474: W/System.err(15411): at android.media.MediaPlayer.prepare(Native Method)
10-14 15:12:05.474: W/System.err(15411): at com.rogerscenter.LearnReadWriteSpell.Utility.Music.playGeneric(Music.java:93)
10-14 15:12:05.474: W/System.err(15411): at com.rogerscenter.LearnReadWriteSpell.LetterCategory.Letter_Lesson1_activity.onCreate(Letter_Lesson1_activity.java:140)
10-14 15:12:05.474: W/System.err(15411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-14 15:12:05.474: W/System.err(15411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
10-14 15:12:05.484: W/System.err(15411): at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 15:12:05.484: W/System.err(15411): at android.os.Looper.loop(Looper.java:123)
10-14 15:12:05.484: W/System.err(15411): at android.app.ActivityThread.main(ActivityThread.java:3647)
10-14 15:12:05.484: W/System.err(15411): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 15:12:05.484: W/System.err(15411): at java.lang.reflect.Method.invoke(Method.java:507)
10-14 15:12:05.484: W/System.err(15411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-14 15:12:05.484: W/System.err(15411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-14 15:12:05.484: W/System.err(15411): at dalvik.system.NativeStart.main(Native Method)
Try changing mp.release() into reset(). that could help you.
As android docs suggest that if mp is if has not been initialized at that time java.lang.IllegalStateException will be thrown so you have to initilize first or you have to write
check out the docs http://developer.android.com/reference/android/media/MediaPlayer.html#isPlaying()
try like this
mp=MediaPlayer.create(context, name);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp=MediaPlayer.create(context, name);
}
mp.start();
} catch (Exception e) {
}
Ok i am here with my solution, hope it will help others.
(i) if you are using videoView and mediaPlayer.isPlaying() (isNative) error occurs
on activity stop
Add this onStop() method:
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
videoView.stopPlayback();
}
Note: Don't use mediaPlayer.stop() or mediaPlayer.release() here when you work with videoView, it will throw IllegalException
(ii) If you are using mediaPlayer to play only audio
Add this onStop() method:
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
Note: This is only for those who get error when your activity is in stop or in resume state.
This could happen if you are trying to stop audio when the player hasn't started playing yet. Hence the IllegalStateException
See if you can prevent that. You can also putting a try catch around the isPlaying()
fun isPlaying(): Boolean {
return try {
mediaPlayer?.isPlaying == true
} catch (illegalStateException: IllegalStateException) {
DebugLog.d(TAG, illegalStateException.message)
DebugLog.d(TAG, illegalStateException.stackTraceToString())
false
}
}
use runOnUiThread for mediaRecorder prepare.
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
runOnUiThread(new Runnable() {
#Override
public void run() {
mediaRecorder.reset();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
} catch (IOException e) {
mediaRecorder = null;
return;
}
mediaRecorder.start();
recording = true;
}
});
return true;
}

Gson and Google

I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Code keeps thowing a NPE, cannot find the cause

i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
 Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.

Categories

Resources