Is findViewById() not be instanced? - java

I have a question about programming in android.
When I write a activity like this:
package com.mathquiz;
import android.widget.ImageButton;
public class ChooseMode extends ActionBarActivity {
private ImageButton easyButton=(ImageButton)findViewById(R.id.easy_button);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mode);
easyButton.setVisibility(View.INVISIBLE);
}
The eclipse throws NullPointerException at line 4
However, if I assign "easyButton" in method onCreate, everything will be OK.
package com.mathquiz;
import android.widget.ImageButton;
public class ChooseMode extends ActionBarActivity {
private ImageButton easyButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_mode);
easyButton=(ImageButton)findViewById(R.id.easy_button);
easyButton.setVisibility(View.INVISIBLE);
}
Please help me to understand this problem.

It can't be "instanced" as you call it because in your first example, you haven't set a content view yet. Android's lifecycle methods have a specific order, that occur after the constructor is called.
The method works as expected, it just returns null because it has nothing to find at that current time.
Also, using an instance variable that requires using the current Activity as a Context will not work (In the below example, this refers to the ChooseMode instance).
Eg
public class ChooseMode extends ActionBarActivity {
private SharedPreferences = PreferenceManager.getDefaultSharedPreferences (this);
Will throw a NullPointerException down the line when used.

The layout is not defined on class variable definition. That's why it's a NullPointerException, because you haven't called setContentView(R.layout.activity_choose_mode); yet.
If you want to do that way, to avoid that amount of boilerplating, try RoboGuice. An example of a view could be this:
#ContentView(R.layout.main)
class RoboWay extends RoboActivity {
#InjectView(R.id.name) TextView name;
#InjectView(R.id.thumbnail) ImageView thumbnail;
#InjectResource(R.drawable.icon) Drawable icon;
#InjectResource(R.string.app_name) String myName;
#Inject LocationManager loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name.setText( "Hello, " + myName );
}
}
More examples and tutorials are here.

Related

did i call wrongly in android studio?

i am trying to use this answer but i don't get why am i getting this error:
error: class, interface, or enum expected
the code:
package com.example.moviereview3;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
BottomNavigationView bottomNavigationView = BottomNavigationView)findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);
sorry for asking so many dumb questions and thanks for answering
Do like this:-
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);
}
}
You are missing a "(" right before casting the view, but even more importantly you're lacking to understand that the reference should be called inside the onCreate() method of the class. Placing stuff outside of the class would compromise proper form and prevent the compiler from recognizing and/or synthesizing the code you wrote, as such, the example you provided.
As an alternative, you could create a class member variable and then access it with the this operator, but most importantly make sure the code is inside the class scope.
private ...View bnv; ... this.bnv = instantiate
This would be your modified code, it's up to you if you want member variables vs local variables.
public class HomeActivity extends AppCompatActivity {
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationView bottomNavigationView =
(BottomNavigationView)findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);
} //END_ON_CREATE_METHOD
}/END_HOMEACTIVITY_CLASS

Load PowerPoint file in Android

I am trying to make a PPT viewer app.I have added the pptViewer library in my project from https://github.com/itsrts/pptviewer-android.
But I am getting an error called "cannot resolve symbol 'activity'" on this line pptViewer.loadPPT(activity,"/home/waheed/lab6.pptx").Please help.
Below is my code:
package com.example.waheed.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.itsrts.pptviewer.PPTViewer;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPTViewer pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
pptViewer.setNext_img(R.drawable.next)
.setPrev_img(R.drawable.prev)
.setSettings_img(R.drawable.settings)
.setZoomin_img(R.drawable.zoomin)
.setZoomout_img(R.drawable.zoomout);
pptViewer.loadPPT(activity,"/home/waheed/lab6.pptx");
}
}
activity isn't a defined symbol, but . In this case, since the code is in an activity, use the current object:
pptViewer.loadPPT(this, "/home/waheed/lab6.pptx");
You probably copy-pasted from the readme, as the activity used as sample method input in the readme means you have to pass an activity instance. You don't declare Activity activity = ..., but since you're in an activity you can use this
pptViewer.loadPPT(this,"/home/waheed/lab6.pptx");
Try this:
pptViewer.loadPPT(MainActivity.this,"/home/waheed/lab6.pptx");
You reference activity in your code which is not defined. Pass current class instead of the undefined field.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPTViewer pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
pptViewer.setNext_img(R.drawable.next)
.setPrev_img(R.drawable.prev)
.setSettings_img(R.drawable.settings)
.setZoomin_img(R.drawable.zoomin)
.setZoomout_img(R.drawable.zoomout);
pptViewer.loadPPT(MainActivity.this,"/home/waheed/lab6.pptx");
}

