I have declared a button in A.Class and have set disabled.
public static Button s1=(Button)findViewById(R.id.sn1);
s1.setEnabled(false);
Now i want to enable this button in another class(B.class)
I tried enabling this button by giving
Button s2=A.s1;
But its throwing an error saying "Cannot make a static reference to the non-static method findViewById(int) from the type Activity"
Pls help me in correcting the error
`First Class:
public class Mapper extends Activity implements OnClickListener
{
public static int sng=0,c=0;
public static double lat;
public static double lon;
public String placenametemp;
public Bundle savedInstanceState;
public static int chk= MapMe.check;
LocationManager locman1= MapMe.locman;
MyOwnLocationOverlay mylocover=MapMe.myLocationOverlay;
public MediaPlayer msong=MapMe.mp;
***public Button s1=(Button)findViewById(R.id.sn1);***
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Add Click listeners for all buttons
View firstButton = findViewById(R.id.geocode_button);
firstButton.setOnClickListener(this);
View secondButton = findViewById(R.id.latlong_button);
secondButton.setOnClickListener(this);
View thirdButton = findViewById(R.id.presentLocation_button);
thirdButton.setOnClickListener(this);
View selectsong=findViewById(R.id.song_select);
selectsong.setOnClickListener(this);
s1.setOnClickListener(this);
s1.setEnabled(false);
}
}
Second Class :
public class MapMe extends MapActivity implements LocationListener
{
Button s1=(Button)findViewById(R.id.sn1);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Suppress title bar to give more space
setContentView(R.layout.mapme);
updateGPSprefs();
// Set up location manager for determining present location of phone
locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Listener for GPS Status...
final GpsStatus.Listener onGpsStatusChange = new GpsStatus.Listener(){
public void onGpsStatusChanged(int event){
switch(event){
case GpsStatus.GPS_EVENT_STARTED:
// Started...
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// First Fix...
Toast.makeText(MapMe.this, "GPS has First fix",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
// Stopped...
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// Satellite update
break;
}
GpsStatus status = locman.getGpsStatus(null);
Iterable<GpsSatellite> satlist = status.getSatellites();
}
};
public void fu(double a,double b,double c,double d)
{
if((val==0)&&(val1==0))
{
mp.reset();
try {
check=1;
System.out.println("matched");
mp.setDataSource(link1);
mp.prepare();
mp.start();
Toast.makeText(MapMe.this, "playing", Toast.LENGTH_LONG).show();
System.out.println("Song button1");
***s1.setEnabled(true);***
System.out.println("Song button");
}
catch(Exception e)
{
}
}
`
You are calling findViewById() in wrong location. You should call it from within some non-static method like onCreate(). This method i.e findViewById() is non-static, so you can not call it the way you have mentioned. So you should declare your variable as static and then set its value in onCreate() of the activity.
Why dont you just call findViewById() in B class and then disable the view. As long as the view is available in the currently loaded layout the following code in B class should do your job.
Button s1=(Button)findViewById(R.id.sn1);
s1.setEnabled(false);
inside Class A :
public static Button s1=(Button)findViewById(R.id.sn1);
s1.setEnabled(false);
Inside Class B:
you should Write : A.s1.setEnabled(true);
EDITED
inside Mapper.java :
Class Mapper extends Activity{
public static Button s1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setEnabled(false);
}
}
inside Mapme.java :
Class Mapme extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_new);
Mapper.s1.setEnabled(true);
}
}
try this out. Might Help you.
Related
I want to finish an activity by an image, and here is what I did:
there's an ImageView in the layout [activity_login.xml] .
/**
* the activity that I want to destroy
*/
public class LoginActivity extends Activity {
public static LoginActivity activityInstance;
private ImageView imgBtnBack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// for closing this activity by an another class
activityInstance = this;
// add event listener
imgBtnBack = (ImageView) findViewById(R.id.img_btn_back);
imgBtnBack.setOnClickListener(new LoginActivityListener());
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
/**
* the event handler of LoginActivity
*/
public class LoginActivityListener implements View.OnClickListener{
private Context context;
#Override
public void onClick(View view) {
context = view.getContext();
int id = view.getId();
switch (id) {
case R.id.img_btn_back: // close the activity by an image
LoginActivity.activityInstance.finish();
default:
break;
}
}
}
And I don't know if it was good by the way I did.
can anyone find and tell me a better way to make this work.
Add below code in your onCreate method
imgBtnBack = (ImageView) findViewById(R.id.img_btn_back);
imgBtnBack .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Calling onBackPressed method of Activity class on a View Class? is it possible? and so how can I? thanks for help
UPDATE: I just created the GameView of my Game which is extends to View Class. I create a variable that increments whenever I finish every level so it will limit a levels per game. And so I want to implement a onBackPressed method which I can set the incrementing variable back to zero whenever the player press the back key.
FULL CODE: MAIN ACTIVITY
public class MainActivity extends Activity {
private GameView mGameView;
#Override
public void onBackPressed() {
if (mGameView.interceptBackPressed()) {
return;
}
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mGameView = (GameView) findViewById(GameView.countmaze);
Afterwards it goes to Menu Class
public class menu extends Activity implements OnClickListener {
static int nextmaze;
int countmaze = 0;
GameView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnplay = (Button) findViewById(R.id.btnPlay);
btnplay.setOnClickListener(this);
}
#Override
public void onBackPressed() {
//I have here an AlertDialog builder
}
#Override
public void onClick(View v) {
case R.id.btnPlay:
Toast.makeText(getApplicationContext(), "LEVEL 1",
Toast.LENGTH_SHORT).show();
startnextmaze();
}
}
void startnextmaze() {
Random rand = new Random();
Intent game = new Intent(menu.this, Game.class);
nextmaze = rand.nextInt(5) + 1;
Maze maze = MazeCreator.getMaze(nextmaze);
game.putExtra("maze", maze);
startActivity(game);
}
Then on my GameView Class
public class GameView extends View {
static int countmaze;
//Big codes here......
public boolean interceptBackPressed() {
// TODO Auto-generated method stub
countmaze = 0;
return true;
}
}
Create a callback on the Activity onBackPressed that the View class will implement
Example
public void interface onBackPressedHandler {
public void onBackPressed();
}
Activity Class
public onBackPressedHandler mHandler;
#Override
public void onCreate(....) {
GameView game... //Inflate or create.
game.setActivity(this);
}
public void setListener(onBackPressedHandler handler) {
mHandler = handler;
}
#Override
public voind onBackPressed() {
if(mHandler != null) {
mHandler.onBackPressed();
}
super.onBackPressed();
View Class
public GameView extends View implements onBackPressedHandler {
public void setActivity(Activity activity) {
activity.setListener(this);
}
public void onBackPressed() {
//your code here.
}
}
This example shows when you press the back Button it will call the onBackPress on the View.
Hope it Helps.
Update your code with the following changes:
Activity
public class MyActivity extends Activity {
private GameView mGameView;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
//View reference to object defined in XML
mGameView = (GameView) findViewById(R.id.gameview);//id must be specified in XML
//I assumed that GameView is a part of your XML layout
//View created programmatically.
mGameView = new GameView(this);
//Use one of the above initialisation techniques of mGameView.
}
#Override
public void onBackPressed() {
//here we are calling method on mGameView which cannot be null
//that's why we initialised it in onCreate() method
if (mGameView.interceptBackPressed()) {
return;
}
super.onBackPressed();//finish your Activity
}
}
GameView
public class GameView extends View {
public boolean interceptBackPressed() {
//TODO handle your game logic here and return true if you don't
//want your game to be shutdown, otherwise return false
return true;
}
}
I have activity flow
Activity 1-> Activity 2->Activity 3
If the user performs certain action in Activity 3, shared preferences boolean variable "performed" stores true. Now if the user presses back button to load Activity 2, it doesn't (i used finish()) and loads Activity 1. This is fine and as per the need.
What I want now is, when Activity 1 restarts this way, based on the value of the shared preferences boolean variable "performed" value true the button in Activity should be hidden.
I am using,
if (preferences.getBoolean("performed",false)){
button.setVisibility(View.Gone);
}
I have written this code in onRestart method of the Activity 1.
What am I missing?
The button does not hides.
I have done it in following way
- wrote a singalton class has variable IsVisited.
- check if it is visited in onResume() method
- if visited then set visibility of the button gone
Main Activity
Controller c;
Button bu ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bu = (Button)findViewById(R.id.button1);
c = Controller.getController();
bu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
c.setIsVisited(true);
Intent i = new Intent(MainActivity.this, mainactivity2.class);
startActivity(i);
}
});
}
protected void onResume() {
super.onResume();
if(c.getIsVisited())
{
bu.setVisibility(View.GONE);
}
Another Activity
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Controller c = Controller.getController();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Controller Class (Singleton Class)
public class Controller {
private static final Controller controller = new Controller();
private Boolean isVisited = false;
private Controller()
{
}
public static Controller getController()
{
return controller;
}
public Boolean getIsVisited() {
return isVisited;
}
public void setIsVisited(Boolean isVisited) {
this.isVisited = isVisited;
}}
![enter image description here][1]
I am having a problem about implemeting android apps.
I made baseActivity which is that base of other applications and other applications.
These are my code.
First, BaseActivity.java
public class BaseActivity extends Activity {
protected void onCreate(Bundle savedInstanceState,int layoutId) {
super.onCreate(savedInstanceState);
setContentView(layoutId);
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
}
}
And the other one is MainActivity.java
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState,R.layout.activity_main);
setContentView(R.layout.activity_main);
}
}
Now I have a question! When I was click the menu button, click listener did not act. It did not print log message and any action. So, I have a problem to make my application. Is it related with life-cycle or How can I solve the problem.
I do not like the way you are forcing thing, still if you want to make it works this way you have remove setContentView(R.layout.activity_main); from MainActivity, that's because one you call again setContentView(R.layout.activity_main); in the sublcass, the view hierarchy for that Activity will be recreated invalidating what you have done in the super class
The code is setting the Content View twice. Following is the sequence of your code.
setContentView()
Add button listener
setContentView()
Statement # 2, adds the button listener and it is all good till now. But as soon as you reset the content view on statement # 3, the previous settings get void. And the button gets reinitialized and the onClickListener is no more attached to the button.
Remove the contentview from BaseActivity and put
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
into MainActivity. The Base activity should be SuperClass and MainActivity subclass all the actions for view shold be initialize into the subclass.
Try this :
public class BaseActivity extends Activity {
protected void onCreate(Bundle savedInstanceState,int layoutId) {
super.onCreate(savedInstanceState);
}
public int getLayoutXML() {
return -1;
}
public abstract int getMenuId();
}
After this use this BaseActivity class like this :
public class service_detail extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use button like this:
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
}
#Override
public int getMenuId() {
// TODO Auto-generated method stub
return 1;
}
#Override
public int getLayoutXML() {
// TODO Auto-generated method stub
return R.layout.service_detail;
}
}
I'm trying to start activitiy using intent:
public class Bez_provjere_739 extends Activity {
Button Tbutun;
public void onCreate(Bundle savedInstanceState) {
Tbutun.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent otvoriIn = new Intent("com.riteh.HL.IN");
startActivity(otvoriIn);
}
});
I use it several times in my aplication in the same way but only in this case i get error:
05-17 00:44:43.694: E/AndroidRuntime(3533): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.riteh.HL/com.riteh.HL.Bez_provjere_739}: java.lang.NullPointerException
You never initialized your button nor assigned to it, so it is null.
Also, there are some basics missing from your code:
// naming conventions - variable names start with lower case letter
private Button tbutun;
#Override
public void onCreate(Bundle savedInstanceState) {
// always call super.onCreate
super.onCreate(savedInstanceState);
// if you have a layout XML, use it
setContentView(R.layout.lay_xml_name);
// if the button declared in the layout, refer to it
tbutun = (Button)findViewById(R.id.the_button_name);
// the rest
}
Initialize your Button, try this
public class Bez_provjere_739 extends Activity {
Button Tbutun;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
Tbutun=(Button)findViewById(R.id.button1) //change the id as per yours
Tbutun.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent otvoriIn = new Intent("com.riteh.HL.IN");
startActivity(otvoriIn);
}
});