How to initialize LinearLayout variable? - android

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!

Related

How do I go about accessing a view when the activity is created? [duplicate]

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!

Nullpointerexception when trying to read textfield - Android

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(...)

Textview.text change example

I have 2 layouts. First layout has 2 textviews. And second layout has 1 button. I want to do when i pres buton textviews.text change. But i get null error about textviews.
textviews on musicactivity, button on homeactivity.
my first activity class --> homeactivity,secon activity class --> Musicactivity,textview-->ad1,textview-->ad2,textviews on musiclayouts,Button on homeactivity.
public class HomeActivity extends Activity {
Button btn;
TextView ad1;
TextView ad2;
private MusicActivity music;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
btn=(Button)findViewById(R.id.button1);
ad1=(TextView)findViewById(R.id.textView1);
ad2=(TextView)findViewById(R.id.textView2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
ad1.setText(null);
ad2.setText(null);
}
}
});
}
The error message you posted is for line 40, which is doing a close of v1. I don't know what a veritabani is, but it appears that error is happening there. I suspect the rest of the error trace might say more.
You are doing it wrong. You can't get the textViews if they are not in the layout. You say yourself they are not in the layout. You have to pass the values you want to set to the new activity (musicActivity) via an Intent. Then in musicActivity's you can get the textViews, you have the values, you set them.

setContentView and Listeners

I'm changing my ContentView of the Activity at some point. (to View2).
After changing it back to View1, the listeners are not more working.
I already tried putting the Listener in the onResume() method.
Is it common anyway to use setContentView() to display e.g. a Progress screen/please wait,...(while an asyncTask is running).
Or should you only have ONE mainView for each Activity? (and replacing the content dynamically).
//EDIT: To be more specific:
I am looking for something like
LinearLayout item = (LinearLayout) findViewById(R.id.mainView);
View child = getLayoutInflater().inflate(R.layout.progress, null);
item.addView(child);
but instead of adding the "progress.xml", it should remove the current layout and ONLY show "progress.xml".
Do I need an "container" and show/hide mainView/progress?
But that doesn't seem very proper to me...
See also code below (stripped)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doSomething();
}
});
}
setContentView(R.layout.view2);
[...]
setContentView(R.layout.view1);
//Listener not more working
Thank you all, for your reply. You made me realize, the onClickListeners are getting lost when I remove or replace (using setContentView()) the main view. I ended up this way now:
onCreate:
setContentView(R.layout.parse);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
container.addView(getLayoutInflater().inflate(R.layout.dialog, null));
container.addView(getLayoutInflater().inflate(R.layout.progress, null));
onStartDoingSomething:
findViewById(R.id.dialog).setVisibility(View.INVISIBLE);
findViewById(R.id.progress).setVisibility(View.VISIBLE);
onEndDoingSomehting:
findViewById(R.id.dialog).setVisibility(View.VISIBLE);
findViewById(R.id.progress).setVisibility(View.INVISIBLE);
I might change View.INVISIBLE to View.GONE, like nmr said, but since I have never used View.GONE, I have to check the Android doku first ;)
Assuming you use 'findViewById' to initialize 'button', you would need to do that every time that you do setContentView(R.layout.view1);
You can only have one UI for each Activity, you should create another activity and in its onCreate method set the content view
Steps:
Create Activity
Use the following code to set the content View:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view2);
}
Define the Activity in the applications manifest as such :
Create an intent in the first Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view1);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
intent();
}
});
}
void intent(){
Intent intent = new Intent();intent.setClass(Activity1.this, Activity2.class);
startActivity(intent);
}
And there you go c:

onClick attribute in XML linking to method in Activity class

There are quite a few questions about this subject, but could not find any with the specific problem I have...
In my layout.xml, I use the android:onClick tag for a Button to call the right onClickListener. I get the error :
java.lang.IllegalStateException: Could not find a method handle_cancel(View) in the activity class com.matthieu.HelloWorldApplication for onClick handler on view class android.widget.Button with id 'button_cancel'
I have that method implemented in the Activity, but it is looking for it in the class that extends Application... I don't understand why. The View and all that is setup only in the Activity.
If anyone needs, here is the declaration of that method (in my activity, NOT in HelloWorldApplication):
public void handle_cancel(View v) {
// do something useful here
}
Edit (from adamp request)... and probably answering my own question :
Here is part of the code where that layout is used...
public class AddVocabularyActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.top); // that layout contains an empty LinearLayout id/main_content
}
private some_other_function() {
LinearLayout main_content = (LinearLayout) findViewById(R.id.main_content);
main_content.removeAllViews();
View.inflate(getApplicationContext(), R.layout.hello, main_content); // layout.hello is the one containing the button
}
// some other stuff
}
While copy/paste this code, I am guessing the problem is that I used getApplicationContext to inflate the View with that Button...
As mentioned in my edit, changing the getApplicationContext() with the Activity context fixes it...
The convention works like this:
In the layout xml file, you give this attribute:
android:onClick:"methodname"
Then, inside a class, you define a method like this:
public void methodname(View v){
//your method code
}
Any other way of doing this is not documented. If you need parameters, just call another method inside that method.

Categories

Resources