Android Studio 3.2.1: Silent Mode Toggle app crashes when clicked even though no error in code - android-studio

I'm just starting to learn coding for Android App by following the book Android App Development for Dummies to create the Silent Mode Toggle App.
Everything seems fine in the code (no error except for warning that:
"Casting 'findViewById(R.id.phone_icon)' to 'ImageView' is redundant.
This inspection reports unnecessary cast expressions."
I have read through a similar problem here (Application Crashes - Silent Mode Toggle - Android for Dummies) and it says to try:
1) Change "extends ActionBarActivity" to just "extends Activity" and import - mine is already as such.
2) delete or comment the 'if' in the onCreate method out - mine don't have this section.
3) change the parameter of the setContentView to: R.layout.fragment_main - not very sure what this means but don't seem to be relevant to my code? (his codes and mine are slightly different)
MainActivity.java Code
package com.dummies.silentmodetoggle;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.dummies.silentmodetoggle.util.RingerHelper;
public class MainActivity extends Activity {
AudioManager audioManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
setContentView(R.layout.activity_main);
FrameLayout contentView =
(FrameLayout) findViewById(R.id.content);
contentView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RingerHelper.performToggle(audioManager);
updateUi();
}
});
}
private void updateUi() {
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
int phoneImage = RingerHelper.isPhoneSilent(audioManager)
? R.mipmap.ringer_off
: R.mipmap.ringer_on;
imageView.setImageResource(phoneImage);
}
#Override
protected void onResume(){
super.onResume();
// Update our UI in case anything has changed.
updateUi();
}
}
RingerHelper.java
The book says to create a java file at: "src/main/java/com/dummies/silentmodetoggle/util/RingerHelper.java" but did not state how. Since I do not have a util folder so I'd created a package (New>Package) at "src/main/java/com.dummies.silentmodetoggle" and added the RingerHelper java file in the util folder. Note sure if this is the problem? The code is as below:
package com.dummies.silentmodetoggle.util;
import android.media.AudioManager;
public class RingerHelper {
// private to prevent users from creating a RingerHelper object
private RingerHelper(){}
/* Toggles the phone's silent mode */
public static void performToggle(AudioManager audioManager) {
// If the phone is currently silent, then unsilence it. If
// it's currently normal, then silence it.
audioManager.setRingerMode(
isPhoneSilent(audioManager)
? AudioManager.RINGER_MODE_NORMAL
: AudioManager.RINGER_MODE_SILENT);
}
/* Returns whether the phone is currently in silent mode. */
public static boolean isPhoneSilent(AudioManager audioManager){
return audioManager.getRingerMode()
== AudioManager.RINGER_MODE_SILENT;
}
}
Error from LogCat when I clicked the button on app
2018-12-01 22:11:44.029 30122-30122/com.dummies.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dummies.silentmodetoggle, PID: 30122
java.lang.SecurityException: Not allowed to change Do Not Disturb state
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
at com.dummies.silentmodetoggle.util.RingerHelper.performToggle(RingerHelper.java:13)
at com.dummies.silentmodetoggle.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
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: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)
2018-12-01 22:11:44.672 1315-1315/? E/EGL_emulation: tid 1315: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
Otherwise the app seems to work fine, ie, when I click on the volume button of the device itself to silent, the app image will change to silent and vice versa. It just crashes when I try to click on the image of the app itself.
I really have no idea what's going on. Please help. Thanks very much!

You need to add permissions for Do Not Disturb State. I was facing the same issue and I added the following lines to my Main_Activity.java code in onCreate method and it works fine Now:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}

Related

TarsosDSP in Android Studio

