I am learning android so I wrote this code just to toggle phone ringer mode. The code compiles with no problem, I made entry in Android Manifest, set content view to the required Layout but I run this app, I get Force close error. Can somebody tell me why Force Close errors occur so that in future I should be to figure out the problem myself.Here is the code:
package com.umer.practice2;
import android.R.bool;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
public class RingerMode extends Activity implements View.OnClickListener {
ToggleButton tb;
ImageView Riv;
TextView tv;
AudioManager mRing;
boolean silent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringermode);
tb.setOnClickListener(this);
InitializeShit();
mRing=(AudioManager) getSystemService(AUDIO_SERVICE);
}
private void InitializeShit() {
// TODO Auto-generated method stub
tb= (ToggleButton) findViewById(R.id.ringTB);
tv= (TextView) findViewById(R.id.ringTV);
Riv= (ImageView) findViewById(R.id.ringIV);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkMode();
if(silent)
{
Riv.setImageResource(R.drawable.mysplash);
}else
{
Riv.setImageResource(R.drawable.myscreen);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
checkMode();
}
private void checkMode() {
// TODO Auto-generated method stub
int temp = mRing.getRingerMode();
if(temp==AudioManager.RINGER_MODE_SILENT)
{
tv.setText("Silent");
Riv.setImageResource(R.drawable.mysplash);
silent= true;
}else
if(temp==AudioManager.RINGER_MODE_NORMAL)
{
tv.setText("Normal");
Riv.setImageResource(R.drawable.myscreen);
silent= false;
}
}
Many Thanks
You need to take a look at the logcat to see what happens. See Logcat | Android Developers.
Find the stacktrace of the crash, which points to your problem. If you can't figure it out yourself, please copy/paste the logcat in your question.
In this very case, you are referencing tb before initializing it:
tb.setOnClickListener(this);
At this point, tb is still null, so a NullPointerException occurs. To resolve this, change your code like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringermode);
InitializeShit();
tb.setOnClickListener(this);
mRing=(AudioManager) getSystemService(AUDIO_SERVICE);
}
Also, I recommend using Java's conventions regarding methods and variable naming:
Classes start with a capital: e.g. MyClass
Variables start with a lowercase: e.g. myVariable
Methods start with a lowercase: e.g. myMethod()
This will save you from confusion later on.
Related
I am trying to use a code from this link https://developer.android.com/training/connect-devices-wirelessly/nsd.html
"from Discover Services on the Network."
I copy and paste code as the following:
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// there is an error in the next line, ";" expected.
// but I do not know where to put ; exactly
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Registration failed! Put debugging code here to determine why.
}
#Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
} }
});
}
}
But there is an error in the this Line "public void initializeRegistrationListener()", ";" expected. but I do not know where to put ";" exactly or there is something else wrong that I cannot see it, can someone guide me, please?
PS: I am trying to make my phone discovers Mdns service that I created on my laptop using javascript, I have no experience in Java but I need to run the previous code to test the service that I have created already.
First of all you need an xml that contains an Button(this button will have android:id="#+id/mybutton", and that's the id you have to use on findViewById(R.id.mybutton).
In onCreate method of your activity you will write that code that you showed us, and you are good to go.
Another small step, if you wrote your own xml, make sure to have this line in onCreate
setContentView(R.layout.yourxml)
I get this error while debugging. I put a breakpoint somewhere in the code.
The project is built and run on my device, but in debugging I get this code, which is looking for android.jar
My target version of android is 2.2. I chose /appcompat_v7/bin/appcompat_v7.jar instead of android.jar, assuming this version of Android is based on appcompat_v7.jar. I don't know.... I was just assuming. Nevertheless, it's not working.
I checked some of Similar Questions and I couldn't find the exactly my answer, this was the most similar problem, yet my problem wasn't solved:
Eclipse java debugging: source not found
This is a screenshot of the error:
http://i.stack.imgur.com/6m45J.png
Thhanks. :)
package com.thenewboston.travis;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class OpenedClass extends Activity implements OnClickListener,
OnCheckedChangeListener {
TextView question, test;
Button returnData;
RadioGroup selectionList;
String gotBread;
String setData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
initialize();
// Bundle gotBasket = getIntent().getExtras();
// gotBread = gotBasket.getString("key");
// question.setText(gotBread);
}
private void initialize() {
// TODO Auto-generated method stub
question = (TextView) findViewById(R.id.tvQuestion);
test = (TextView) findViewById(R.id.tvText);
returnData = (Button) findViewById(R.id.bReturn);
returnData.setOnClickListener(this);
selectionList = (RadioGroup) findViewById(R.id.rgAnswers);
selectionList.setOnCheckedChangeListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent person = new Intent();
Bundle backpack = new Bundle();
backpack.putString("answer", setData);
person.putExtras(backpack);
setResult(RESULT_OK, person);
finish();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.rCrazy:
setData = "Probably right!";
break;
case R.id.rSexy:
setData = "Definitely right!";
break;
case R.id.rBoth:
setData = "Spot On!";
break;
default:
break;
}
test.setText(setData);
}
}
This is not an error.
You try to open the source of the class, but you only have access to the .class file (which is all you need to run it).
You can attach the code (for instance by clicking the Change attached sources button), but this is in no way mandatory.
You have skip that point by pressing F8 instead of F6 cause you have limitation of it. So try this one.
I have a game where you click on an image in the centre, and a value increases. When the app is opened, I've made a splash come up before the main activity starts (the clicking screen). However, every time I back out of the app, and click the icon again, it goes through the splash, goes to the main screen, and starts the game again, setting the value back to zero.
My Java for the Splash:
package com.bipbapapps.leagueclickerapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class Splash extends Activity {
#Override
public void onCreate(Bundle splashBundle) {
// TODO Auto-generated method stub
super.onCreate(splashBundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
Thread logoTimer = new Thread(){
public void run(){
try {
sleep(2000);
Intent mainIntent = new Intent("com.bipbapapps.leagueclickerapp.CLICKER");
startActivity(mainIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
My Java for the MainClass which is then run:
package com.bipbapapps.leagueclickerapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class MainClass extends Activity implements OnClickListener {
public float goldCount = 0.0f;
Button minionClick;
TextView textGoldCount;
String textTotal;
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainlayout);
//Linking the variables
minionClick = (Button) findViewById(R.id.minioncentreid);
textGoldCount = (TextView) findViewById(R.id.textviewtop);
//String which will display at the top of the app
textTotal = goldCount + " Gold";
//Setting TextView to the String
textGoldCount.setText(textTotal);
//Setting onClickListener
minionClick.setClickable(true);
minionClick.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.minioncentreid:
goldCount += 1.0;
textTotal = goldCount + " Gold";
textGoldCount.setText(textTotal);
break;
}
}
}
Anyone have any idea how to allow my game to pause and resume when it's minimized? Also, is there a way so that when the app is destroyed (properly closed), and restarted, the values for variables are kept? Would appreciate your help.
Inside onBackPress of the second activity, you should store the score in shared preferences. Every time you come on the onCreate of Splash activity, retrieve the score value and check if it is set to 0 then show splash screen else goto main activity with current score.
I am trying to set up a surface view for graphics but an error keeps showing up that I have to import SView when I already did. Everything I try never seems to work. Is anything missing in the following code? or is it that I forgot to add something.
Firstclass.java:
package com.XXX.XXX;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.mtprogramming.blockfight.SView;
SView ourView;
public class Singleplayer extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ourView = new SView(this);
setContentView(ourView);
}
}
SView:
package com.XXX.XXX;
public class SView extends SurfaceView implements Runnable{
public SView(Singleplayer singleplayer) {
// TODO Auto-generated constructor stub
}
public void run(){
}
}
Check the package for SView.java: com.XXX.XXX it intended as so?
If yes, use import com.XXX.XXX.Sview instead of import com.mtprogramming.blockfight.SView in Firstclass.java
I have a button that leads to another page. And whenever I click it I get this info code in logcat :
12-07 16:09:45.073: I/ActivityManager(273): Displayed com.example.prva/.button: +1s764ms
Seconds and ms vary of course each time between 1-3 seconds. The problem is that I noticed that it takes a while for that button to open that page. It has some kind of pause or whatever and this is the only relevant thing I have found in the logcat that could be connected to it. How can I fix this, why is this button acting "slow"?
This is where the button code is :
package com.example.prva;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Meni_Splash extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnv = (Button) findViewById(R.id.buttonv);
btnv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Meni_Splash.this, button.class));
}
});
}
}
And this is the class that opens :
package com.example.prva;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
public class button extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
//Button click sound
final MediaPlayer MPRadio1 = MediaPlayer.create(this, R.raw.radio1);
final MediaPlayer MPRadio2 = MediaPlayer.create(this, R.raw.radio2);
final MediaPlayer MPRadio3 = MediaPlayer.create(this, R.raw.radio3);
final RadioButton rb1, rb2, rb3;
rb1 = (RadioButton) findViewById(R.id.radio1);
rb2 = (RadioButton) findViewById(R.id.radio2);
rb3 = (RadioButton) findViewById(R.id.radio3);
Button btn = (Button) findViewById(R.id.buttonplay);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(rb1.isChecked())
{
MPRadio1.start();
}
else
{
if(rb2.isChecked())
{
MPRadio2.start();
}
else
{
if(rb3.isChecked())
{
MPRadio3.start();
}
}
}
}
}
);}}
I don't know what thing could make it so slow from these activities?
Your code looks pretty decent to be honest. Not sure entirely what could be causing it to intialise slowly.
But there are two areas to look at.
The first, most likely, is your layout loading:
setContentView(R.layout.button);
I dont imagine your layout to be complex though. But if it is, aka, lots of nested views (linear layouts within other linear layouts), or lots of views (textviews etc) in general on the page, then it could be taking a while to "inflate" the Layout.
Alternatively and less likely, is that MediaPlayer.create takes a fair while to load. The reason I suggest this, is I have no idea how it works, as I've not used it before.
//Button click sound
final MediaPlayer MPRadio1 = MediaPlayer.create(this, R.raw.radio1);
final MediaPlayer MPRadio2 = MediaPlayer.create(this, R.raw.radio2);
final MediaPlayer MPRadio3 = MediaPlayer.create(this, R.raw.radio3);
The best thing to do, would be to profile it with the DDMS profiler. Or put a timer around it, and print the results to logcat.
Also, on a quick note, is it just 2-3 seconds loading? And is it really that bad for what its trying to do?