In my Android app, I'm trying to display a personalized message "Welcome, [name]!" when the app starts up. Through error logs I've determined that I successfully save a user's name after he/she is prompted to give it, and successfully retrieve that name on subsequent startups. But when I try to change the default "Welcome!" to "Welcome, [name]!" using settext, I get a null pointer exception.
My XML (activity_main.xml)
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFC2"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<TextView
android:id="@+id/main_textview"
android:text="Welcome!"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="40sp"
android:typeface="serif"/>
</RelativeLayout>
And my Java
public class main extends Activity {
TextView mainTextView;
private static final String PREFS = "prefs";
private static final String PREF_NAME = "name";
SharedPreferences mainSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainTextView = (TextView) findViewById(R.id.main_textview);
String name = mainSharedPreferences.getString(PREF_NAME, "");
if(name.length() > 0){mainTextView.setText("Welcome, " + name + "!" );}
else{greeting();}
}
}
Based on other, similar posts, I've tried making sure I'm using setContentView on the xml file that contains the relevant TextView, and I've tried cleaning and rebuilding the project. It still gives me a NullPointerException. Any help would be greatly appreciated!
No comments:
Post a Comment