Domanda

I'm making this program that requires a username to run. In the settings, the intent worked fine until I added the Shared Preferences code. I might have added it in the wrong place. Otherwise the intent was working absolutely fine. Also the share preferences is not saving the string. It keeps on crashing. Any ideas?

package com.XXX.XXX;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Settings extends Activity{

EditText nameXML;
SharedPreferences filename;
public  String name;
String filenamename = "nameFile";
Button save = (Button) findViewById(R.id.button1);

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    nameXML = (EditText) findViewById(R.id.editText1);
    filename = getSharedPreferences(filenamename,0);
    String username = filename.getString("nameString", "Master Traders");
    nameXML.setHint(username);
    name = nameXML.getText().toString();
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Editor nameEditor = filename.edit();
            nameEditor.putString("nameString", name);
            nameEditor.commit();
        }
    });
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

}




}
È stato utile?

Soluzione

Button save = (Button) findViewById(R.id.button1);

change to:

    Button save;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        save  = (Button) findViewById(R.id.button1);//this line is before onclicklistener.
 save.setOnclickListner(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            name = nameXML.getText().toString(); 
            Editor nameEditor = filename.edit();
            nameEditor.putString("nameString", name);
            nameEditor.commit();
        }
    });
    }

You should post logcat the further see what the problem is. But most likely is due to what @Reid proposed. The new updated code is added.

Altri suggerimenti

You're creating an editText and only supplying it with a hint, then attempting to get the contents from it all in the onCreate(). You need to get the Text from the editText when the user has clicked save. So try putting

name = nameXML.getText().toString();

Inside the onClickListener.

otherwise you're attempting to get a string from an empty editText.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top