Handler is abstract ,cannot be instantiated - java

I am trying to use a Handler in my app. However, when I instantiate it like this:
Handler handler = new Handler();
I get the following error:
Gradle: error: Handler is abstract; cannot be instantiated
And when I check the solutions, it asks me to implement these methods:
Handler handler = new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
I have never used Handlers before and I am using it just to call a method after some delay. To achieve that, I've used:
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
}
}, 100);
But it shows the error:
Gradle: error: cannot find symbol method postDelayed(,int)

It seems you have imported a wrong Handler class
import java.util.logging.Handler;
Change it to
import android.os.Handler;

In Place Of
import java.util.logging.Handler;
add
import android.os.Handler;
also if you use
Handler handler = new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
it will give error that boolean found somthing like error so either use boolean handler = new Handler()...
or simply use (new Handler()){....`

Android SDK auto imports the incorrect one. That's why people have problems.

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ActionActivity extends ActionBarActivity {
final String LOG_TAG = "myLogs";
TextView tvInfo;
Button btnStart;
Handler h;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_activity);
tvInfo = (TextView)findViewById(R.id.tvinfo);
btnStart = (Button)findViewById(R.id.btnstart);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
// update TextView
tvInfo.setText("Закачано файлов: " + msg.what);
if (msg.what == 10) btnStart.setEnabled(true);
};
};
}
public void onclick(View v) {
switch (v.getId()) {
case R.id.btnstart:
btnStart.setEnabled(false);
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 10; i++) {
// some process
downloadFile();
h.sendEmptyMessage(i);
Log.d(LOG_TAG, "i = " + i);
}
}
});
t.start();
break;
case R.id.btnTets:
Log.d(LOG_TAG, "test");
break;
default:
break;
}
}
public void downloadFile(){
try{
TimeUnit.SECONDS.sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
};
}
}

It seems like you have implemented the wrong Handler class
import java.util.logging.Handler;
Change it to
import android.os.Handler;

import android.os.Handler;
this the handler needed for your purpous. Before importing the Handler class please try to import the above.

Related

MutableLiveData doesn't return HashMap object after Retrofit finishes downloading my data and updating the HashMap

So, I recently learned Retrofit and was trying to create an application that uses an API to download Pokemon details. Here's the code for the MainActivity.java class and the MainActivityViewModel.java class. There are other classes there but they are mostly the Model classes and so I haven't mentioned them:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.widget.Toast;
import com.arpansircar.java.pokemonapplication.R;
import com.arpansircar.java.pokemonapplication.viewmodel.MainActivityViewModel;
public class MainActivity extends AppCompatActivity {
private MainActivityViewModel mainActivityViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
}
#Override
protected void onResume() {
super.onResume();
observeRetrofitFailures();
mainActivityViewModel.downloadMainPokemonData();
mainActivityViewModel.returnMainDownloadedData().observe(this, resultsPokemonServiceModels ->
mainActivityViewModel.downloadSelectedPokemonData(resultsPokemonServiceModels));
mainActivityViewModel.returnDownloadedPokemonData().observe(this, map -> {
});
}
private void observeRetrofitFailures() {
mainActivityViewModel.returnMainServiceErrorLiveData().observe(this, s ->
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show());
mainActivityViewModel.returnSelectedPokemonServiceErrorLiveData().observe(this, s ->
Toast.makeText(this, s, Toast.LENGTH_SHORT).show());
}
}
MainActivityViewModel.java
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.arpansircar.java.pokemonapplication.model.GetPokemonId;
import com.arpansircar.java.pokemonapplication.model.MainPokemonServiceModel;
import com.arpansircar.java.pokemonapplication.model.ResultsPokemonServiceModel;
import com.arpansircar.java.pokemonapplication.model.SelectedPokemonModel;
import com.arpansircar.java.pokemonapplication.retrofit.MainPokemonRetrofitInstance;
import com.arpansircar.java.pokemonapplication.retrofit.PokemonServiceInterface;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.internal.EverythingIsNonNull;
public class MainActivityViewModel extends ViewModel {
private MainPokemonServiceModel mainPokemonServiceModel;
private final Map<String, String> pokemonHashMap = new HashMap<>();
private final PokemonServiceInterface mainPokemonServiceInterface = MainPokemonRetrofitInstance.getInstance();
private final MutableLiveData<String> mainServiceErrorLiveData = new MutableLiveData<>();
private final MutableLiveData<String> selectedPokemonServiceErrorLiveData = new MutableLiveData<>();
private final MutableLiveData<Map<String, String>> downloadMainPokemonData = new MutableLiveData<>();
private final MutableLiveData<List<ResultsPokemonServiceModel>> resultsPokemonServiceModelListLiveData = new MutableLiveData<>();
public void downloadMainPokemonData() {
Call<MainPokemonServiceModel> mainPokemonServiceModelCall = mainPokemonServiceInterface.getResultsDataFromService();
mainPokemonServiceModelCall.enqueue(new Callback<MainPokemonServiceModel>() {
#Override
#EverythingIsNonNull
public void onResponse(Call<MainPokemonServiceModel> call, Response<MainPokemonServiceModel> response) {
if (!response.isSuccessful()) {
mainServiceErrorLiveData.postValue(String.valueOf(response.code()));
return;
}
mainPokemonServiceModel = response.body();
resultsPokemonServiceModelListLiveData.postValue(Objects.requireNonNull(mainPokemonServiceModel).resultsPokemonServiceModel);
}
#Override
#EverythingIsNonNull
public void onFailure(Call<MainPokemonServiceModel> call, Throwable t) {
mainServiceErrorLiveData.postValue(t.getMessage());
}
});
}
public void downloadSelectedPokemonData(List<ResultsPokemonServiceModel> resultsPokemonServiceModelList) {
for (ResultsPokemonServiceModel resultsPokemonServiceModel : resultsPokemonServiceModelList) {
String pokemonId = GetPokemonId.getId(resultsPokemonServiceModel.url);
Call<SelectedPokemonModel> selectedPokemonModelCall = MainPokemonRetrofitInstance.getInstance().getSelectedPokemonSprite(pokemonId);
selectedPokemonModelCall.enqueue(new Callback<SelectedPokemonModel>() {
#Override
#EverythingIsNonNull
public void onResponse(Call<SelectedPokemonModel> call, Response<SelectedPokemonModel> response) {
if (!response.isSuccessful()) {
selectedPokemonServiceErrorLiveData.postValue(String.valueOf(response.code()));
return;
}
SelectedPokemonModel selectedPokemonModel = response.body();
String pokemonName = Objects.requireNonNull(selectedPokemonModel).pokemonName;
String pokemonSpriteUrl = selectedPokemonModel.pokemonSpriteModel.spriteUrl;
pokemonHashMap.put(pokemonName, pokemonSpriteUrl);
}
#Override
#EverythingIsNonNull
public void onFailure(Call<SelectedPokemonModel> call, Throwable t) {
selectedPokemonServiceErrorLiveData.postValue(t.getMessage());
}
});
}
downloadMainPokemonData.postValue(pokemonHashMap);
}
public LiveData<Map<String, String>> returnDownloadedPokemonData() {
return downloadMainPokemonData;
}
public LiveData<List<ResultsPokemonServiceModel>> returnMainDownloadedData() {
return resultsPokemonServiceModelListLiveData;
}
public LiveData<String> returnMainServiceErrorLiveData() {
return mainServiceErrorLiveData;
}
public LiveData<String> returnSelectedPokemonServiceErrorLiveData() {
return selectedPokemonServiceErrorLiveData;
}
}
My main problem is at the line downloadMainPokemonData.postValue(pokemonHashMap);. When the download finishes, the MutableLiveData object (for some reason) isn't notified about this, i.e., the HashMap isn't returned back to the MainActivity.
I put some log checks and found the method is indeed being triggered. However, the system exits the method even before the download is completed. The download does get completed, yes. But for some reason, it doesn't return the downloaded HashMap back to the MainActivity. I think that this could be because the enqueue method provided by Retrofit is asynchronous and does all the tasks in a background thread.
Could someone provide any hints as to how I can take care of this? Thanks!
selectedPokemonModelCall.enqueue is async request. downloadMainPokemonData.postValue(pokemonHashMap) called before Response<SelectedPokemonModel> data was handled

How can I open an Activity in the Wikitude Client Tracker Activity?

I have a problem with my first real android project. I need to start a new activity from this one down there, when the client tracker does recognize a target. It would mean the world to me if someone could help me.
The things I already tried, ended always in a disaster... probably because I have no idea what I’m doing (thats also the reason I'm not posting what I have tried)
P.S. I used the Wikitude native Api libary
package com.ia.grafp.maturapp2_2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.ia.grafp.maturapp2_2.rendering.external.CustomSurfaceView;
import com.ia.grafp.maturapp2_2.rendering.external.Driver;
import com.ia.grafp.maturapp2_2.rendering.external.GLRenderer;
import com.wikitude.WikitudeSDK;
import com.wikitude.WikitudeSDKStartupConfiguration;
import com.wikitude.common.camera.CameraSettings;
import com.wikitude.common.rendering.RenderExtension;
import com.wikitude.common.tracking.RecognizedTarget;
import com.wikitude.rendering.ExternalRendering;
import com.wikitude.tracker.ClientTracker;
import com.wikitude.tracker.ClientTrackerEventListener;
import com.wikitude.tracker.Tracker;
/**
*/
public class ArchitectView extends AppCompatActivity implements ClientTrackerEventListener, ExternalRendering {
private static final String TAG = "ArchitectView";
private WikitudeSDK _wikitudeSDK;
private CustomSurfaceView _view;
private Driver _driver;
private GLRenderer _glRenderer;
private boolean tracking;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_wikitudeSDK = new WikitudeSDK(this);
WikitudeSDKStartupConfiguration startupConfiguration
= new WikitudeSDKStartupConfiguration
(WikitudeSDKConstants.WIKITUDE_SDK_KEY,
CameraSettings.CameraPosition.BACK,
CameraSettings.CameraFocusMode.CONTINUOUS);
_wikitudeSDK.onCreate(getApplicationContext(), this, startupConfiguration);
ClientTracker tracker
= _wikitudeSDK.getTrackerManager().create2dClientTracker
("file:///android_asset/magazine.wtc");
tracker.registerTrackerEventListener(this);
}
#Override
protected void onResume() {
super.onResume();
_wikitudeSDK.onResume();
_view.onResume();
_driver.start();
}
#Override
protected void onPause() {
super.onPause();
_wikitudeSDK.onPause();
_view.onPause();
_driver.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
_wikitudeSDK.onDestroy();
}
#Override
public void onRenderExtensionCreated(final RenderExtension renderExtension_) {
_glRenderer = new GLRenderer(renderExtension_);
_view = new CustomSurfaceView(getApplicationContext(), _glRenderer);
_driver = new Driver(_view, 30);
setContentView(_view);
}
#Override
public void onExtendedTrackingQualityUpdate(final Tracker tracker_, final String targetName_, final int oldTrackingQuality_, final int newTrackingQuality_) {
}
#Override
public void onErrorLoading(final ClientTracker clientTracker_, final String errorMessage_) {
Log.v(TAG, "onErrorLoading: " + errorMessage_);
}
#Override
public void onTrackerFinishedLoading(final ClientTracker clientTracker_, final String trackerFilePath_) {
}
#Override
public void onTargetRecognized(final Tracker tracker_, final String targetName_) {
}
#Override
public void onTracking(final Tracker tracker_, final RecognizedTarget recognizedTarget_) {
_glRenderer.setCurrentlyRecognizedTarget(recognizedTarget_);
}
#Override
public void onTargetLost(final Tracker tracker_, final String targetName_) {
_glRenderer.setCurrentlyRecognizedTarget(null);
}
}
#Override
public void onTargetRecognized(final Tracker tracker_, final String targetName_) {
Intent i = new Intent(ArchitectView.this, yourActivityClass.class);
startactivity(i);
}
I don't know if this answer your question, but that is the way of starting a new activity.

Google recognizer and pocketsphinx in two different classes, how to loop them?

Yesterday i ask a simplified question of my problem, but think its too simplified.
What my programm should do, is to hear a keyword and when he hear it, he should listen to what i said. (like if you told to siri or google now, by saying siri or ok google).
I'm using pocketsphinx for the keyword and the google speechrecognizer for the longer parts. It works, but only for one time. The pocketsphinx is in the MainActivity and the google recognizer is in an extra class (Jarvis).
The programm starts with the pocketsphinx listener, when he hear the KEYPHRASE, he starts the google listener by calling jarvis.startListener() (by the next()-method) and there is the problem, when the googlelistener is done, i dont come back from the Jarvis-class to the MainActivity to call the next() method again.
(when the google recognizer is done, the last things he do is in the onResult() in Jarvis-class, but from there i cant call the next()-method from MainActivity-class)
MainActivity
package com.example.superuser.jarvis;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.SpeechRecognizer;
import edu.cmu.pocketsphinx.SpeechRecognizerSetup;
import static android.widget.Toast.makeText;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
public class MainActivity extends Activity implements edu.cmu.pocketsphinx.RecognitionListener {
private String LOG_TAG = "Jarvis_hears_anything";
private TextView tv;
private Jarvis jarvis;
private boolean wannahearjarvis = false;
/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "jarvis";
private edu.cmu.pocketsphinx.SpeechRecognizer recognizer;
//private HashMap<String, Integer> captions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.b1);
tv = (TextView) findViewById(R.id.tv1);
//captions = new HashMap<String, Integer>();
//captions.put(KWS_SEARCH, R.string.kws_caption);
jarvis = new Jarvis(getApplicationContext());
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(MainActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.tv1))
.setText("Failed to init recognizer " + result);
} else {
//switchSearch(KWS_SEARCH);
recognizer.startListening(KWS_SEARCH);
}
}
}.execute();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "geht", Toast.LENGTH_SHORT).show();
}
});
}
public void next(){
if (wannahearjarvis){
recognizer.startListening(KWS_SEARCH);
wannahearjarvis = false;
}
else{
jarvis.startListening();
wannahearjarvis = true;
}
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
if (text.equals(KEYPHRASE)){
tv.append("found");
recognizer.stop();
//switchSearch(KWS_SEARCH);
}
else {
//((TextView) findViewById(R.id.tv1)).append(text+"PR");
//Log.i(LOG_TAG, text+"PR");
}
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
//((TextView) findViewById(R.id.tv1)).setText("");
((TextView) findViewById(R.id.tv1)).append("oR");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
next();
}
#Override
public void onBeginningOfSpeech() {
}
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
if (!recognizer.getSearchName().equals(KWS_SEARCH)){
tv.append("fuck");
}
//switchSearch(KWS_SEARCH);
}
/*private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
//String caption = getResources().getString(captions.get(searchName));
//((TextView) findViewById(R.id.tv1)).setText(caption);
//((TextView) findViewById(R.id.tv1)).append(caption);
}*/
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// To disable logging of raw audio comment out this call (takes a lot of space on the device)
.setRawLogDir(assetsDir)
// Threshold to tune for keyphrase to balance between false alarms and misses
.setKeywordThreshold(1e-20f)
// Use context-independent phonetic search, context-dependent is too slow for mobile
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
}
#Override
public void onError(Exception error) {
((TextView) findViewById(R.id.tv1)).setText(error.getMessage());
}
#Override
public void onTimeout() {
//switchSearch(KWS_SEARCH);
}
}
Jarvis
package com.example.superuser.jarvis;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Toast;
import java.util.ArrayList;
public class Jarvis implements RecognitionListener{
private AudioManager audiom;
private SpeechRecognizer speech;
private Intent recogIntent;
private Toast m;
private Context c;
private String text;
public Jarvis(Context context){
speech = SpeechRecognizer.createSpeechRecognizer(context);
speech.setRecognitionListener(this);
recogIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recogIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "de");
//recogIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.getPackageName());
m = new Toast(context);
c=context;
}
public void startListening(){
speech.startListening(recogIntent);
}
public void destroy(){
speech.stopListening();
speech.cancel();
speech.destroy();
}
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Toast.makeText(c, matches.get(0), Toast.LENGTH_LONG).show();
speech.cancel();
//tried
//MainActivity m = new MainActivity();
//m.next();
//but got a Nullpointer Exception
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
You can store reference to the main activity in Jarvis object in a field:
class Jarvis {
....
private MainActivity m;
....
public Jarvis(MainActivity m) {
this.m = m;
}
....
public void onResults(Bundle results) {
....
m.next();
}
You can also send intents to the main activity as described here. This might be overkill in your case though.

Created a simple timer on Android, doesn't work as expected

I'm trying display a timer on my app with a Thread calculating the elapsed time and a Handler to modify the view.
I know that Android doesn't allow other threads that the UI Thread to modify a view, so I use the Handler to do this.
But it seems that it was not effective, because I still have the "android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."
What should I do ?
(Oh, and the code is bellow if this might help)
package com.hangin.arround.emergency;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
public class MainActivity extends SherlockActivity {
private static final String TAG = "MainActivity";
private TextView elapsedTime;
private Button startButton;
private Button stopButton;
private boolean shouldContinue = false;
private Handler mHandler;
private Runnable runnable;
private static final int MESSAGE_ELAPSED_TIME = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Creating the action bar, initializing my views and stuff
// Creating the Handler
mHandler = new Handler() {
#SuppressLint("SimpleDateFormat")
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what) {
case MESSAGE_ELAPSED_TIME :
// Converting from milliseconds to a String
DateFormat formatter = new SimpleDateFormat("hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(msg.arg1);
String elapsedTimeString = formatter.format(calendar.getTime());
elapsedTime.setText(elapsedTimeString);
break;
default:
break;
}
}
};
// Creating the Runnable
runnable = new Runnable(){
#Override
public void run() {
int startTime, actualTime;
startTime = (int) System.currentTimeMillis();
Log.d(TAG, "startTime = " + startTime);
while(shouldContinue) {
// Calcul du temps écoulé
actualTime = (int)System.currentTimeMillis() - startTime;
Log.d(TAG, "actualTime = " + actualTime);
// Creating the message sent to the Handler
Message elapsedTimeMessage = new Message();
elapsedTimeMessage.what = MESSAGE_ELAPSED_TIME;
elapsedTimeMessage.arg1 = (int) actualTime;
// Sending the message
mHandler.handleMessage(elapsedTimeMessage);
}
}
};
// Adding the OnClickListeners on startButton and stopButton
startButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// Launching Thread
(new Thread(runnable)).start();
shouldContinue = true;
}
});
stopButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// Stopping the thread
shouldContinue = false;
}
});
}
}
Change
Message elapsedTimeMessage = new Message();
elapsedTimeMessage.what = MESSAGE_ELAPSED_TIME;
elapsedTimeMessage.arg1 = (int) actualTime;
// Sending the message
mHandler.handleMessage(elapsedTimeMessage);
to
Message.obtain(mHandler, MESSAGE_ELAPSED_TIME, (int) actualTime, 0).sendToTarget();
From the API docs, it seems handleMessage is something called later in the handling process and shouldn't be invoked directly.
In order to have the message processed on the thread where the handler was created, you need to call sendMessage
You should change mHandler.handleMessage(elapsedTimeMessage);
with mHandler.sendMessage(elapsedTimeMessage);

How to loop sound in android

When press button first sound active. Then press that button again it will stop and second sound active My code is OK?
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt=(TextView)findViewById(R.id.txt);
bt1 = (Button)findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while(showRandom){
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp.setLooping(true);
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
mp2.setLooping(true);
mp2.start();
}catch(Exception ex){
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Add the line:
mp.setLooping(true);
Then set false when you want to stop it looping.
Your code has several errors. Typos, cases,
ex.: Medaiplayer should be MediaPlayer
This alone would be enough to cause the error. Also, declaring your variables outside the method is a good idea.

Categories