Why is this static field null? - java

on android.
my activity is like this.
public class MainActivity extends Activity {
static TextView textview;
static int aaa = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_main);
textview = (TextView)findViewById(R.id.textView6);
//other method,startservice()and so on.
and there is BroadcastReceiver to receive a flag from service.
public static class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intents) {
intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
textview.setText("set")//throw null point
Log.d("aaa","aaa is" + aaa);
like this, in onReceiver, textview is null.
as test, int aaa is'nt null.
why textview is null?
EDIT
Texttiew xml is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/adview"
android:layout_alignParentLeft="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
And method in Activity using same textview.settext isnt null.
Thanks.
EDIT2
I can know i should save this variable.
So, whats the best way to save VIEW variable?
SharedPreferences seem not able to save VIEW variable.

This thread indicates that having static fields might be a problem.
In general, android kills your app.. and on return static variables may not be set.
static variable null when returning to the app

This is likely that you are not referencing the correct textview element. Double check your IDs in your layout file.

Related

Displaying variables as text in Android Studio

I'm new to mobile development and I am having trouble displaying variables as text on to the screen.
public class wifiinfo() {
public string getmac = getBSSID();
}
I have this in my main (blank) activity but I have no clue as to how to code this in with XML. The Android Developer tutorials haven't really helped me. Do I have to index the string in a database, perhaps? Any help would be greatly appreciated.
Use Textview to display text.
Add this in your XML:
<TextView
android:id="#+id/textViewSSID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:hint="Your SSID"/>
And display text in activity like this:
TextView tvSSID = (TextView) findViewById(R.id.textViewSSID);
String ssid = getBSSID();
tvSSID.setText(ssid);
Why you create an inner class to keep the value of ssid is a real mystery to me. You can make the variable getmac as a member variable in the activity and initialize it in your onCreate of your activity.
Update:
As to your comment, your activity should start somewhat like this:
public class ActivityName extends Activity {
private string MacId = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
MacId = getBSSID();
//Other functions
}
You can use TextView to write text and display it on the screen.
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Your text here..."/>
If your text line is so long you should write it in res/values/strings.xml:
<string name="my_text">This is a very long line text I want to show on screen.</string>
And use android:text="#string/my_text" to get it in the TextView.
Hope it helps!

Android Change text in TextView

I'm trying to change the text in my TextView by using the setText().
When I try to do this I get the following error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{<bla bla bla>}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.training.mytraining.test.MainActivity.display(MainActivity.java:35)
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView tvCountry;
private Server theServer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvCountry = (TextView) findViewById(R.id.countryTextView);
theServer = new Server(this);
theServer.weatherFromYahoo();
}
public void display() {
tvCountry.setText("USA");
}
}
Server.java
public class Server extends AppCompatActivity {
MainActivity theMainActivity;
//Constructor
public Server (Context context){
this.theMainActivity = new MainActivity();
}
public void weatherFromYahoo() {
theMainActivity.display();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="#+id/countryTextView"
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This is just an example of my real code. I did'nt want to put all the code, so I made a new code with just that problem I get. I have to set the text by calling my MainActivity from an another class.
Please help me, I have been stuck here for hours.
Change this:
public Server (Context context){
this.theMainActivity = new MainActivity();
}
To this:
public Server (Context context){
this.theMainActivity = (MainActivity)context;
}
So that the onCreate is called properly still. If you are new'ing up an activity, it won't be able to set the view properly and follow the correct lifecycle. As #CommonsWare says, you shouldn't ever create an activity via its constructor.

setText() on a textView coming from a subClass in Android

First I'm a beginner in Android development !
In my app, I include a library that help me to create card UI.
In this library, you have a basic layout where there is a Title, a description and a thumbnails but you can create and inflate a custom layout for having a better filled card.
What I want to do is to change the text of a TextView coming from the sub Class, which is linked to the sub Layout. But everytime I try to invoke the setText method from the MainActivity, I get a NullPointerexception.
There is my sub Class:
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.Card.OnCardClickListener;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class CustomCardAccueil extends Card{
public TextView TitreExtensionAccueil;
public TextView DateSortieAccueil;
public TextView NombreCarteAccueil;
public TextView DescriptionExtensionAccueil;
public TextView RareteCarteAccueil;
public TextView DetailExtensionAccueil;
public CustomCardAccueil(Context context) {
this(context, R.layout.accueil_mycard_inner_content);
}
/**
*
* #param context
* #param innerLayout
*/
public CustomCardAccueil(Context context, int innerLayout) {
super(context, innerLayout);
init();
}
/**
* Init
*/
private void init(){
//No Header
//Set a OnClickListener listener
setOnClickListener(new OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Toast.makeText(getContext(), "Click Listener card=", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
TitreExtensionAccueil = (TextView) parent.findViewById(R.id.TitreExtensionAccueil);
}
}
My Layout where there is the TextView that I want to change:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TitreExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DateSortieAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TitreExtensionAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/NombreCarteAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/DateSortieAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DescriptionExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/NombreCarteAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/RareteCarteAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/DescriptionExtensionAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DetailExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/RareteCarteAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
And there is how I try to change the content of TextView in my MainActivity, in the OnCreate:
CustomCardAccueil.TitreExtensionAccueil.setText("Test");
There is also the error I get in the logcat of the crash:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText.setText(java.lang.CharSequence)' on a null object reference
I don't understand the error because the object is initiated (correct me if I'm wrong).
Also if I try to change the text from the sub class (CustomCardAccueil), it's a success, but I need to do it through my MainActivity.
Any help is appreciated, thanks in advance !
You need to initialize the class with something like:
CustomCardAccueil myCard = new CustomCardAccueil(mContext, R.mylayout);
The context you can get from your activity class using something like MyActivity.this or getApplicationContext(). Then you can use methods such as the class' setText:
myCard.setText("blah")
Your TitreExtensionAccueil is said to be null when you are trying to set the text.
You may want to point out where are CustomCardAccueil.TitreExtensionAccueil.setText("Test"); is called for better respond to your question.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText.setText(java.lang.CharSequence)' on a null object reference
shows that you invoked setText() on a null object, so did you initialize CustomCardAccueil.TitreExtensionAccueil and how?
your problem is or you are not using the proper instance for the class CustomCardAccueil, as you declared and initialized the TextView through it, So, even you have to make an instance from the class or to make the TextView declared as static variable, but make sure you run the method called setupInnerViewElements() before trying to set the TextView value.
UPDATE:
to get the current window view through some layout:
View global_view = getWindow().getDecorView(); // use that in the MainActivity to get the view
then, pass that view to your method setupInnerViewElements() and simply create the view with it not with ViewGroup:
in your MainActivity:
CustomCardAccueil mCard = new CustomCardAccueil(getApplicationContext(), R.layout.accueil_mycard_inner_content);
mCard.setupInnerViewElements(parent, global_view);
in your setupInnerViewElements() method:
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
TitreExtensionAccueil = (TextView) view.findViewById(R.id.TitreExtensionAccueil);
}
I've found the answer by looking at the card library and his setTitle Library (I don't know why I've not thinked to this sooner !)
In my CustomCardAccueil class, I've created a String as this:
protected static String titreExtension;
Here is the getter and setter methods:
public String getTitreExtension() {
return titreExtension;
}
public static void setTitreExtension(String titre) {
titreExtension = titre;
}
Again in CustomCardAccueil, in setupInnerViewElements method, I've put this:
TitreExtensionAccueil = (TextView) view.findViewById(R.id.TitreExtensionAccueil);
TitreExtensionAccueil.setText(titreExtension);
And in my MainActivity I simply call my setter with:
CustomCardAccueil.setTitreExtension("test du setTitreExtension");
Simply as this !

Android, set text for an EditText on startup

So I have a simple android app where I take text from a text file (that part is working) and I want to set that text to EditText.setText(). The problem I'm having is that I cannot do this in the onCreate() method because the EditText field and the UI hasn't been created yet(from what it seems).
My question is where would be a good place to do this? Is there a function that is called right after the GUI elements are created?
public class MainActivity extends ActionBarActivity
{
private final String FILE_NAME = "awayReply";
private EditText myEditMessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
protected void onStart()
{
String message = readMessage();
myEditMessage = (EditText)findViewById(R.id.edit_message);
if(myEditMessage != null)
{
myEditMessage.setText(message, TextView.BufferType.EDITABLE);
}
}
XML Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="16dp"
android:paddingTop="16dp" >
<EditText
android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/lbl_message"
android:inputType="textImeMultiLine" />
<Button
android:id="#+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/edit_message"
android:onClick="updateMessage"
android:text="#string/lbl_update" />
<ToggleButton
android:id="#+id/toggle_away"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/lbl_enable"
android:layout_alignBottom="#+id/lbl_enable"
android:layout_toRightOf="#+id/edit_message"
android:textOff="Disabled"
android:textOn="Enabled"
android:onClick="toggleEnabled" />
</RelativeLayout>
You can't set your text in a TextView until you inflate your layout with
setContentView(R.layout.main_activity);
in the Activity's OnCreate
Once that happens you can do:
EditText editText = (EditText)findViewById(R.id.myEditText)
Full Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // this needs to happen first
EditText editText = (EditText)findViewById(R.id.myEditText)
editText.setText("my text", TextView.BufferType.EDITABLE); // <-- needs that second parameter
}
Edit: updated for EditText instead of TextView
I think I figured out my problem. I need to do this work in the PlaceholderFragment where onCreateView is defined. When I call findviewbyid here it dosen't return null.

The method findViewById(int) is undefined for the type Json.SnagInfo

So I set up a main_layout.xml shown below with 3 textviews which I then "setContentView" to the main_layout.xml from MainActivity.java as shown below. I then have methods which will be in Java.class (a seperate class in a seperate package) that won't be an activity but will have methods that will be called from MainActivity. The problem is I'm having trouble accessing any of these resources, each of the three findViewById's in Java.class get highlighted under in red and error states: The method findViewById(int) is undefined for the type Json.SnagInfo
What am I doing wrong?
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/title" />
<TextView
android:id="#+id/author"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/author" />
<TextView
android:id="#+id/release"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/release"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
// Local Variables
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
}
Json.java
public class Json {
TextView title;
TextView author;
TextView release;
ListView published;
ArrayList<HashMap<String, String>> bookList = new ArrayList<HashMap<String, String>>();
public class SnagInfo extends AsyncTask<URL, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
bookList.clear();
title = (TextView) findViewById(R.id.title);
author = (TextView) findViewById(R.id.author);
release = (TextView) findViewById(R.id.release);
}
}
}
findViewById is a method of Activity class. SnagInfo extends AsyncTask.
If you want to the result of background computation in the activity class you can use interface as a Callback.
Now initialize all your views in activity and set the data there.
Check this link
How do I return a boolean from AsyncTask?
You can also make asynctask an inner class of activity and update ui in onPostExecute

Categories