开发者

Android SharedPreferences crashing when storing a string with a quotation mark

I am having some trouble with shared preferences. I am attempting to save the text of a search box (an edit text) before an orientation change, and then reinstate it after the activity is recreated following the orientation change. It works like a charm.... except when the edit text contains a quotation mark. When there is a quotation mark and I rotate the device, the app crashes when trying to create the activity in the new orientation. This ONLY symbol this happens when there is a double quote ", all other symbols, including the single quote ', work just fine.

The error I get is android.database.sqlite.SQLiteException: unrecognized token: "" ORDER BY name COLLATE NOCASE". My guess is that the " is interfering with the way SQL queries are written. I tried replacing all " with \" before storing them in the SharedPreferences and then replacing all \" with " when getting the string back out. I still get this same problem. Anyone know how to fix this?

My code is as follows:

@Override
public void onResume()
{
    super.onResume();
    String searchText = f_sharedPreferences.getString("searchText", "");
    f_searchBox.setText(searchText);
}

@Override
public void onPause()
{
    super.onPause();
    String searchText = f_searchBox.开发者_运维知识库getText().toString();
    f_sharedPreferences.edit().putString("searchText", searchText).commit();
}

Thanks! Your help is very much appreciated.

EDIT: In my onCreate method, I get f_sharedPreferences with the following line:

    f_sharedPreferences = getSharedPreferences(this.getClass().getName(), Context.MODE_PRIVATE);

Also, I cannot use android:configChanges="orientation" as it interferes with other functionality.


You can try escaping the characters of your string with sqlEscapeString from DatabaseUtils (not tested, just found it on google)


Seems like an Android problem. Why not just add this attribute to the Activity part of your Manifest? It will make the text save so you don't have to store it.

android:configChanges="orientation"

Just keep in mind that this will disable the default way that Android handles rotations, so if you rely on using different layouts for portrait/landscape, you may wish to use another approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