应用程序在使用共享首选项时崩溃

时间:2014-02-03 11:21:38

标签: android

如果我在oncreate方法中不使用getstring,我的代码工作没有任何问题。我认为我的应用程序正在崩溃,因为它无法从sharedfile中找到字符串。如何在oncreate方法

中读取共享文件中的内容
    package com.example.com.vyaap.myfirstapp;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    //import android.support.v4.widget.SearchViewCompatIcs.MySearchView;
    import android.view.Menu;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.ImageView;

    public class MainActivity extends Activity {

        public  static String EXTRA_MESSAGE="com.vyaap.myfirstapp.MESSAGE";
        public  static final String PREFS_NAME="MyPrefsFile";
        ImageView image;
        String valid_name=null;
        EditText edittext;
        SharedPreferences settings;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            image =(ImageView) findViewById(R.id.imageView1);
            image.setImageResource(R.drawable.logo);
            settings= getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            if(settings.contains("sharedString")){
            String returnString=settings.getString("sharedString","Couldn't load the data");
            edittext.setText(returnString);
            }

        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {         
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }


        public void sendMessage(View view){
        Intent intent=new Intent(this,DisplayMessageActivity.class);
        edittext =(EditText)findViewById(R.id.edit_message);
        String message=edittext.getText().toString();
        isValidName(message);

        if(valid_name!=null){
        intent.putExtra(EXTRA_MESSAGE,valid_name);
        startActivity(intent);
        }
        }
        public void isValidName(String message){
        if(message.length()<0){
        edittext.setError("Accept alphabates only");    
        valid_name=null;}
        else if(!message.matches("[a-zA-Z]+")){
        edittext.setError("Accept alphabates only");    
        valid_name=null;
        }else{
        valid_name=message; 
        }
        SharedPreferences.Editor editor= settings.edit();
        editor.putString("sharedString",valid_name);
        editor.commit();
        }
    }

0 个答案:

没有答案