threadid=1: thread exiting with uncaught exception error - java

I'm recieving an error of threadid=1... I don't always get it but I do at a point in the app at sometime. Not sure what my specific error is. I've check line 164 and I don't see anything that would cause the result. Maybe something I need to add into my manifest? Here is my LogCat.
05-08 17:19:28.796: W/dalvikvm(8683): threadid=1: thread exiting with uncaught exception (group=0x40e37438)
05-08 17:19:28.806: E/AndroidRuntime(8683): FATAL EXCEPTION: main
05-08 17:19:28.806: E/AndroidRuntime(8683): java.lang.NullPointerException
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.example.speech.MainActivity$SpeechListener.onResults(MainActivity.java:164)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.speech.SpeechRecognizer$InternalListener$1.handleMessage(SpeechRecognizer.java:442)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.os.Looper.loop(Looper.java:137)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.app.ActivityThread.main(ActivityThread.java:4918)
05-08 17:19:28.806: E/AndroidRuntime(8683): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 17:19:28.806: E/AndroidRuntime(8683): at java.lang.reflect.Method.invoke(Method.java:511)
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-08 17:19:28.806: E/AndroidRuntime(8683): at dalvik.system.NativeStart.main(Native Method)
Here is my Main Activity Code:
package com.example.speech;
import java.util.ArrayList;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.util.Log;
public class MainActivity extends Activity implements OnClickListener {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
boolean reseter = false;
private AudioManager mAudioManager;
private volatile boolean mNoSpeechCountDownOn;
MediaPlayer testSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean available = SpeechRecognizer.isRecognitionAvailable(this);
Log.d("Speech", "available = " + available);
testSound = MediaPlayer.create(MainActivity.this, R.raw.soundclip);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 0);
mAudioManager = (AudioManager) getSystemService(this.AUDIO_SERVICE);
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
try {
Thread.sleep(4000);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}
}
private CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#SuppressWarnings("synthetic-access")
#Override
public void onFinish()
{
mNoSpeechCountDownOn = false;
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
};
#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 class SpeechListener implements RecognitionListener {
#Override
public void onBeginningOfSpeech() {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.d("Speech", "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
}
#Override
public void onError(int error) {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onError");
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.d("Speech", "onEvent");
}
#Override
public void onPartialResults(Bundle partialResults) {
Log.d("Speech", "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mNoSpeechCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("Speech", "onReadyForSpeech");
try {
Thread.sleep(6000);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}}
#Override
public void onResults(Bundle results) {
Log.d("Speech", "results");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (String match : matches) { if (match.equals("one")) testSound.start();
else if (match.equals("two")) testSound.start();
}
// Do whatever you want here
try {
Thread.sleep(1);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}
}
#Override
public void onRmsChanged(float rmsdB) {
//Log.d("Speech", "onRmsChanged");
}
}
#Override
public void onClick(View arg0) {
//must keep the onClick
}
}

05-08 17:19:28.806: E/AndroidRuntime(8683): java.lang.NullPointerException
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.example.speech.MainActivity$SpeechListener.onResults(MainActivity.java:164)
Guessing that line 164 is
else if (match.equals("two")) testSound.start();
I suspect your match can be null sometimes. If so, the match.equals... code will crash for pretty much obvious reason. The simplest solution is to change this line, from:
else if (match.equals("two")) testSound.start();
to more safe form:
else if ("two".equals(match)) testSound.start();

ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches!=null) {
for (String match : matches)
/* ... */
}
matches may be null if there are no matches.

Related

I'm building a media player app, my application is getting a fatal exception

