Wormy
Wormy

Reputation: 1

On TextView.setText(string) null pointer exception occurs

I am trying to update some TextViews. I have 3 Layout Main_Activity.XML For default Portrait and Landscape. The TextView in those layouts all have the same andoid:id

I have read everything I can on updating the TextView and have no idea why this is crashing the whole app.

I think maybe TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1) is returning a null and then when I try to setText I get a null pointer exception. Any thoughts? I have put the

TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref); 

In a Button onclick event that occurs long after the setContentView has completed with the same results above. Verified that the id's I am using to reference the TextView exit in all 3 of my layouts.

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    PreferenceManager.setDefaultValues(this, R.xml.preference, false);
    setContentView(R.layout.activity_main);

TextView txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);
}

Upvotes: 0

Views: 1699

Answers (2)

G M Ramesh
G M Ramesh

Reputation: 3412

it seems that the value String strPref = retrievePrefs("pref_active_times_prop1"); is coming null , print that strPref value and check

Upvotes: 0

Ashwin N Bhanushali
Ashwin N Bhanushali

Reputation: 3882

Hi You have to do findViewById inside onCreate method. since you are doing findViewById inside event listener it is returning null.

Do the below mentioned changes in your code.

public class MainActivity extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

PreferenceManager.setDefaultValues(this, R.xml.preference, false);
setContentView(R.layout.activity_main);

txt = (TextView) findViewById(R.id.txtViewActiveTimeProp1);
String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);
}

and inside your click listener

String strPref = retrievePrefs("pref_active_times_prop1");
txt.setText(strPref);

Hope this helps.

Upvotes: 1

Related Questions