My application got crashed because of not initializing the view

后端 未结 3 352
孤独总比滥情好
孤独总比滥情好 2021-01-29 15:07

Here, i am trying to call setText method but my application is getting crashed because of some initialization problem.

EditText edittext;
    SharedPreferences          


        
相关标签:
3条回答
  • 2021-01-29 15:42

    edittext is not initialized. Initialize it in onCreate.

    In onCreate you have

    edittext.setText(returnString); // not initialized in onCreate
    

    You have

    edittext =(EditText)findViewById(R.id.edit_message); // initialized in sendMessage
    

    in sendMessage. So you may be setting text to edittext even before it is initialized

    0 讨论(0)
  • 2021-01-29 15:51

    Please try with the code.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image =(ImageView) findViewById(R.id.imageView1);
        image.setImageResource(R.drawable.logo);
        edittext = (EditText)findViewById(R.id.edittext);        
        settings= getBaseContext().getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("sharedString", "Shared Preference Data");
        editor.commit();
        String returnString=settings.getString("sharedString","Couldn't load the data");
        edittext.setText(returnString);
    }
    

    Before to use the code first look about thee shared Preferences and their examples.

    SharedPreference

    SharedPreferences Example

    Hope it should work. Please let me know.If it not working means tell me what you want to do actually.

    0 讨论(0)
  • 2021-01-29 15:55

    its a very common mistake .. I should initialize the editText before calling a method on it by

    edittext =(EditText)findViewById(R.id.edit_message);

    0 讨论(0)
提交回复
热议问题