null pointer exception at getRingerMode() - java

I wrote this app where users can toggle silent mode by clicking on an image button:
package p.a;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
View.OnClickListener onClickListener = new View.OnClickListener(){
#Override
public void onClick(View view) {
mode.toggle(audioManager);
update();
}
};
imageView.setOnClickListener(onClickListener);
}
public void update(){
int mod=mode.phonesilent(audioManager)?
R.drawable.ringer_off:
R.drawable.ringer_on;
}
}
Here's the mode class:
package p.a;
import android.media.AudioManager;
/**
* Created by root on 9/19/17.
*/
public class mode {
public static boolean phonesilent(AudioManager audioManager){
return audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT;
}
public static void toggle(AudioManager audioManager){
int mode = phonesilent(audioManager)?
AudioManager.RINGER_MODE_NORMAL:
AudioManager.RINGER_MODE_SILENT;
}
}
The app can be initialized normally, but when I click on the image icon, it crashes and produces the error message in the title.
Here's the logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.AudioManager.getRingerMode()' on a null object reference
at p.a.mode.phonesilent(mode.java:11)
at p.a.MainActivity.update(MainActivity.java:29)
at p.a.MainActivity$1.onClick(MainActivity.java:22)

Firstly create a Mode Object like this :
Mode mode = new Mode();

You can do it as Vamshi Krishna says, it's totally a good answer for this problem, but if you don't want to instantiate it for some reason you could change "Mode class" to a "Mode static class" as follows:
package p.a;
import android.media.AudioManager;
/**
* Created by root on 9/19/17.
*/
public static class mode {
public static boolean phonesilent(AudioManager audioManager){
return audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT;
}
public static void toggle(AudioManager audioManager){
int mode = phonesilent(audioManager)?
AudioManager.RINGER_MODE_NORMAL:
AudioManager.RINGER_MODE_SILENT;
}
}
Hope it helps!

Related

Java- hot to have just 1 button to toggle back and forth instead of two buttons?

I have 1 button for changing an image and a text.
I wanted to make that same button so that if I click AGAIN, it would change back to the original image and the text. However, 'TextView' and 'ImageView' in Java code would tell me, I have already defined. Therefore, I guess I can't re-define them within 1 button.
I ended up creating 2 buttons: 1 to change and 2nd one to return back. How can I just have one button to change and return images and text? HELP!
package com.example.android.cookies;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Called when the cookie should be eaten.
*/
public void eatCookie(View view) {
// TODO: Find a reference to the ImageView in the layout. Change the image.
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.after_cookie);
// TODO: Find a reference to the TextView in the layout. Change the text.
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("Im so full");
}
public void returnCookie(View view) {
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.before_cookie);
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("I'm so hungry");
}
}
]2
I have written a well maintained code for you. You can save current state.
I don't recommend boolean. Because if you take int you can save more states in future, whereas in boolean you can save only two states- true or false.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
ImageView imageView;
TextView textView;
Button button;
final int STATE_HUNGRY = 1;
final int STATE_FULL = 2;
int currentState = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.android_cookie_image_view);
textView = (TextView) findViewById(R.id.status_text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentState) {
case STATE_FULL:
returnCookie();
break;
case STATE_HUNGRY:
eatCookie();
break;
default: // used when there is no state available
eatCookie();
}
}
});
}
public void eatCookie() {
currentState = STATE_FULL;
imageView.setImageResource(R.drawable.after_cookie);
textView.setText("Im so full");
}
public void returnCookie() {
currentState = STATE_HUNGRY;
imageView.setImageResource(R.drawable.before_cookie);
textView.setText("I'm so hungry");
}
}
Have you tried using a static variable to keep track of the currently displayed image? Static means it will maintain its state between function calls. Then toggle it each time the function is called. The initial declaration will only be called once.
static Boolean eaten = false;

How can make a relation between 2 class in one program?(android)

I must write a program with android which can find other ssid's and show them. I desinged it with 2 xml pages. I create an imagebutton in page2 and want to make a relation between imagebutton and searching method. It means i want to click on imagebutton and seaching method begin it's work and search ssid's and show them...
My problem is, I download my search method and because of that i can not recognize which method i must call on my setonclick method that i write for an imagebutton in second page? I try to create another class seperately for search method and call it from the second class of page2.
but i dont know how can i make a relation between these 2 calss(i mean the second and third class). Or i must write the method of searching and on click of my imagebutton in one class?
Thanks for your suggestion.this is the code that i was copy:
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class wifiScan extends Activity {
private class WifiReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = wifi.getScanResults();
Date tempDate=new Date();
String info=testNumber+" "+(tempDate.getTime()-testDate.
getTime()) +" "+results.size();
Log.i("wifiScan", info);
wifiText.setText(info);
testNumber++;
testDate=new Date();
wifi.startScan();
}
}
private TextView wifiText;
private WifiManager wifi;
private WifiReceiver receiver;
private Date testDate;
private static int testNumber=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testNumber=0;
wifiText = (TextView) findViewById(R.id.wifiText);
receiver=new WifiReceiver();
registerReceiver(receiver, new IntentFilte
(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){
wifi.setWifiEnabled(true);
}
startScan();
}
#Override
public void onStop(){
super.onStop();
finish();
}
public void startScan(){
testDate=new Date();
wifi.startScan();
}
}
you_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(this, wifiScan.class);
getApplicationContext().startActivity(i);
}
});

Phonegap: calling a java function from Javascript

