在android中使用Sharedpreferences?

时间:2012-10-29 07:04:37

标签: android sharedpreferences

我是Android开发新手,我遇到了一个问题,我需要使用共享首选项。

Main.java

WebServiceInterface webinterface;

ProgressDialog progdial;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    handler     =   new Handler();
    webinterface=   new WebServiceInterface(wslogin);

    submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            getuser = username.getText().toString();
            getpass = password.getText().toString();


        /*****
             * setting values in HASHMAP 
             * 
             * 
             */

            HashMap<String, Object> map =  new HashMap<String,Object>();
            map.put("username", getuser);
            map.put("password", getpass);

            /*****
             * calling sendRequest() method in WebInterface class
             * 
             */
            webinterface.sendRequest(map);

    //for getting values from preferences
       SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
         String getResponse = prefs.getString("responsevalue", "");
       //but its getting error as showing NULLPOINTERException. 
        System.out.Println("response is -----  " + getResponse);
//here i am getting null value for gerResponse. .....               
        }
    });
}

WebInterface.java(只有类不活动)

public class WebServiceInterface{


public WebServiceInterface(String getstring)
{       
    getWebServiceType = getstring;      
}

public void sendRequest(Map<String, Object> map) {
    // TODO Auto-generated method stub

    Collection<Object> strings = map.values();
    Iterator iterator = strings.iterator();
    while (iterator.hasNext()) {
        getuser = (String) iterator.next();
        ast.add(getuser);
    }

    String password = ast.get(0).toString();
    String username = ast.get(1).toString();

  //calling webservice client to request webserivce code
    RestClient client = new RestClient(
            "http://**********************8");
    client.AddParam("username", username);
    client.AddParam("password", password);

    try {
        client.Execute(RequestMethod.POST);
    } catch (Exception e) {
        e.printStackTrace();
    }
      //getting response back from Restclient and saving in response string. 
    String response = client.getResponse();

   //for setting values in preferences
  SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
     SharedPreferences.Editor editor = prefs.edit();
    editor.putString("responsevalue", response);
   editor.commit();


}

以下是我遇到的问题:
我想访问Main.java文件中onCreate块的响应。 在按钮点击方法的Main.java文件中,我需要显示toast,并在Webinterface类中获得以下响应。

任何人都可以帮助我。由于我是Android开发的新手,所以任何小帮助都将受到赞赏。

以下是stacktrace ..

10-29 13:07:44.042: I/global(379): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
10-29 13:07:44.062: D/AndroidRuntime(379): Shutting down VM
10-29 13:07:44.062: W/dalvikvm(379): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-29 13:07:44.072: E/AndroidRuntime(379): FATAL EXCEPTION: main
10-29 13:07:44.072: E/AndroidRuntime(379): java.lang.NullPointerException
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
10-29 13:07:44.072: E/AndroidRuntime(379):  at com.leads.doctorgokhale.Interface.WebServiceInterface.call(WebServiceInterface.java:44)
10-29 13:07:44.072: E/AndroidRuntime(379):  at com.leads.doctorgokhale.Interface.WebServiceInterface.sendRequest(WebServiceInterface.java:39)
10-29 13:07:44.072: E/AndroidRuntime(379):  at com.leads.doctorgokhalenative.Main$2.onClick(Main.java:154)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.view.View.performClick(View.java:2408)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.view.View$PerformClick.run(View.java:8816)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.os.Handler.handleCallback(Handler.java:587)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.os.Looper.loop(Looper.java:123)
10-29 13:07:44.072: E/AndroidRuntime(379):  at android.app.ActivityThread.main(ActivityThread.java:4627)
10-29 13:07:44.072: E/AndroidRuntime(379):  at java.lang.reflect.Method.invokeNative(Native Method)
10-29 13:07:44.072: E/AndroidRuntime(379):  at java.lang.reflect.Method.invoke(Method.java:521)
10-29 13:07:44.072: E/AndroidRuntime(379):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-29 13:07:44.072: E/AndroidRuntime(379):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-29 13:07:44.072: E/AndroidRuntime(379):  at dalvik.system.NativeStart.main(Native Method)
10-29 13:07:44.143: D/dalvikvm(379): GC_FOR_MALLOC freed 3188 objects / 215024 bytes in 64ms

7 个答案:

答案 0 :(得分:0)

试试这个。

Relace

editor.putFloat("responsevalue", response); to below code

editor.putString("responsevalue", response);

您正在尝试将字符串添加到float并返回字符串,因此您会收到错误。

修改:

您在初始化之前正在访问提交(按钮onClick事件),因此请初始化它。对用户名,密码编辑文本执行相同操作。

submit   = (Button)findViewById(R.id.submit);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);

答案 1 :(得分:0)

写下面的代码行

editor.putString("responsevalue", response);

而不是

editor.putFloat("responsevalue", response);

onCreate()之后将以下代码添加到setcontentview();方法中。

username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);

它将解决您的问题。

答案 2 :(得分:0)

使用

  

putString

而不是

  

putFloat

答案 3 :(得分:0)

我的猜测是prefNamenull。 <{1}}不应该为空,因为你给它一个空字符串的后备。

答案 4 :(得分:0)

试试这个

SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    if (response == null)
        editor.putString("responsevalue", "response is null");
    else
        editor.putString("responsevalue", response);
    editor.commit();

答案 5 :(得分:0)

中执行prefName
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);

持有任何合理的价值,还是未初始化的变量?

答案 6 :(得分:0)

从Main.java(Activity)

将Context对象传递给WebInterface
webinterface=   new WebServiceInterface(this,wslogin);

将构造函数更改为:

Context mContext;
public WebServiceInterface(Context context, String getstring)
{       
    mContext =context;
    getWebServiceType = getstring;      
}

从WebServiceInterface显示toast:

 String response = client.getResponse();
 Toast toast = Toast.makeText(mContext, response, duration);
 toast.show();