I have a button with a method that is invoked upon clicking.
The method:
public void addToList(View view) {
System.out.println(1);
String str = "";
try{
str = edit.getText().toString();}
catch (Exception ex){
System.out.println( ex );
}
System.out.println(2);
new QueryInList( ).execute(helper, str);
System.out.println(3);
edit.setText(null);
System.out.println(4);
//adapter.notifyDataSetChanged();
}
Well, I always get the exception, it is a Nullpointerexception.
This quite baffles me, because edit IS initalized:
It is declared in the class:
private EditText edit;
and besides, it is initialized in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edit = (EditText)findViewById(R.id.textfield);
setContentView(R.layout.activity_view);
......}
So I wonder why I always get a Nullpointer?
Set the content view, before looking for the items. You dont have a view to find the items in until you set the content view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
edit = (EditText)findViewById(R.id.textfield);
......}
Move edit = (EditText)findViewById(R.id.textfield); after your setContentView statement.
Here is a nice explanation from user #Squonk from another question:
setContentView(...) perfoms something called 'layout inflation'. What that means is it parses the XML in the relevant file (main.xml in your case) and creates instances of all the UI elements within it. It then attaches that view to the Activity. When you call findViewById(...) it doesn't reference your main.xml directly - instead it references the content view attached to the Activity, in other words the one inflated by setContentView(...)
Related
Quick notice: I am using SharedPreferences so that I can reload data when I re-open the app.
Problem
I have a LinearLayout in the main fragment of my application. Everything runs smoothly until I re-open the app and try to reinitialize the LinearLayout.
I am trying to initialize the LinearLayout with findViewById(). I have put the function in many different places. Currently I am trying to get it to work in onCreate and a function that is called from onCreate. Here is my code so far:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.linearLayout);
// this is where is load the SharedPreferences
// this is where I implement them back into the app ('reload' the app)
reload();
}
public void reload() {
// bunch of other irrelevant stuff
linearLayout = findViewById(R.id.linearLayout);
linearLayout.addView(/*other view*/); // this is where it complains
}
// the is for when the button is clicked
public void submitEntry(View view) {
// this is fine according to Logcat
linearLayout = findViewById(R.id.linearLayout);
}
}
I would expect after initializing it twice, or at least trying to, that is would've caught on but no. Logcat complains that linearLayout is a null object reference. I don't know what to do at this point but it's probably something simple that I've overlooked. Any help would be appreciated.
LinearLayout linearLayout= new LinearLayout(context);
Initialize like this it will help you!
Quick notice: I am using SharedPreferences so that I can reload data when I re-open the app.
Problem
I have a LinearLayout in the main fragment of my application. Everything runs smoothly until I re-open the app and try to reinitialize the LinearLayout.
I am trying to initialize the LinearLayout with findViewById(). I have put the function in many different places. Currently I am trying to get it to work in onCreate and a function that is called from onCreate. Here is my code so far:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.linearLayout);
// this is where is load the SharedPreferences
// this is where I implement them back into the app ('reload' the app)
reload();
}
public void reload() {
// bunch of other irrelevant stuff
linearLayout = findViewById(R.id.linearLayout);
linearLayout.addView(/*other view*/); // this is where it complains
}
// the is for when the button is clicked
public void submitEntry(View view) {
// this is fine according to Logcat
linearLayout = findViewById(R.id.linearLayout);
}
}
I would expect after initializing it twice, or at least trying to, that is would've caught on but no. Logcat complains that linearLayout is a null object reference. I don't know what to do at this point but it's probably something simple that I've overlooked. Any help would be appreciated.
LinearLayout linearLayout= new LinearLayout(context);
Initialize like this it will help you!
I was looking at my code and I realized that there are at least 3 ways of getting widget's reference in code:
First one (before onCreate):
private TextView textView= (TextView) findViewById(R.id.textView);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
Second one (in onCreate):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
final TextView textView= (TextView) findViewById(R.id.textView);
}
Third one (creating out and setting in onCreate):
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
textView= (TextView) findViewById(R.id.textView);
}
What is the difference between this 3 methods? When should I use them?
You must call setContentView() prior calling findViewById(), therefore on 1st approach will give you null all the times. 2nd and 3rd are the same with the exception for final keyword, but this is Java feature, not Android's.
The first does not guarantee that your widget is actually instantiated, it is not within the onCreate.
Second will be instantiated, but its value can not be changed because it becomes a constant to be the final.
Third, it is a global variable that will be instantiated in onCreate and you can use it in any other part of your code.
If you need to call findViewById() then the call should be anywhere after setContentView. Not before that like in your first option. Your third option creates an instance variable, use it only if the textview will be accessed a lot throughout the class, otherwise just call findViewById wherever you need it.
I'm new to android, so maybe I'm doing something horribly wrong. I want to have a particular Activity that shows details about an instance of a "Creature" class for a game. Name, damage taken, that sort of thing.
I'm having a problem getting the creature data to be properly shown in the GUI objects. Both at initial creation (where it should copy the creature's name into the name field) and when a damage mark is added (where it doesn't update to show the proper image).
Here's my mini-example of what I have:
public class CreatureDetailActivity2 extends Activity
{
Creature creature;
public void addMark(View v)
{
// connected to the button via android:onClick="addMark" in the XML
creature.getTrack().addDamage(DamageType.Normal, 1);
refreshDisplay();
new AlertDialog.Builder(this).setTitle(creature.getName())
.setMessage(creature.getTrack().toString()).show();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creature_detail);
creature = new Creature("Example");
refreshDisplay();
}
public void refreshDisplay()
{
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
final EditText nameField = (EditText) (creatureDetailView
.findViewById(R.id.textbox_creature_name));
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) (creatureDetailView.findViewById(R.id.damageBox0));
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
}
Now the problem is that the app will load up and start, but then none of the widgets will update properly. You can click the button, and it'll show the AlertDialog, and the text of the AlertDialog will change, but the textfield in the activity won't be changed, and the ImageView doesn't change at any point from what it starts as to the one it's supposed to change to.
So I'm very stumped. I can post more about the project's setup if I'm leaving out something important, but I'm not even sure what the problem going on is so I'm not sure what else to include in my question.
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
Inflates your Activity's layout into basically nothing, just returning the View it inflated. setContentView is what actually inflates your layout into the Activity's View hierarchy.
Once you inflate your layout you don't need to do it again. Just use findViewById without the reference to a dangling unattached View.
Change your refreshDisplay method to this:
public void refreshDisplay()
{
final EditText nameField = (EditText) findViewById(R.id.textbox_creature_name);
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) findViewById(R.id.damageBox0);
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
Nothing changes because You do it completely wrong.
If You wish to update any view element of current activity You do it like this
View v = findViewById(R.id.element);
v.setText("text");
this is just simple example.
You would need to cast a returned element to correct type like to be able to access all available methods.
What You do wrong is trying to inflate a layout again.
I have several LinearLayouts contained inside their respective ScrollView which in turn are contained by a ViewFlipper. The odd stuff is that in some of the Layouts once they have the focus, it starts automatically in a place other than the top.
So what can be causing this ? In order to force them to start at the top, is there something like the tabindex property in html ?
Thanks
if you have problem called focus is gone automatically on other place instead of top position's field then you have to write this code simply at onStart() method of activity life cycle with respective field id in my case first field
is referenced by firstfield_et this is the variable of Activity.java file and it is also already referenced by etfirstfield from .xml file
the code is simply as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstfield_et= (EditText) findViewById(R.id.etfirstfield);
}
#Override
protected void onStart() {
super.onStart();
if(TextUtils.isEmpty(firstfield_et.getText().toString())){
firstfield_et.requestFocus();
}
}