I want to call one of my Java functions in Javascript and get its result. In order to do that I followed this tutorial and this question. I followed them step by step and I still get this error
Cannot call method 'showKeyBoard' of undefined
Here is my java class:
package keyboard;
import org.apache.cordova.DroidGap;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
public class KeyBoard {
private WebView mAppView;
private DroidGap mGap;
public KeyBoard(DroidGap gap, WebView view) {
mAppView = view;
mGap = gap;
}
public void showKeyBoard() {
InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
mgr.showSoftInput(mAppView, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(mAppView, 0);
}
public void hideKeyBoard() {
InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mAppView.getWindowToken(), 0);
}
}
Here is my Main class:
package com.example.helloworld;
import keyboard.KeyBoard;
import android.os.Bundle;
import org.apache.cordova.*;
import android.view.Menu;
import QR.*;
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
KeyBoard keyboard = new KeyBoard(this, appView);
appView.addJavascriptInterface(keyboard, "KeyBoard");
super.loadUrl("file:///android_asset/www/index.html");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And I call it in Javascript like this:
(function(){
window.KeyBoard.showKeyBoard();
})();
Is there anything that I haven't done or am missing? As I said I get this error:
Cannot call method 'showKeyBoard' of undefined
I recommend that you write a PhoneGap plugin instead of trying to roll your own method. We've already gone through all the pain points of the JavaScript to Java communication. Use what we've already written and you won't run into the Android bugs that we've already smoothed over in the past 3 years.
http://docs.phonegap.com/en/2.1.0/guide_plugin-development_index.md.html#Plugin%20Development%20Guide
In phonegap i recommend you using a custom plugin do this
but still if you want to make a direct call to Java see this example to get a general idea
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("loadUrlTimeoutValue", 70000);
super.loadUrl("file:///android_asset/www/index.html");
super.appView.addJavascriptInterface(new Bridge(), "b");
}
}
class Bridge {
#JavascriptInterface
public String a()
{
Log.i("Bridge","This is from js");
return "This is a message";
}
}
in javascript
setTimeout(function(){
alert(b.a());
}, 1000);
#JavascriptInterface annotation is required in you code to make this work .
package keyboard;
import org.apache.cordova.DroidGap;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
public class KeyBoard {
private WebView mAppView;
private DroidGap mGap;
public KeyBoard(DroidGap gap, WebView view) {
mAppView = view;
mGap = gap;
}
/*make it visible in bridge*/
#JavascriptInterface
public void showKeyBoard() {
InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
mgr.showSoftInput(mAppView, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(mAppView, 0);
}
/*make it visible in bridge*/
#JavascriptInterface
public void hideKeyBoard() {
InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(mAppView.getWindowToken(), 0);
}
}
And in Javascript call it like this:
(function(){
KeyBoard.showKeyBoard();
})();
I'm struggling with JavascriptInterface too. The reason why you cant call showKeyboard is IMHO you should call window.showKeyBoard() instead of window.Keyboard.showKeyBoard().

mCamera cannot be resolved to a variable (Android, Eclipse)

I am very new to Android development. I am following Google's Android "classes" and am receiving an error for this code in Eclipse:
package com.feistie.myfirstapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
//does not behave as a buutton
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
#Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Release the Camera because we don't need it when paused
// and other activities might need to use it.
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage (View view) {
// Do Something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
There is an error for each of these lines:
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
The error for the first and third lines says "mCamera cannot be resolved to a variable." The error for the second line just says "mCamera cannot be resolved."
If you need more information please let me know.
Thanks!
You need to declare mCamera before you can reference it:
public class MainActivity extends Activity {
Camera mCamera;
And then you need to initialize it, probably in onResume()
#Override
protected void onResume() {
super.onResume();
mCamera = Camera.open()
}
Make sure you added the appropriate permission that you manifest:
<uses-permission android:name="android.permission.CAMERA" />
Addition
You need to declare_every_ variable before you try use it in Java. I don't see where you declare mTextView either.
public class MainActivity extends Activity {
Camera mCamera;
TextView mTextView;

Android/Java: Starting activity from class method

I'm trying to start a new activity from a non-activity class.
From the main menu:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Menu extends Activity {
Button start, options;
GameLoop Game = new GameLoop();
#Override
public void onCreate(Bundle mainStart) {
super.onCreate(mainStart);
setContentView(R.layout.menu);
start = (Button) findViewById(R.id.bStart);
options = (Button) findViewById(R.id.bOptions);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openStart = new Intent(Menu.this, Game.class);
startActivity(openStart);
}
});
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context mContext = null; //Error called for mContext to be initialized so just tried setting to null. This is most likely the error cause it would make more sense for it to be equal to "getContext()" or something like that
Game.Start(mContext);//Here
}
});
}
}
I'm trying to open an activity from the Game.Start() method.
import android.content.Context;
import android.content.Intent;
public class GameLoop extends Menu{
boolean hello = false;
public void Start(Context sContext){
Intent openOptions = new Intent(sContext, Options.class);
startActivity(openOptions);
}
}
I'm not sure if using context would be the right way of going about this but I figured it was worth a try. Im entirely new to java and android so I'm pretty much lost on where to go next. Any help in what direction to take would be throughly appreciated.
Activity extends Context, so you can just use this when inside Activity.
Game.Start(Menu.this);
I use Menu.this because you are inside inner anonymous class (View.OnClickListener) where this refers to this inner class.
Do you added the new activities to the androidmanifest.xml?

Categories