Can we call a method declared in same class in MainActivity not in onCreate or other methods in android studio?

I have created a method in MainActivity class. I know I can call that in onCreate method and other methods in that same class. But can I call that method outside onCreate and other methods but in MainActivity class?
When I try to do that, I get an error.
The error I am getting is "Invalid method declaration" but I have already declared the method below. I am just calling it here.
package com.example.android.kabaddicounter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//Can we call this method here? Its giving an error
displayForPakistan(25);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void displayForPakistan(int score){
TextView scoreView = (TextView) findViewById(R.id.score_pakistan);
scoreView.setText(String.valueOf(score));
}
public void displayForIndia(int score){
TextView scoreView = (TextView) findViewById(R.id.score_india);
scoreView.setText(String.valueOf(score));
}
}
The answer is no you can't, unlike other codeflows the android codeflow runs only through callback functions called from the devices internal system.
You can for example call a method from other method but if that method will not be call from any of the callbacks , both will never get excited
With that been said, you have the exception of listener which can also call methods but there are just another type of callbacks
Read about activitys lifecycle to learn more

LunchList Android App

I am new to Android Programming. I am doing this project from the book. I wrote the class to return the name and the address and then wrote the OnClickListener for it but it doesn't seem to work when i click the save Button. Here is my Two Java file:
package com.example.lunchlist;
public class Returant {
private String name="";
private String address="";
public String getName() {
return(name);
}
public void setName(String name) {
this.name=name;
}
public String getAddress() {
return(address);
}
public void setAddress(String address) {
this.address=address;
}
}
Here is my MainActivity File:
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Returant r = new Returant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
}
};
}
I believe once you click the save Button it suppose to return the name and the address that you have on the TextField
I have no idea why you would think that. The book certainly does not indicate that. I know this, because I wrote the book in question. Specifically, this would appear to be from my retired book, Android Programming Tutorials, specifically Tutorial #2.
In the most recent Creative Commons edition of the book (Version 3.4), the end of the tutorial steps for Tutorial #2 has:
Run the application to make sure it seems like it runs without errors,
though at this point we are not really using the data saved in the restaurant
object just yet.
All we are doing, at this point in the tutorials, is taking data out of EditText objects and putting it into a Restaurant (or, in your case, Returant).
You can just log the value and see the log.
Try adding these two lines in the OnClickListener.
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
If something is printed out, that means you successfully set the values to the variable.
public class MainActivity extends Activity {
Returant r = new Returant();
EditText name;
EditText address;
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
Log.i(TAG, r.getName());
Log.i(TAG, r.getAddress());
}
};
}

Problems with OnClickListener

Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code:
package karim.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
}
and i got this error :
Description Resource Path Location Type
The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem
can you please tell me whats wrong ????
Please Be specific !!
My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, #Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6.
Change the compiler version, or remove the #Override annotation on the onClick method.
You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs:
http://developer.android.com/guide/topics/ui/ui-events.html
public class TestActivity extends Activity{
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
or in your case
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
if(v==b1)
{
//button logic
}
}
As an extension to "JB Nizet" answer:
The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition.
<Button android:text="Click Me!"
android:onClick="doSomething"
/>
In your java-code:
public void doSomething(View v){
// Do stuff here
}
This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6
Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.

Categories