I don't know what to do now, I'm new to Android.
package com.example.macbookpro.myplayer;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class AudioPlayer extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
ImageView btn_play;
Button btn_pause;
ImageView btn_next;
ImageView btn_prev;
ImageView btn_forward;
ImageView btn_backward;
TextView song_title;
int currentsongindex;
int seekForwardTime = 5000;
int seekBackwardTime = 5000;
private Utilities utilities;
Handler mHandler1=new Handler();
SeekBar song_progressbar;
final ArrayList<File> arrayList = new ArrayList<File>();
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
btn_play = (ImageView) findViewById(R.id.btn_play);
btn_next = (ImageView) findViewById(R.id.btn_next);
btn_prev = (ImageView) findViewById(R.id.btn_prev);
btn_forward = (ImageView) findViewById(R.id.btn_forward);
btn_backward = (ImageView) findViewById(R.id.btn_backwrd);
song_title = (TextView) findViewById(R.id.tw);
song_progressbar=(SeekBar)findViewById(R.id.song_progressbar);
song_progressbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
try {
PlaySongtwo(getIntent().getStringExtra("index"));
} catch (IOException e) {
e.printStackTrace();
}
final String[] sec = getIntent().getStringArrayExtra("index2");
currentsongindex = Integer.parseInt((getIntent().getStringExtra("positionofcurrentsong")));
utilities = new Utilities();
// Button for playing the song
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
btn_play.setImageResource(R.drawable.button_play);
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
}
});
// Button for the next song in the list
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("currenttt song is ",currentsongindex+"");
if(currentsongindex < (sec.length-1)){
int cc=currentsongindex+1;
Log.e("value in cc",cc+"");
try {
PlaySongtwo(sec[cc]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("next song number is ",cc +"");
currentsongindex = currentsongindex +1;
}else {
try {
PlaySongtwo(sec[0]);
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = 0;
}
}
});
//Button for the previous song in the list
btn_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentsongindex > 0){
int prevsong= currentsongindex-1;
try {
PlaySongtwo(sec[prevsong]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("prev song",prevsong+"");
currentsongindex = prevsong;
}else {
try {
PlaySongtwo(String.valueOf((sec.length-1)));
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = sec.length-1;
}
}
});
//Button for fast-forwarding the song
btn_forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition + seekForwardTime <= mp.getDuration() ){
mp.seekTo(currentPosition + seekForwardTime);
}else {
mp.seekTo(mp.getDuration());
}
}
});
//Button for fast-backwarding the song
btn_backward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPostion = mp.getCurrentPosition();
if(currentPostion - seekBackwardTime >= 0){
mp.seekTo(currentPostion - seekBackwardTime);
}else {
mp.seekTo(0);
}
}
});
}
private void PlaySongtwo(String path) throws IOException {
try {
String songname = path.substring(path.lastIndexOf("/") + 1);
song_title.setText(songname);
mp.reset();
Uri myUri = Uri.parse(path);
mp.setDataSource(AudioPlayer.this, myUri);
mp.prepare();
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
song_progressbar.setProgress(0);
song_progressbar.setMax(100);
updateProgressBar1();
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateProgressBar1() {
mHandler1.postDelayed(mUpdateTimeTask1,100);
}
private Runnable mUpdateTimeTask1=new Runnable() {
#Override
public void run() {
long totalDuration = mp.getDuration();
long currentDuration=mp.getCurrentPosition();
int progress=(int)(utilities.getProgresspercentage(currentDuration,totalDuration));
song_progressbar.setProgress(progress);
mHandler1.postDelayed(this,100);
}
};
#Override
protected void onDestroy ()
{
super.onDestroy();
mp.release();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
int totalDuration=mp.getDuration();
int currentPosition=utilities.progressToTimer(seekBar.getProgress(),totalDuration);
mp.seekTo(currentPosition);
updateProgressBar1();
}
#Override
public void onCompletion(MediaPlayer mp1) {
enter code here
}
}
This is the error I'm facing.
11-06 13:30:03.935 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:04.031 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:22.260 1060-1060/com.example.macbookpro.myplayer D/AndroidRuntime: Shutting down VM
11-06 13:30:22.261 1060-1060/com.example.macbookpro.myplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.macbookpro.myplayer, PID: 1060
java.lang.IllegalStateException
at android.media.MediaPlayer.getDuration(Native Method)
at com.example.macbookpro.myplayer.AudioPlayer$6.run(AudioPlayer.java:220)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
My guess is that you are trying to getDuration before your MediaPlayer is ready to be used.
Make sure you're setting all controls that interact with the mediaplayer.

ImageButton to open a new activity

I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.

Android SeekBar NullPointerException

I have a probleme with my code. When I lunch my program i have a crash.
On the Android monitor i can see :
04-04 20:21:10.369 2042-2042/com.led.led E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.led.led, PID: 2042
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.led.led/com.led.led.ledControlSeekBar}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at com.led.led.ledControlSeekBar.onCreate(ledControlSeekBar.java:76)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5294) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
And there is my class :
package com.led.led;
import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.SeekBar;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.io.IOException;
import java.util.UUID;
import java.lang.String;
public class ledControlSeekBar extends AppCompatActivity {
Button btnDis;
SeekBar seek_r, seek_g, seek_b;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ConnectBT bt = new ConnectBT();
String phraseAEnvoyer = "000000000";
String phraseTemp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);
bt.execute();
//view of the ledControl layout
setContentView(R.layout.activity_led_control);
//call the widgtes
btnDis = (Button)findViewById(R.id.button_disconnect);
seek_r = (SeekBar)findViewById(R.id.seekBar_r);
seek_g = (SeekBar)findViewById(R.id.seekBar_g);
seek_b = (SeekBar)findViewById(R.id.seekBar_b);
seek_r.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Rouge : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(3, 9);
phraseAEnvoyer = progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_g.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Vert : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(6, 9);
phraseAEnvoyer = phraseAEnvoyer.substring(0, 3);
phraseAEnvoyer = phraseAEnvoyer + progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_b.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Bleu : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(0, 6);
phraseAEnvoyer = phraseTemp + progressChanged;
envoyerPhrase(phraseAEnvoyer);
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void envoyerPhrase(String phrase)
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(phraseAEnvoyer.getBytes());
msg(phraseAEnvoyer);
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControlSeekBar.this, "Connecting...", "Please wait!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
I don't finish and some lines are useful sorry.
If someone can help me I will happy.
Thank you.
I have also the same error . I resolved this error by defining a function outside the onCreate() method. Inside that function you need to call the different seek bar findViewByid method . Like this
private void initializeVariables() {
// Showing progress dialog
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
seekBar = (SeekBar) findViewById(R.id.seekBarprice);
seekBarKilometer = (SeekBar) findViewById(R.id.seekBarDis);
}
Declare pDialog first private ProgressDialog pDialog;
call the initializeVariables() method inside the oncreate method , here i mention my seekbar names replace these names with your code .
`

fatal exception: main java.lang.RuntimeException in android map,

i'm currently working on android maps by following this tutorial http://developer.android.com/training/location/retrieve-current.html, and i keep getting error.there are 4 warnings and i tried to fix it but when i run it again the error message fatal exception still showing
here's the warning messages:
1. the message servicesConnected() from the type LokasiKampus is never used locally
2. the value of local variable kampus is not used
3. the value of local variable laboratorium is not used
4.the value of local variable myCurrentLocation is not used
here's my Java code
package ninth.example.dteinformationcenter;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LokasiKampus extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
static final LatLng Kampus = new LatLng (-7.775038, 110.373253);
static final LatLng Laboratorium = new LatLng (-7.765437, 110.374496);
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap map;
private GooglePlayServicesClient myLocationClient;
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
// TODO Auto-generated method stub
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch(resultCode) {
case Activity.RESULT_OK : break;
}
}
}
**private boolean servicesConnected()** {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updated", "Google Play Services is available");
return true;
} else {
Dialog ErrorDialog = GooglePlayServicesUtil
.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (ErrorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(ErrorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_kampus);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.lokasikampus)).getMap();
if (map != null) {
**Marker kampus = map.addMarker(new MarkerOptions().position(Kampus)
.title("Kampus "));
Marker laboratorium = map.addMarker(new MarkerOptions().position(Laboratorium)
.position(Laboratorium)
.title("Laboratorium")
);**
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Kampus, 18));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
LocationClient myLocationClient = new LocationClient(this,this,this);
**Location myCurrentLocation;
myCurrentLocation = myLocationClient.getLastLocation();**
}
#Override
public void onConnected(Bundle dataBundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected, please re-connect", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch(IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
myLocationClient.connect();
}
#Override
protected void onStop() {
myLocationClient.disconnect();
super.onStop();
}
}
this is the error message
FATAL EXCEPTION: main
Process: ninth.example.dteinformationcenter, PID: 1443
java.lang.RuntimeException: Unable to start activity ComponentInfo{ninth.example.dteinformationcenter/ninth.example.dteinformationcenter.LokasiKampus}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
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)
Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.gms.internal.hb.cn(Unknown Source)
at com.google.android.gms.internal.jg.b(Unknown Source)
at com.google.android.gms.internal.jg$c.cn(Unknown Source)
at com.google.android.gms.internal.jf.getLastLocation(Unknown Source)
at com.google.android.gms.internal.jg.getLastLocation(Unknown Source)
at com.google.android.gms.location.LocationClient.getLastLocation(Unknown Source)
at ninth.example.dteinformationcenter.LokasiKampus.onCreate(LokasiKampus.java:112)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

Permission Denial Error - SpeechRecognizer as a continuous service? (android.permission.INTERACT_ACROSS_USERS_FULL)

EDITED:
I have changed my service code to implement as started service instead of IntentService as updated StreamService.java below
Now, I am getting error regarding permission denial error as described in logcat messages after StreamService.java
EDITED:
As mentioned in Android Developer site that SpeechRecognizer API can only be used as Application Context. Is there any woraround with which I can get it working
I have implemented MainActivity class that has all the UI Components. Class is as below
CODE - MainActivity.java
package com.example.speechsensorservice;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "SpeechSensor";
private boolean headsetConnected = false;
public TextView txtText;
private BroadcastReceiver mReceiver;
private ImageButton btnSpeak;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),StreamService.class);
startService(intent);
}
});
}
protected void onResume() {
super.onResume();
IntentFilter sIF = new IntentFilter();
sIF.addAction(Intent.ACTION_HEADSET_PLUG);
sIF.addAction("com.example.speechsensorservice.TEXT");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String act = arg1.getAction();
Log.d(TAG, "Received Action = " + act);
if ( Intent.ACTION_HEADSET_PLUG.equals(act) ) {
if ( arg1.hasExtra("state")) {
if ( !headsetConnected && arg1.getIntExtra("state", 0) == 1 ) {
headsetConnected = true;
txtText.setText("Headset Plugged in");
startNoiseProcessService();
}
}
}
else if ( act.equals("com.example.speechsensorservice.TEXT") ){
if ( arg1.hasExtra("Identity")) {
String s = arg1.getStringExtra("Identity");
if ( s.equals("NA") ) {
Toast t = Toast.makeText(getApplicationContext(),
"Your Device doesnot support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
else txtText.setText(s);
}
}
}
};
this.registerReceiver(mReceiver, sIF);
}
public void onPause() {
super.onPause();
this.unregisterReceiver(this.mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startNoiseProcessService() {
Intent intent = new Intent(this,StreamService.class);
startService(intent);
}
}
Another class that I have implemented to start Speech Recognition Service as a background task by inheriting IntentService class. The implementation is as below
Code - StreamService.java
package com.example.speechsensorservice;
import java.util.ArrayList;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
public class StreamService extends Service {
private static final String TAG = "SpeechSensor";
private static final String ACTION = "com.example.speechsensorservice.TEXT";
private SpeechRecognizer sr;
private BroadcastReceiver sReceiver;
private boolean headsetConnected = true;
String text;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate() StreamService Method");
super.onCreate();
sReceiver = new BroadcastReceiver() {
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if ( Intent.ACTION_HEADSET_PLUG.equals(arg1.getAction()) ) {
if ( arg1.hasExtra("state")) {
if ( headsetConnected && arg1.getIntExtra("state", 0) == 0 ) {
headsetConnected = false;
stopStreaming();
}
}
}
}
};
this.registerReceiver(sReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"Inside onStartCommand()");
// Runnable r = new Runnable() {
// public void run() {
startStreaming();
// }
// };
// Thread t = new Thread(r);
// t.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy() StreamService Method");
super.onDestroy();
this.unregisterReceiver(this.sReceiver);
}
public void startStreaming() {
Log.d(TAG, "Inside startStreaming()");
Intent intent;
text = "";
if ( !SpeechRecognizer.isRecognitionAvailable(this) ) {
Log.d(TAG, "Not Applicable with your device");
text = "NA";
intent = new Intent(ACTION);
intent.putExtra("Identity", text);
sendBroadcast(intent);
}
else {
Log.d(TAG, "started taking input");
sr = SpeechRecognizer.createSpeechRecognizer(this.getApplicationContext());
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");//RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);//RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
sr.setRecognitionListener( new mylistener());
sr.startListening(intent);
}
}
public void stopStreaming() {
if ( sr == null ) return;
Log.d(TAG, "stopped taking input");
sr.cancel();
sr.destroy();
sr = null;
this.stopSelf();
}
public boolean isStreaming() {
// TODO Auto-generated method stub
Log.d(TAG,"isStreaming : YES");
if ( sr != null ) return true;
return false;
}
class mylistener implements RecognitionListener {
#Override
public void onBeginningOfSpeech() {
// TODO Auto-generated method stub
Log.d(TAG, "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] arg0) {
// TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onEvent(int arg0, Bundle arg1) {
// TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReadyForSpeech(Bundle arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onReadyForSpeech");
}
#Override
public void onResults(Bundle arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "Got Results");
ArrayList<String> al = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
text = al.get(0);
for ( int i =0 ; i < al.size(); i++ ) {
Log.d(TAG,"result=" + al.get(i));
}
Intent intent = new Intent(ACTION);
intent.putExtra("Identifier", text);
sendBroadcast(intent);
// startStreaming();
}
#Override
public void onRmsChanged(float arg0) {
// TODO Auto-generated method stub
}
}
}
Here I am getting error java.lang.RuntimeException: SpeechRecognizer should be used only from the application's main thread
Code flow is like this:
ImageButton->onClick()->Fire the service Intent for StreamService.class->onCreate()->onHandleIntent()->calling startStreaming() -> getting error
LogCat Message:
12-13 17:03:24.822 794 7381 E DatabaseUtils: Writing exception to parcel
12-13 17:03:24.822 794 7381 E DatabaseUtils: java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
12-13 17:03:24.822 794 7381 E DatabaseUtils: at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:12754)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:1998)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:574)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at android.content.ContentProvider$Transport.call(ContentProvider.java:256)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:256)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at android.os.Binder.execTransact(Binder.java:351)
12-13 17:03:24.822 794 7381 E DatabaseUtils: at dalvik.system.NativeStart.run(Native Method)
There are times when this particular error is actually misleading, and is caused by other runtime problems.
I documented one such example here - a NullPointerException thrown down deep ended up being reported as this same error, even though it had nothing to do with cross-user permissions.
In my particular case, ProGuard was stripping out a method that I needed, which caused a NullPointerException to be thrown. The stack trace looked like this:
Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
java.lang.NullPointerException
at java.lang.Enum$1.create(Enum.java:43)
at java.lang.Enum$1.create(Enum.java:35)
at libcore.util.BasicLruCache.get(BasicLruCache.java:54)
at java.lang.Enum.getSharedConstants(Enum.java:209)
at java.lang.Enum.valueOf(Enum.java:189)
at com.my.app.package.b.c.a(Unknown Source)
at com.my.app.package.b.a.onCreate(Unknown Source)
at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
at android.support.v4.app.BackStackRecord.run(Unknown Source)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(Unknown Source)
at android.support.v4.app.FragmentManagerImpl$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
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:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
I haven't a clue in the world why Android turned the NullPointerException into the android.permission.INTERACT_ACROSS_USERS_FULL error, but the obvious solution was to tweak the ProGuard configuration so that the method wasn't being stripped.
The method I was calling that wasn't there was the "valueOf" method on an enum. It turns out that there's some interesting reflection involved under the hood (which I go into at the link above), but the solution for me was to add the following to my ProGuard configuration.
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
well the problem is self solution explaining , the first line in your logCat is giving you the solution that, the current thread does not have the permission for executing user task , so just add the following permission in manifest and see if it works out .
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL">
lemme know if I had understood the problem correctly

Categories