Expected BEGIN_ARRAY but was BEGIN_OBJECT | ArrayList issue - android

I'm using the Gson library to save and retrieve an ArrayList of Players Objects.
My onStop()
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String guardJSON = gson.toJson(playersNoGuard);
editor.putString(GUARD, guardJSON);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
My onCreate important part
ArrayList<Player> playersNoGuard;
RecyclerView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_players_guard);
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
String guardJSON = prefs.getString(GUARD, null);
Type arrayListPlayers = new TypeToken<ArrayList<Player>>(){}.getType();
Gson gson = new Gson();
if(guardJSON != null) {
playersNoGuard = gson.fromJson(guardJSON, arrayListPlayers);
}
// Get the players and remove the Clairvoyant
Intent intent = this.getIntent();
playersNoGuard = intent.getParcelableArrayListExtra("PLAYERS");
[...] // Code skipped
}
But when this Activity is run, I get the following error log:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
What's wrong in this code?

You probably write to the same preferences entry somewhere else. Ensure that your key (GUARD) is unique throughout the application.

The problem is with your Response while Gson converting a response it expected Array in response but in your response you have made you are passing Object.
This is already answered here and here
here is reverse situation described.

Related

How to send the response to new activity?

I want to pass my API response to another activity . I am using intent but getting null in the next activity .
My code is MainPage.java
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
}
I am getting the correct response .
Calculation.java
Intent intn = new Intent();
members = intn.getStringExtra("MEMBERS");
System.out.println("dmkmdk"+members);
//no_of_members = Integer.parseInt(members);
I also want to parse it in integer form .
you should get extra like this, don't initiate an intent object
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("MEMBERS");
Try to save data in SharedPreference instead Intent.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("MEMBERS",members);
editor.apply();
For retriving data:-
editor.getString("MEMBERS", null); // getting String
Please try this
To Transfer data in next activity
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
startActivity(intn)
}
In New activity where you want to get data try this line
String resFromLast = getIntent().getExtras().getString("MEMBERS");
Log.e("Response From last activity is :" ,resFromLast);
MEMBERS is that key you passed in last activity with intent.
Hope it works.

Error while accessing Shared Preference of my App

I am not able to access shared preference data. I have already checked in another URL for this error. Error is...
remove failed: ENOENT (No such file or directory) : /data/data/com.example.lenovo.sms/shared_prefs/refresh_token.xml.bak
Code for storing and accessing data in shared preference
private void saveToken(String recent_token) {
saveTokenPref = getSharedPreferences(Config.SAVE_TOKEN_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveTokenPref.edit();
editor.putString(Config.TAG_TOKEN,recent_token);
editor.commit();
}
public String getSavedToken() {
saveTokenPref = getSharedPreferences(Config.SAVE_TOKEN_FILE,Context.MODE_PRIVATE);
String saved_token = saveTokenPref.getString(Config.TAG_TOKEN,"");
Log.d("save token",saved_token);
return saved_token;
}
In onCreate():
saveTokenPref = PreferenceManager.getDefaultSharedPreferences(this);
Then, use the below codes:
private void saveToken(String recent_token) {
SharedPreferences.Editor editor = saveTokenPref.edit();
editor.putString("token",recent_token);
editor.commit();
}
public String getSavedToken() {
String saved_token = saveTokenPref.getString("token","");
Log.d("save token",saved_token);
return saved_token;
}
Hope this helps.

How to refresh/Update Serialize Java Object in sharedPreferences

For storing the serilaizable java object i m using below code
if(sharedpreferences.getString(ComplexObjectXMl,"")!=null) {
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject .class, sharedpreferences.getString(ComplexObjectXMl,""));
} catch (Exception e) {
e.printStackTrace();
}
Intent i1 = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i1);
}
new MyAsyncTask().execute();
In MyAsyncTask i m storing the XmlDataOverHttp in sharedPreferences. Will it get updated everytime if i like do this
you can compare byte array of those object. one coming from shared preference and other which is latest.
byte[] array = new Gson().toJson(latestObject).getBytes(); //your lattest byte array
byte[] secondArray = new Gson().toJson(objectConvertedFromSharedPreferenceOLD).getBytes();
if (Arrays.equals(array, secondArray))
System.out.println("They are same");
else
System.out.println("Nope...");
and as you said you can use service or shared preference to check hourly update in oncreateView() but it only happens when user open your app(between hour it will call api for list items)
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
long lastUpdateTime = mSettings.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (3600000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
SharedPreferences.Editor editor = mSettings.edit();
lastUpdateTime = System.currentTimeMillis();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Start Update for listview your URL to fetch data and then you can check and compare object
also you can use swipeRefreshLayout so user can also refresh data*/
//asyncRequestTime.execute(URL);
}

Issue reading data from sharedpreferences. I have to run the app twice before it gets the data stored

I have an issues reading from sharedpreferences in android. The data is stored in the preference file, and i ma sure of this because i used logcat to log the data when i read it back IMMEDIATELY as it was stored as well as i used a toast message to display the data after i read it back from preferences. However when i try to read the data again from a new activity it returns the default of an empty sting. When i exist the app and run it again it read the data that was previously stored. Here is my code for when i initially save the data, it also contains the comments i used to verify that the data stored was read back:
public void downloadMatchesAsync() {
brawtaAPIAdapter.runGetMatches(new Callback<JSONKeys>() {
#Override
public void success(JSONKeys jsonKeys, Response response) {
Log.d(ApplicationConstants.TAG, "blarg");
Success = jsonKeys.isSuccess();
message = jsonKeys.getErrorMessage().toString();
if(!message.isEmpty()){
Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
}
Gson gson = new Gson();
String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'
Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
//data =Preferences.readFromPreferences(activity, ApplicationConstants.match_data, "no data");
//Toast.makeText(MyApplication.getAppContext(), "In networkOperation" + data, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
}
}); // Call Async API
//return data;
}
In a different activity i try to read the data previously written like so:
jsonString = Preferences.readFromPreferences(MatchSelect.this, ApplicationConstants.match_data, "");
but the code only returns the data stored if i exist the app and run it again.
this is my preference class:
public class Preferences {
private static final String PrefName = "net.brawtasports.brawtasportsgps";
public static void saveToPreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String readFromPreferences(Context context, String key, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
}
What is the issue?
apply() is an asynchronous call, so the data doesn't have to be stored immediately. Try calling .commit() instead.

How to perform two operations on one activity in android

I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need

Categories

Resources