This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 6 years ago.
I am writing a piece of code which displays in an expandable list using information from an AsyncTask and a pre defined HashMap. But it is throwing java.util.ConcurrentModificationException. My code is as follows:
AsnycTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
ArrayList<String> name;
ArrayList<Integer> quantity;
Map<String, Map<String, Integer>> cart_names1 = new HashMap<String, Map<String, Integer>>();
public BackTask(ArrayList<String> name, ArrayList<Integer> quantity) {
this.name = name;
this.quantity = quantity;
}
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ha);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... arg0) {
InputStream is = null;
String result = "";
try {
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b) + "&";
}
for (int a = 0; a < quantity.size(); a++) {
link += "quantities[]" + "=" + quantity.get(a);
if (a != quantity.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null) pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
temmap.put("Second", jsonObject.getInt("Second"));
temmap.put("Third", jsonObject.getInt("Third"));
Log.e("ERROR", temmap.get("First").toString());
cart_names1.put(temname, temmap);
}
strhold2.clear();
strhold2.add("First");
strhold2.add("Second");
strhold2.add("Third");
String[] strhold1 = new String[strhold2.size()];
for (int i56 = 0; i56 < strhold2.size(); i56++) {
strhold1[i56] = strhold2.get(i56);
}
System.out.println(cart_names1);
Log.e("ERROR", Integer.toString(cart_names1.size()) + "IN LATEST");
if (cart_names1.size() > 1) {
System.out.println(cart_names1.size());
System.out.println(strhold2.size());
Combination.printCombination(cart_names1, strhold1, strhold2.size(), cart_names1.size(), 2);
ArrayList<String> wrong = Permutation.getlist();
System.out.println(wrong + "this is final");
setalldata(wrong);
System.out.println(wrong);
couldthis.clear();
couldthis.addAll(wrong);
} else {
Single_Permutation.getpermute(cart_names1);
System.out.println(Single_Permutation.singlelist);
couldthis.clear();
couldthis.addAll(Single_Permutation.singlelist);
setalldata(Single_Permutation.singlelist);
Log.e("ERROR", "thisis the list 1" + getdataformap());
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
/*SetMap setMap = new SetMap(getdataformap());
setMap.execute();*/
if (pd != null){ pd.dismiss();}
ListFragment.addtolist(getdataformap());
Log.e("ERROR", "This is putmap i" + getdataformap());
SetMap setMap =new SetMap(getdataformap());
setMap.execute();
}
}
}
Fragment(with expandable list)
public static class ListFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static ExpandableListView expandablelistview;
public static CustomExpandableListAdapter expandableadapter;
public static HashMap<Fitems, List<Fnitems>> datapforput = new HashMap<>();
public static List<Fitems> mainforput = new ArrayList<>();
public static View view;
public static Context getha;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.activity_listfragment, container, false);
//doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result) getActivity()).getha(), mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
getha = ((Result) getActivity()).getha();
return view;
}
#Override
public void onStart() {
super.onStart();
Permutation.finallist = new ArrayList<>();
Single_Permutation.singlelist = new ArrayList<>();
/* doddata();
expandablelistview = (ExpandableListView) view.findViewById(R.id.expandableListView);
expandableadapter = new CustomExpandableListAdapter(((Result)getActivity()).getha(),mainforput,datapforput);
expandablelistview.setAdapter(expandableadapter);*/
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static void doddata() {
Fitems fitems1 = new Fitems();
Fitems fitems2 = new Fitems();
Fnitems fnitems1 = new Fnitems();
Fnitems fnitems2 = new Fnitems();
Fnitems fnitems3 = new Fnitems();
Fnitems fnitems4 = new Fnitems();
fitems1.setName("AAA");
fitems2.setName("BBB");
fnitems1.setName("AAAa");
fnitems2.setName("AAAb");
fnitems3.setName("BBBa");
fnitems4.setName("BBBb");
List<Fnitems> listfnitem1 = new ArrayList<>();
List<Fnitems> listfnitem2 = new ArrayList<>();
listfnitem1.add(fnitems1);
listfnitem1.add(fnitems2);
listfnitem2.add(fnitems3);
listfnitem2.add(fnitems4);
datapforput.put(fitems1, listfnitem1);
datapforput.put(fitems2, listfnitem2);
mainforput.add(fitems1);
mainforput.add(fitems2);
//Log.e("ERROR", "thisis the list for god's sake " + Result.couldthis+datapforput.toString());
if (Result.couldthis.size() > 0) {
for (int i = 0; i < (Result.couldthis).size(); i++) {
for (Map.Entry<Fitems, List<Fnitems>> entry : datapforput.entrySet()) {
if (Result.couldthis.get(i).equals(entry.getKey().getName())){
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
entry.getValue().add(fnitems5);
}else {
Fitems fitems3 = new Fitems();
fitems3.setName(Result.couldthis.get(i));
Fnitems fnitems5 = new Fnitems();
fnitems5.setName(Search_multiple.cart_records.get(i).getName());
List<Fnitems> listfnitem3 = new ArrayList<>();
listfnitem3.add(fnitems5);
datapforput.put(fitems3, listfnitem3);
mainforput.add(fitems3);
}
}
}
}
}
public static ListFragment newInstance() {
ListFragment fragment = new ListFragment();
Log.e("ERROR", "man .... " + fragment.getTag());
return fragment;
}
public static void addtolist(ArrayList<String> dataforputting) {
// Log.e("ERROR", "thisis the list 3" + (dataforputting));
//if (expandableadapter != null){
expandableadapter.clear();//}
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
doddata();
//Log.e("INFO", "This is mainforput" + mainforput + "This is dataforput" + datapforput);
expandableadapter = new CustomExpandableListAdapter(getha, mainforput, datapforput);
expandablelistview.setAdapter(expandableadapter);
}
}
Stack
07-13 18:16:11.955 17339-17339/nf.co.riaah.chutte E/ERROR: Inside populate Second
07-13 18:16:11.986 17339-17339/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 17339
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$EntryIterator.next(HashMap.java:824)
at java.util.HashMap$EntryIterator.next(HashMap.java:822)
at nf.co.riaah.chutte.Result$ListFragment.doddata(Result.java:199)
at nf.co.riaah.chutte.Result$ListFragment.addtolist(Result.java:230)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:1049)
at nf.co.riaah.chutte.Result$SetMap.onPostExecute(Result.java:967)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
This means that you're modifying a collection while trying to iterate over it. It could be all in the same place or it could be from different threads.
for each loop are generally fail fast , that you can 't change the collection ( as for each internally use iterator ) .
instead of using " for (Map.Entry> entry : datapforput.entrySet()) "
create an iterator and then iterate over map again , don't forget to assign
iterator reference to newly created entrySet . just reassign iterartor reference each time in while / for whichever loop you use to iterate .
}
Related
I am beginner in Java and Android. I searched yesterday a whole day for a solution. I want to check a variable in second activity if it is filled. Or ask the methode "loadAngebote" if it has a return value. The methode that is executed to get data is:
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/file.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
return dataList; <--------------------------------------------
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
I need to check if dataList is filled in an other class of my app:
static String getLocationResultTitle(Context context, List<Location> locations) {
if(?????dataList_is_filled?????){
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
Updated Answer
Here is your AngeboteActivity
public class AngeboteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>> {
String data = "";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params) {
try {
URL url = new URL("http://url/file.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i = 0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €", "Von: " + all_von[i], "Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult) {
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
}
And Here is your Utils class
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}
Ok now Your Activity looks good..
Now in Utils class change if(loadAngebote.DataHolder.hasData()) to if (AngeboteActivity.DataHolder.hasData())
Here:-
public class Utils {
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
} else {
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
}
UPDATED ANSWER My Angebote Activity:
public class AngeboteActivity extends AppCompatActivity {
public static TextView data;
public static ListView mListView;
private static final String TAG = "AngeboteActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_angebote);
data = (TextView) findViewById(R.id.data);
mListView = (ListView) findViewById(R.id.listView);
new loadAngebote().execute();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object Inhalt = parent.getAdapter().getItem(position);
final Intent intent = new Intent(AngeboteActivity.this, AngeboteRequestInfoActivity.class);
Bundle bundle = new Bundle();
//Objekt Serialisieren
bundle.putSerializable("object", (Serializable) Inhalt);
//Objekt in Intent Extras packen
intent.putExtras(bundle);
AngeboteActivity.this.startActivity(intent);
}
});
}
private class QueryResult {
ArrayList<ArtikelAngebot> dataList;
public QueryResult(ArrayList<ArtikelAngebot> dataList) {
this.dataList = dataList ;
}
}
public enum DataHolder {
INSTANCE;
private ArrayList<ArtikelAngebot> mObjectList;
public static boolean hasData() {
return INSTANCE.mObjectList != null;
}
public static void setData(final ArrayList<ArtikelAngebot> objectList) {
INSTANCE.mObjectList = objectList;
}
public static ArrayList<ArtikelAngebot> getData() {
final ArrayList<ArtikelAngebot> retList = INSTANCE.mObjectList;
INSTANCE.mObjectList = null;
return retList;
}
}
public class loadAngebote extends AsyncTask<String, Void, ArrayList<ArtikelAngebot>>{
String data ="";
#Override
protected ArrayList<ArtikelAngebot> doInBackground(String... params){
try
{
URL url = new URL("http://url/request.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
}
JSONArray json = new JSONArray(data);
String[][] matrix = new String[json.length()][6];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
matrix[i][0] = String.valueOf(obj.getInt("ID"));
matrix[i][1] = String.valueOf(obj.getInt("art_nr"));
matrix[i][2] = String.valueOf(obj.getDouble("preis"));
matrix[i][3] = obj.getString("von");
matrix[i][4] = obj.getString("bis");
matrix[i][5] = obj.getString("art_link");
}
String[] all_ID = new String[matrix.length];
String[] all_art_nr = new String[matrix.length];
String[] all_preis = new String[matrix.length];
String[] all_von = new String[matrix.length];
String[] all_bis = new String[matrix.length];
String[] all_link = new String[matrix.length];
for (int i = 0; i < matrix.length; i++) {
all_ID[i] = matrix[i][0];
all_art_nr[i] = matrix[i][1];
all_preis[i] = matrix[i][2];
all_von[i] = matrix[i][3];
all_bis[i] = matrix[i][4];
all_link[i] = matrix[i][5];
}
ArrayList<ArtikelAngebot> dataList = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
ArtikelAngebot angebote = new ArtikelAngebot(all_art_nr[i], "Für: " + all_preis[i] + " €","Von: " + all_von[i],"Bis: " + all_bis[i], all_link[i]);
dataList.add(angebote);
}
DataHolder.setData(dataList);
return dataList;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<ArtikelAngebot> QueryResult){
AngeboteListAdapter adapter = new AngeboteListAdapter(AngeboteActivity.this, R.layout.angebote_list_view_adapter, QueryResult);
mListView.setAdapter(adapter);
}
}
My Utils.java class
public class Utils {
final static String KEY_LOCATION_UPDATES_REQUESTED = "location-updates-requested";
final static String KEY_LOCATION_UPDATES_RESULT = "location-update-result";
static void setRequestingLocationUpdates(Context context, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_LOCATION_UPDATES_REQUESTED, value)
.apply();
}
static boolean getRequestingLocationUpdates(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_LOCATION_UPDATES_REQUESTED, false);
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
static void sendNotification(Context context, String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(context, AngeboteActivity.class);
notificationIntent.putExtra("from_notification", true);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(AngeboteActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
// Notification Einstellungen
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle("Ihre Apotheke vor Ort")
.setContentText(notificationDetails)
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Returns the title for reporting about a list of {#link Location} objects.
*
* #param context The {#link Context}.
*/
static String getLocationResultTitle(Context context, List<Location> locations) {
if (AngeboteActivity.DataHolder.hasData()) {
//if hasData do your stuff what you want
String numLocationsReported = "Text1";
return numLocationsReported + " \r\n \r\n :) \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}else{
String numLocationsReported = "Text2";
return numLocationsReported + " \r\n \r\n :( \r\n \r\n" + DateFormat.getDateTimeInstance().format(new Date());
}
}
/**
* Returns te text for reporting about a list of {#link Location} objects.
*
* #param locations List of {#link Location}s.
*/
private static String getLocationResultText(Context context, List<Location> locations) {
if (locations.isEmpty()) {
return "Unbekannte Position";
}
StringBuilder sb = new StringBuilder();
for (Location location : locations) {
sb.append("(");
sb.append(location.getLatitude());
sb.append(", ");
sb.append(location.getLongitude());
sb.append(")");
sb.append("\n");
}
return sb.toString();
}
static void setLocationUpdatesResult(Context context, List<Location> locations) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(KEY_LOCATION_UPDATES_RESULT, getLocationResultTitle(context, locations)
+ "\n" + getLocationResultText(context, locations))
.apply();
}
static String getLocationUpdatesResult(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY_LOCATION_UPDATES_RESULT, "");
}
}
I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}
I have a JSON like this
{
"questions": [{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
},
{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
}
]
}
I have added values of lets suppose "Answer_Video_Link" into Arraylist for e.g arraylistAnswerLink so the output will be like[null,null,....so on]
As setting this arraylist in a BaseAdapter,the functionality is want to achieve is:
if(arraylistAnswerLink.get(position).contains(null)){
button.setVisibilty(View.Visible)}
else{
button.setVisibilty(View.Gone)
}
This my json parsing code
jsonInnerArray = jsonInnerObject.getJSONArray("questions");
for (int j = 0; j <= jsonInnerArray.length(); j++) {
jsonArrayObject = jsonInnerArray.getJSONObject(j);
Question_Video_Title = jsonArrayObject.getString("Question_Video_Title");
question_video_playingTime = jsonArrayObject.getString("question_video_playingTime");
String Designation1 = jsonArrayObject.getString("Designation");
full_name = jsonArrayObject.getString("User_name"); Question_Video_Link = jsonArrayObject.getString("Question_Video_Link");
Answer_Video_Link = jsonArrayObject.getString("Answer_Video_Link");
QuestionID = jsonArrayObject.getString("QuestionID");
video_thumbnail=jsonArrayObject.getString("video_thumbnail"); }
am having error of array index out of bound while fetching null at a particular position of the list.
Please check my code
public class UnRepliedFragment_ extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
View rootview;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// ArrayList<Integer> arrayListImage;
ArrayList<Integer> arrayListVideos;
File mediaFile, vPath;
String song_dur_str, st, vst, vst1, orginalName;
String timestamp, advisorID, token;
int VIDEO_CAPTURE = 1000;
ProgressDialog dlg;
SharedPreferences preferences;
ArrayList<String> arrayListName, videoName, singleVideoName, questionLink, arrquestion_video_playingTime, answerLinkEmpty;
String FirstName, durationofVideo, User_name, Question_Video_Title, Question_Video_Link, shorted, cmpsort, question_video_playingTime, path, QuestionID;
int advisor, pos;
private List<Modals> feedsList;
Uri mediaPath;
PutObjectRequest por;
String url = "https://s3-us-west-1.amazonaws.com/talentedge1";
private static AmazonS3Client sS3Client;
Uri fileUri;
static Object Answer_Video_Link;
ArrayList<Object> answerLink;
Object item;
JSONObject jsonObject,innerObject;
JSONArray innerArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_unreplied, container, false);
dlg = new ProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
token = preferences.getString(AppConstant.TOKEN, "");
advisorID = preferences.getString(AppConstant.USERID, "");
arrayListVideos = new ArrayList<>();
feedsList = new ArrayList<>();
arrayListName = new ArrayList<>();
videoName = new ArrayList<>();
questionLink = new ArrayList<>();
arrquestion_video_playingTime = new ArrayList<>();
answerLink = new ArrayList<>();
singleVideoName = new ArrayList<>();
/*
API hit
*/
new Proadvice().execute();
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view_unreplied);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootview;
}
/*
Adapter class
*/
class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
ArrayList<String> videoName;
ArrayList<String> questionLink;
ArrayList<String> arrquestion_video_playingTime;
ArrayList<Object> answerLink;
public MyRecyclerViewAdapter(ArrayList<String> videoName, ArrayList<String> questionLink, ArrayList<Object> answerLink, ArrayList<String> arrquestion_video_playingTime) {
this.videoName = videoName;
this.questionLink = questionLink;
this.answerLink = answerLink;
this.arrquestion_video_playingTime = arrquestion_video_playingTime;
}
#Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.unreplied_list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
holder.txt_it_author.setText(arrayListName.get(position));
holder.textView.setText(arrquestion_video_playingTime.get(position));
holder.txt_it_Title.setText(videoName.get(position));
for (Object value : answerLink) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
#Override
public int getItemCount() {
return videoName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView, txt_it_author, txt_it_Title, share;
RippleView relativeLayout;
LinearLayout imageButtonAnswer;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = (RippleView) itemView.findViewById(R.id.relative_video_it);
relativeLayout.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.img_it_Video);
textView = (TextView) itemView.findViewById(R.id.txt_it_duration);
txt_it_author = (TextView) itemView.findViewById(R.id.txt_it_author);
txt_it_Title = (TextView) itemView.findViewById(R.id.txt_it_Title);
imageButtonAnswer = (LinearLayout) itemView.findViewById(R.id.img_answers);
frameLayout = (FrameLayout) itemView.findViewById(R.id.relative_play_img);
imageButtonAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
int id = v.getId();
switch (id) {
case R.id.relative_play_img:
Intent i = new Intent(getActivity(), Video_ViewAct.class);
i.putExtra("position", "" + position);
i.putExtra("Question_Video_Link", questionLink.get(position));
// i.putExtra("Answer_Video_Link", answerLink.get(position));
startActivity(i);
break;
}
}
}
}
class Proadvice extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return doInLoginProadvice();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dlg.setMessage("Loading.....");
dlg.setCancelable(false);
dlg.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (result.contains("true")) {
updateUIProadvice(result);
}
}
}
private void updateUIProadvice(String result) {
try {
jsonObject = new JSONObject(result);
String message = jsonObject.getString("message");
innerObject = jsonObject.getJSONObject("Object");
innerArray = innerObject.getJSONArray("details");
// Log.e("arr", " " + arr);
for (int i = 0; i <= innerArray.length(); i++) {
JSONObject obj = innerArray.getJSONObject(i);
String advisorID = obj.getString("AdvisorID");
FirstName = obj.getString("FirstName");
String LastName = obj.getString("LastName");
String Email = obj.getString("Email");
String Password = obj.getString("Password");
String Designation = obj.getString("Designation");
String Company = obj.getString("Company");
String Location = obj.getString("Location");
String Description = obj.getString("Description");
String Profile_Pic_Small = obj.getString("Profile_Pic_Small");
String Profile_Pic_Original = obj.getString("Profile_Pic_Original");
String No_Questions = obj.getString("No_Questions");
String No_Answers = obj.getString("No_Answers");
String No_Up_Votes = obj.getString("No_Up_Votes");
String No_Followers = obj.getString("No_Followers");
String IsActive = obj.getString("IsActive");
String Created = obj.getString("Created");
String Modified = obj.getString("Modified");
JSONArray arr1 = innerObject.getJSONArray("questions");
for (int j = 0; j <= arr1.length(); j++) {
JSONObject obj1 = arr1.getJSONObject(j);
Question_Video_Title = obj1.getString("Question_Video_Title");
question_video_playingTime = obj1.getString("question_video_playingTime");
String Designation1 = obj1.getString("Designation");
User_name = obj1.getString("User_name");
Question_Video_Link = obj1.getString("Question_Video_Link");
shorted = Question_Video_Title.replace("=", " ");
cmpsort = shorted.replace("-", " ");
Answer_Video_Link = obj1.get("Answer_Video_Link");
QuestionID = obj1.getString("QuestionID");
videoName.add((cmpsort));
questionLink.add(Question_Video_Link);
answerLink.add(Answer_Video_Link);
arrayListName.add(User_name);
arrquestion_video_playingTime.add(question_video_playingTime);
mAdapter = new MyRecyclerViewAdapter(videoName, questionLink, answerLink, arrquestion_video_playingTime);
mRecyclerView.setAdapter(mAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String doInLoginProadvice() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConstant.getAdvivisorDetail);
httppost.addHeader("APIKEY", "123ABC890567");
httppost.addHeader("Token", token);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("AdvisorID", advisorID));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
Here is the Simple Way to Parse JSON array and easily get Null as well as a value pair . Important Thing Do not use variable name as a capital letter it must be start with lower case.
please find programme and you can modify it according to Your Requirement
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class UnRepliedFragment_ {
//Define this as a global varraible
static Object Advisor_User_ID;
static Object Creator_User_ID;
static Object Question_Video_Title;
static Object playing_time;
static Object Created;
static Object Modified;
static Object question_video_playingTime;
static Object Answer_Video_Title;
static Object Answer_Video_Link;
static Object answer_video_playingtime;
static Object StatusName;
static Object QuestionID;
static ArrayList al;
public void onBindViewHolder() {
for (Object value : al) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
private void updateUIProadvice(String result) {
//Since i have an limited JSON so Accroding to that i did parsing . Dont try with getString just try with Get();//method
try {
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(result);
org.json.simple.JSONArray lang = (org.json.simple.JSONArray) jsonObject.get("questions");
for (int i = 0; i < lang.size(); i++) {
}
Iterator i = lang.iterator();
while (i.hasNext()) {
org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next();
Creator_User_ID = innerObj.get("Creator_User_ID").toString();
Advisor_User_ID = innerObj.get("Advisor_User_ID");
Question_Video_Title = innerObj.get("Question_Video_Title");
playing_time = innerObj.get("playing_time");
Created = innerObj.get("Created");
Modified = innerObj.get("Modified");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
Answer_Video_Link = innerObj.get("Answer_Video_Link");
answer_video_playingtime = innerObj.get("answer_video_playingtime");
StatusName = innerObj.get("StatusName");
QuestionID = innerObj.get("QuestionID");
// Storing data into arrayList
al = new ArrayList();
al.add(Creator_User_ID);
al.add(Advisor_User_ID);
al.add(Question_Video_Title);
al.add(playing_time);
al.add(Created);
al.add(Modified);
al.add(question_video_playingTime);
al.add(Answer_Video_Link);
al.add(Answer_Video_Title);
al.add(answer_video_playingtime);
al.add(QuestionID);
al.add(StatusName);
// First Way to get element one by one
for (Object value : al) {
if (value != null) {
System.out.println("Not Null:" + value);
} else {
System.out.println("Null:" + value);
}
}
//or Second Way
Object valuenext=al.get(0); // Get First Index Value
System.out.println(valuenext);
}
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
I have an ArrayList listwriter which I populate using this AsyncTask.
class LoadAllGamesWhenNull extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "","",Teams));
Log.d("map", map.toString());
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
finaloutcomess = finaloutcomes.toString();
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
listwriter.get(p).setActualselections(finalhash.toString());
listwriter.get(p).setUserselections(userhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")) {
listwriter.get(p).setStatus("open");
} else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
if (currentitem.getStatus().equals("open")) {
} else {
if (currentitem.getStatus().equals("won")) {
valuechange = valuechange + currentitem.getReturns() - (currentitem.getStake());
}
String c = currentitem.getId() + "," + currentitem.getStatus() + "//";
updateparam = updateparam + c;
Log.d("UPDATEPARAM1", updateparam);
}
}
}
}
Log.d("Listwriterbefore",listwriter.toString());
session.setListwriter(listwriter);
new UpdateBetStatus().execute();
Intent g = new Intent(loadingscreen.this,DisplayAllBets.class);
startActivity(g);
finish();
}}
This is done on my loadscreen Activity and I want to set the listwriter to my SharedPreferences so that I can use it in another Activity. This is my session manager class. The logging in the AsyncTask shows me that the listwriter gets populated correctly. However, when I call on the getlistwriter in my other class I receive an empty ArrayList. I can't see where the error is.
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "AndroidHiveLogin";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public static final String USERNAME = "username";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public ArrayList<BetDisplayer> getListwriter() {
return listwriter;
}
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = listwriter;
}
public void setLogin(boolean isLoggedIn, String username) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.putString(USERNAME, username);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(USERNAME, pref.getString(USERNAME, null));
// return user
return user;
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}}
Code used to retrieve listwriter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
menu menu = (menu)
getFragmentManager().findFragmentById(R.id.fragment);
menu.updateinfo(getName());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
listwriter = session.getListwriter();
AppController class :
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
private ArrayList<HashMap<String, String>> gamesList;
public ArrayList<HashMap<String, String>> getGamesList() {
return gamesList;
}
public void setGamesList(ArrayList<HashMap<String, String>> gamesList) {
this.gamesList = gamesList;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
In your SessionManager you're not saving your List into SharedPrefs. You should do something like this:
public static final String MY_LIST = "my_list";
private static final Type LIST_TYPE = new TypeToken<List<BetDisplayer>>() {}.getType();
to save:
public void setListwriter(ArrayList<BetDisplayer> listwriter) {
this.listwriter = new ArrayList<BetDisplayer>(listwriter);
mPrefs.edit()
.putString(MY_LIST, new Gson().toJson(listwriter));
.commit();
}
to load:
public ArrayList<BetDisplayer> getListwriter() {
if (listwriter == null) {
listwriter = new Gson().fromJson(mPrefs.getString(MY_LIST, null), LIST_TYPE);
if(listwriter == null){
listwriter = new ArrayList<BetDisplayer>();
}
}
return listwriter;
}
Your BetDisplayer must implements Serializable.
See here: Android array to Sharedpreferences with Gson
To use Gson just add this dependency: 'com.google.code.gson:gson:2.3.1' or download the .jar
UPDATE:
Create a Singleton that holds one reference only to your SharedPreferences editor, it's just a will guess but I think you are using different context to get your editor and that could be the problem (UPDATE 2: it's not, check here, but the Singleton approach it's a plus):
private static SharedPreferences mPrefs;
private static SessionManager sInstance = null;
protected SessionManager() {
mPrefs = AppController.getInstance().getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static SessionManager getInstance() {
if (sInstance == null) {
sInstance = new SessionManager();
}
return sInstance;
}
And when you need to use SharedPreferences use SessionManager().getInstance().someMethod();
I am creating an app where the user puts in a name into an EditText. This text is then used in a loop to see if there are any matches in the parsed JSON data. If there is a match the match will be added to an ArrayList. This array list is then adapted to a listview.
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
I don't see what i'm doing wrong but i keep getting this error Caused by: java.lang.NegativeArraySizeException: -1
here is the full code
public class NameListActivity extends ListActivity {
private String mName;
public static final String TAG = NameListActivity.class.getSimpleName();
private JSONArray mNameArray;
private final String KEY_CONTENT = "content";
private final String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_list);
Intent intent = getIntent();
mName = intent.getStringExtra("name");
if (networkIsON()) {
GetNameData getNameData = new GetNameData();
getNameData.execute();
} else {
}
}
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
private boolean networkIsON() {
boolean isOn = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
isOn = true;
}
return isOn;
}
private class GetNameData extends AsyncTask< Object , Void , JSONArray> {
#Override
protected JSONArray doInBackground(Object... objects) {
int responseCode = -1;
JSONArray jsonResponse = null;
try {
URL nameUrl = new URL("https://fast-lowlands-9315.herokuapp.com/posts.json");
HttpURLConnection connection = (HttpURLConnection) nameUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
Log.v(TAG , "" + responseCode);
if (responseCode == 200 ) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONArray(responseData);
} else {
Log.i(TAG , "unsuccessful HTTP response code" + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONArray result) {
mNameArray = result;
handleJsonNameResponse();
}
}
}
this is the error i am getting in my logcat
02-08 09:38:15.190 27892-27979/com.androidy.listactivity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.androidy.listactivity, PID: 27892
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NegativeArraySizeException: -1
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:142)
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:121)
in this snippet,
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
you are using the return value of content length, to allocate a byte array, and in your case it is returning -1, causing the exception. A possible fix:
StringBuilder builder = new StringBuilder();
byte[] array = new byte[8092];
int read = 0;
while ((read = inputStream.read(array)) != -1) {
builder.append(new String(array, 0, read));
}
jsonResponse = new JSONArray(builder.toString());