Im writing my project app in Android Studio. The app is connected to microcontroller and send logic 1 on button Click to get data string from microcontroller all by BT. I have question for you how can i automatize it to send this logic 1 with some delay. I tried some methods but them dont work properly. The app stops
//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendButton.performClick();
}
},20000);
LogCat:
2020-03-27 18:44:10.913 11754-11754/com.example.bt_serial_test_1_0 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bt_serial_test_1_0, PID: 11754
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:5645)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.IllegalArgumentException: Invalid message body
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:337)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:325)
at com.example.bt_serial_test_1_0.MainActivity.sendSms(MainActivity.java:239)
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
this method is in onCreate. Can someone please help me to resolve this problem
Here is a Handler example for a repeating task.
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
You can modify it for your case like that
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
handler().postDelayed(r,1000);
}
catch (IOException ex) { }
}
});
final Runnable r = new Runnable()
{
public void run()
{
sendButton.performClick();
}
};
Related
I appreciate your help with a problem with the ratingbar, I want to show the value of the ratingbar in a Toast when pressing a button, therefore each time you press the button, the value of the ratingbar should be displayed, however at the time pressing the button closes the application and debugging I get the following error.
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'float android.widget.RatingBar.getRating()' on a null object
reference at
com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
"
#Override
protected void onCreate(Bundle savedInstanceState) {
commentsFra = new ComentariosFragment();
navhost = new HomeFragment();
thanks = new ThanksFragment();
}
public void onClick(View view){
ratingBar = findViewById(R.id.ratingBarOne);
transaction = getSupportFragmentManager().beginTransaction();
switch (view.getId()){
case R.id.fin_encuesta: {
transaction.replace(R.id.nav_host_fragment, thanks);
transaction.addToBackStack(null);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override public void run() {
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, navhost);
transaction.addToBackStack(null); transaction.commit();
}
};
handler.postDelayed(runnable,7000);
comments = findViewById(R.id.comments_dialog);
comments.setText(""); float rating; rating = ratingBar.getRating();
//Linea 114 Toast.makeText(this, ":" + rating, Toast.LENGTH_SHORT).show();
break;
}
transaction.commit();
}
}
This is the error that it generates:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.org.notas.asembisencuesta, PID: 7682
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:414)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(.java:409)
at android.view.View.performClick(View.java:7146)
at android.view.View.performClickInternal(View.java:7119)
at android.view.View.access$3500(View.java:803)
at android.view.View$(View.java:27533)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.org.notas.asembisencuesta.MainActivity.onClick(MainActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
i`m new to android development and i wanted to make an audio recorder, when i want to access the method for starting of recording from my main activity it always gives an error. Below is my code. I hope you can help me:
This is the mainActivity:
public class MainActivity extends AppCompatActivity {
Boolean isRecording = false;
Record record;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
record = new Record();
}
public void recordAudio(View view){
if(!isRecording)
{
isRecording = true;
record.startRecording();
}
else{
isRecording = false;
record.stopRecording();
}
}
Below is the subclass:
public class Record extends MainActivity {
public void startRecording() {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, getBufferSize());
int i = recorder.getState();
if (i == 1)
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
#Override
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
buttonRecord.setText(R.string.button_stop_record);
}
Thanks for your help!
Here is the exact error code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com, PID: 31778
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:6199)
at android.widget.TextView.performClick(TextView.java:11090)
at android.view.View$PerformClick.run(View.java:23647)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6199)
at android.widget.TextView.performClick(TextView.java:11090)
at android.view.View$PerformClick.run(View.java:23647)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.IllegalArgumentException: Invalid audio buffer size.
at android.media.AudioRecord.audioBuffSizeCheck(AudioRecord.java:751)
at android.media.AudioRecord.<init>(AudioRecord.java:385)
at android.media.AudioRecord.<init>(AudioRecord.java:289)
at com.Record.startRecording(Record.java:63)
at com.MainActivity.recordAudio(MainActivity.java:35)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6199)
at android.widget.TextView.performClick(TextView.java:11090)
at android.view.View$PerformClick.run(View.java:23647)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
In Android Activity is usually stared by the user code but the object creation is not the responsibility of the user, rather it is the Android framework which does this.
Your case has Record extends MainActivity and MainActivity being an Activity makes Record also an Activity. So you need to start it either make it the launcher main activity in manifest file or use startActivity() (or startActivityForResult()).
The code record = new Record(); Here you create the instance of Record yourself that too in the parent class MainActivity. This is not a very good idea from both programming in Android and Java Object oriented point of view. (Hence you can but should not choose to do so)
Refer one answer from another post
https://stackoverflow.com/a/14956056/504133
I suggest you to make simple Android application with two or three activities, with each having simple UI layout. You can learn there and then apply the concepts for more complex application as AudioRecorder.
The error says com.Record.startRecording(Record.java:63) is the cause of: java.lang.IllegalArgumentException: Invalid audio buffer size.
Please call AudioRecord.getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) to make sure your buffer size is big enough before you instantiate a new AudioRecord. Just like it says in the documentation.
Please note that you should also check if your AudioRecord instance was initialized correctly by calling getState() (and checking that it returns STATE_INITIALIZED).
This is my first time asking questions here.
I am trying to make my TextView text color changing to a random color time by time when the application is started.
This is what I tried but it made my app crash.
TextView txtLucky;
Random rd;
int r = 0, g = 0, b = 0;
Thread stopper = new Thread();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLucky = findViewById(R.id.txtLucky);
while (true){
try {
wait(2000);
rd = new Random();
int rdcolor = Color.argb(255, rd.nextInt(256), rd.nextInt(256), rd.nextInt(256));
txtLucky.setTextColor(rdcolor);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopper.start();
}
}
Error Log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.threadstopper, PID: 14708
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.max.threadstopper/com.example.max.threadstopper.MainActivity}: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:422)
at com.example.max.threadstopper.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Try this
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
rd = new Random();
final int rdcolor = Color.argb(255, rd.nextInt(256), rd.nextInt(256), rd.nextInt(256));
runOnUiThread(new Runnable() {
#Override
public void run() {
txtLucky.setTextColor(rdcolor);
}
});
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
2000);
Text color change code put in runOnUiThread. because you already start one Thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
txtLucky.setTextColor(rdcolor);
}
});
everytime I'm trying to start my app it crashes immediately on this part of code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isOnline()) {
// textViewTemperature.setText(Data);
Toast.makeText(getApplicationContext(), "Cannot connect to network, data will be restore from file with last downloaded data...", Toast.LENGTH_LONG).show();
} else {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
weather = parser.getWeatherForLocation(editText.getText() + "");
runOnUiThread(new Runnable() {
#Override
public void run() {
editText.setText(weather.getCity() + ", " + weather.getCountry()); }
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
}
});
This is the full logcat from this error:
12-29 10:06:36.376 3524-3524/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.piotr.pogoda, PID: 3524
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.piotr.pogoda/com.example.piotr.pogoda.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.piotr.pogoda.MainActivity.onCreate(MainActivity.java:136)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
I can see the error but I don't get what does it mean that I'm trying to use a method on a null object reference. The button does not exist or what?
Initialize your button, either by findViewById(R.id.btn) or programatically button = new Button(getApplicationContext())
From your crash log, button view is null. May be your view initialization has some issues. Please check the code.
You need to initialize the button
Button btn = (Button) findViewById()
I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?
call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});