This is my first post on SO and I am trying to combine my music skills with computer science.
I am using Android studio 3.1.2 with gradle 4.5, Nexus 5X, API 25, Android 7.1.1, Windows 7.
I followed very careful these instructions:
Create a project called Pitchbender
Download the .jar of TarsosDSP and included in
C:\Users\Carlos\AndroidStudioProjects\Pitchbender\app\libs\TarsosDSP-Android-latest
I checked the build.gradle of my project:
dependencies { implementation fileTree(dir: ‘libs’, include: [‘*.jar’]) }
In my project, I have the following imports automatically done by Android Studio:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.io.android.AudioDispatcherFactory
import be.tarsos.dsp.pitch.PitchDetectionHandler
import be.tarsos.dsp.pitch.PitchDetectionResult
import be.tarsos.dsp.pitch.PitchProcessor
import kotlinx.android.synthetic.main.activity_main.*
import be.tarsos.dsp.pitch.PitchProcessor.PitchEstimationAlgorithm
import be.tarsos.dsp.AudioProcessor
import android.widget.TextView
import be.tarsos.dsp.AudioDispatcher
I have this permission in my manifest file
uses-permission android:name=”android.permission.RECORD_AUDIO”
Android Studio gives the option to convert to Kotlin the first line of the following code:
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
If I respond to “No” to the Kotlin conversion, I have the following compilation error:
Clasifier “AudioDispatcher” does not have any companion object, and thus must be initialized here.
What can I do?
If I respond “Yes” to the Kotlin conversion question, that statement is converted to
val dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0)
and then, when I run this program, Android informs me that there is an error and closes my project and keeps closing my project. What to do?
Please help to run at least that first instruction of the complete code:
PitchDetectionHandler pdh = new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult res, AudioEvent e){
final float pitchInHz = res.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
processPitch(pitchInHz);
}
});
}
};
AudioProcessor pitchProcessor = new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(pitchProcessor);
Thread audioThread = new Thread(dispatcher, "Audio Thread");
audioThread.start();
Question:
Do you have any simple project in Android Studio, so that I can see what my errors are?
I had a similar problem when I tried to run this example and my solution (Sep. 2019) was to add a runtime confirmation of the record permission. I'm not sure if it's the same case, buuuut
Here is my code to it:
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}

Lwuit touch screen strange behaviour

I am making an application using LWUIT.
There is a form
There is a list embedded on the form.
The list has 5 elements.
Initially, when I first load the app, if I choose the 1st element, 2nd gets chosen; when I choose the second the 3rd gets chose and and so on (Weird!)
I am not able to click any button on the screen either
next what I do is, shift to a different from using arrow keys (of the keyboard... I am running the app on a simulator btw)
Then I come back to the first form and now everything works as expected(no weird behaviour).
What could be the issue?
I am using Sun Java Micro Edition SDK 3.0 (default touch screen for testing)
My code is:
List dummy = new List();
dummy.addItem("wewerwer");
dummy.addItem("wewerdswer");
dummy.addItem("wewqweerwer");
dummy.addItem("dscxwewerwer");
dummy.addItem("jhgwewerwer");
mainListForm.setLayout(new BorderLayout());
mainListForm.addComponent(BorderLayout.CENTER,dummy);
mainListForm.show();
What could possible be going wrong here?
UPDATE 1
I think there is a bug here. I have attached the complete code below along with the screen shot
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class Demo extends MIDlet implements ActionListener {
private Form mForm;
List abc;
public void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/Test.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0])
);
} catch (Exception e){
System.out.println(e.toString());
}
if (mForm == null) {
Button click = new Button("Press me!");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("I have been pressed");
}
});
abc = new List();
abc.addItem("Str1");
abc.addItem("Str2");
abc.addItem("Str3");
abc.addItem("Str4");
abc.addItem("Str5");
abc.addItem("Str6");
Form f = new Form("Hello, LWUIT!");
abc.addActionListener(this);
f.addComponent(abc);
Command exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.addCommandListener(this);
f.addComponent(click);
f.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
System.out.println(abc.getSelectedIndex());
}
}
So now when I click on 'Str1' of the list Str2 gets selected and so on.
IDE: Netbeans
Emulator: Default Touch screen phone
On the action event set the list to active again after the event by invoking setHandlesInput(true)
OK....so this is how you resolve it.
After the form is displayed remove the list from the form and again add it to the form and then repaint the form.
Earlier Code
1) form.addComponenet(BorderLayout.center,list);
2) form.show();
Word Around for the problem
1)form.addComponenet(BorderLayout.center,list);
2)form.show();
3)form.setScrollable(false);
I know its kind of strange, but this way the list index selection works smooth for touch screen phones.

J2ME Uncaught Exception

