Reputation: 3
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://schemas.android.com/apk/res/android"
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!
Upvotes: 0
Views: 106
Reputation: 38
String name;
static String EXTRA_NAME;
EditName = (EditText) findViewById(R.id.name);
name = EditName.getText().toString();
Intent.putExtra("EXTRA_NAME", name);
you will have the EditName (what user inputs)in the string name and you can also put the string name in a static string EXTRA NAME if you want to send that to another class...or you can create a separate class that can be used as object ..with getters and setters
or maybe you have to set text view in the xml file android:text="name"
Upvotes: 0
Reputation: 152867
The NPE is on the preceeding line. You haven't initialized your mainSharedPreferences
object.
Upvotes: 1