I plan to start my first lesson in j2me, and I download a simple book and I try my first program.
When I take a second step to add commands, I face an error message which is:
uncaught exception java/lang/noclassdeffounderror: readfile.
So, would you please help me to understand this message? and how to solve it?
Please find my code below.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ReadFile extends MIDlet implements CommandListener
{
private Form form1;
private Command Ok, Quit;
private Display display;
private TextField text1;
public void startApp()
{
form1 = new Form( "TA_Pog" );
Ok = new Command("Ok", Command.OK, 1);
Quit = new Command("Quit", Command.EXIT, 2);
form1.setCommandListener(this);
form1.addCommand(Ok);
form1.addCommand(Quit);
text1 = new TextField("Put Your Name :","His Name : " , 32, TextField.URL );
form1.append(text1);
display = Display.getDisplay(this);
display.setCurrent(form1);
}
public void commandAction(Command c , Displayable d)
{
if (c == Ok)
{
Alert a = new Alert("Alert","This Alert from Ok Button", null, AlertType.ALARM);
a.setTimeout (3000);
display.setCurrent(a,this.form1);
}
else
{
this.notifyDestroyed();
}
}
public void pauseApp() {}
public void destroyApp( boolean bool ) {}
}
Note: the code above is taken exactly from a book.
Thanks in advance
Besr regards
uncaught exception java/lang/noclassdeffounderror: readfile.
I somehow doubt the message is exactly as you describe it. Does it look more like below?
uncaught exception java/lang/NoClassDefFoundError: ReadFile
Please keep in mind in Java it matters much whether you use lower or upper case letters. As long as you don't pay attention to stuff like that, you are likely be getting a lot of problems like that.
Now, take a closer look at your class name:
public class ReadFile //...
The exception you are getting most likely says that Java machine can't find the class you try to use. There is something wrong with your build/compilation.
I run your code. It's running good. I think you have to clean and build your project. Firstly go to project properties and then go to Application Descriptor and click on Midlet tab, and select your midlet and press ok then clean build, run it.

LWUIT assistance

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class Ruwwa extends javax.microedition.midlet.MIDlet
implements ActionListener{
Form f;
Button mybutton1;
Button mybutton2;
Command exit;
Command ok;
public void startApp() {
Display.init(this);
f = new Form();
try {
Resources r = Resources.open("/mairuwa.res");
UIManager.getInstance().setThemeProps(r.getTheme("Mairuwa Theme"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
mybutton1=new Button("Report A Problem");
mybutton2=new Button("Request Info");
f.setLayout(new BorderLayout());
f.addComponent(BorderLayout.CENTER, new Label("The Mairuwa Portal"));
ok = new Command("OK");
exit = new Command("Exit");
f.addCommand(ok);
f.addCommand(exit);
f.addCommandListener(this);
f.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
notifyDestroyed();
}
}
I would like to add another label under the "The Mairuwa Portal" and also place two buttons ("Report A Problem","Request Information") beneath this as well. An illustration of what I am describing is
label: The Mairuwa Portal
then another label beneath it: I want to:
Then two buttons beneath this Button:Report Problem Button: Request Information
I have been able to add OK and EXIT button to the project,but this above buttons I talked about should as I described.
These buttons will carry functionality. I hope this can be done in LWUIT.
You need to include all JSR's when compiling a LWUIT application in the IDE. LWUIT doesn't require them all to run but requires 184, 226, MMAPI & file connector to compile. This is causing your verification error.
I would recommend developing with the Sun/Oracle simulators and using the more device like emulators for QA.
The exception you got means your application was built incorrectly, see that Ruwwa is in the jar file that was produced by your build. If not fix your build.

Problem in Finding Resource File in Android

Hi i am using Google Maps in a code
This is the code written in the activity file
package com.hellomaps;
import android.app.Activity;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
public class HelloGoogleMaps extends MapActivity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
}
Now in the line setContentView(R.layout.main) it does not recognse "R" and hence mapview cannot be used in the activity as it doesnot recognse the view
I know android.R and com.google.R should not be imported.
i am stuck here .. kindly help..!!
Thanks in Advance
R file is generated when you compile your project. So if you are using eclipse just press ctrl+b and R file should appear in gen folder in your project.
If you checked out project from SVN or some other version control you could have problem with R file. If you do, create new android project in eclipse then copy/paste source and resources from checked out project to new created one and build. Hope this helps.

Resources