Array not printing what it should be - android - android

When I try print the values to a textfield they come out as [Ljava.lang.String;#405af10
try {
JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
JSONArray Monday = jObject.getJSONArray("Monday");
String time = "";
String module = "";
String lecturer = "";
listAdapter = new ArrayAdapter<String[]>(this, R.layout.simplerow);
for (int i = 0; i < Monday.length(); i++)
{
time = Monday.getJSONObject(i).getString("time");
module = Monday.getJSONObject(i).getString("module");
lecturer = Monday.getJSONObject(i).getString("lecturer");
listAdapter.add(new String[] {time, module, lecturer});
}
mainListView.setAdapter(listAdapter);
} catch (Exception e) {
e.printStackTrace();
}
in the simplerow xml file I have
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
So each time a time, module or lecturer is printed it should be in it's own textview box., but it's not working and I don't know why or how to fix it.

It is most likely because your ArrayAdapter is set to accept in a String array (String []).
listAdapter = new ArrayAdapter<String[]>(this, R.layout.simplerow); //Parameterized for String []
Therefore you have a list of String arrays, which is basically equivalent to a 2D array.
This means, when the ArrayAdapter is setting the Text to the TextView you specified, it is calling toString() on the whole array object, hence the hashcode.
Consider making your own ArrayAdapter and override the getView() method so that it does what you want to do. There are plenty of tutorials online, such as this one.

I suggest that you make a POJO to hold your data. The POJO can have a name such as CourseInfo which clearly defines its meaning. Similarly, the members of CourseInfo will clearly define what they represent. This is preferred to an array because you can clearly define the meaning of each piece of data. Typically, Java programmers frown upon using an array which holds heterogenous data. In this case, even though the type of each piece of data is the same, the meaning of each element of the array differs.
This solution has the advantage that you can change
listAdapter = new ArrayAdapter<String[]>(this, R.layout.simplerow);
to
listAdapter = new ArrayAdapter<CourseInfo>(this, R.layout.simplerow);

Related

Android ArrayList<String> stored not restored back to its saved sorted order

I have an myArrayList which is to be stored and restored back in its saved sorted order. But the code does not do that. Why?
ArrayList<String> myArrayList
// save:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit;
edit = prefs.edit();
edit.putStringSet("mydata", new LinkedHashSet<String>(myArrayList));
edit.commit();
// read:
myArrayList = new ArrayList<String>(PreferenceManager
.getDefaultSharedPreferences(getBaseContext()).getStringSet(
"mydata", new LinkedHashSet<String>()));
adapterAppList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
myArrayList);
Is there any better way I can store the value of myArrayList and restored back to its original saved sorted order?
HashSet is not keeping orders, it is ordering for quickest find to it. You can convert list to json and save as string.
When you need to it, you can convert it to ArrayList from json with keeped ordering.
Example:
String listAsString = new Gson().toJson(arrayList); //list to string
List<String> arrayList = Arrays.asList(new Gson().fromJson(listAsString,String[].class)) //string to list
dont forget add library to build.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
You can serialize arrayList like string:
1 with gson
public ArrayList<String> convertToArrayList(String json) {
if (TextUtils.isEmpty(json)){
return null; // or new ArrayList<>()
}
Type type = new TypeToken<ArrayList<String>>(){}.getType();
return new Gson().fromJson(json, type);
}
public String convertFromArrayList(ArrayList<String> list) {
if (list == null){
return null;
}
return new Gson().toJson(list);
}
2 without gson
public ArrayList<String> convertToArrayList(String st) {
if (!TextUtils.isEmpty(st)){
String[] str = st.split(",");
if (str.length > 0){
return new ArrayList<>(Arrays.asList(str));
}
}
return null;
}
public String convertFromArrayList(ArrayList<String> list) {
if (list!=null && !list.isEmpty()){
return TextUtils.join(",", list);
}
return null;
}
Yes, you are right, the order is not stored in string set, coz it is a set (duh).
When I was bugged with this, I got the serializing solution where, you can serialize your string.
Read this only if you haven't read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 -
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it.
If you are worried about splitting just look up "splitting a string in java".
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.

Iterate through Java jsonObjects without array included

My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;
As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)

Android setter of String array

now i've got simple setter and getter of string array. I want to use setter to put some retrevied json info + same text to array. When i use belowe code:
met.setPlacepic(new String[]{"http://dfsdfsdfsf/" + json.getString("source")});
it looks like setter put only one string to array, despite there is many more data.
Declaration is simple
public String[] placepic
and the setter is also simple:
public void setPlacepic(String[] placepic) {
this.placepic = placepic;
}
Anybody knows reason of this?
If the number of strings is fixed (you know exactly how many element you would have in the array), then you could use String Arrays:
String[] placepic = new String[20]; //20 strings
//Then, in your loop:
placepic[i] = yourData;
If you do NOT know how many strings in your data, You should use List:
List<String> placepicList= new ArrayList<String>();
//Then, in your loop:
placepicList.add(yourData);
//Then after the loop, you get the array
String[] placepic = placepicList.toArray(new String[placepicList.size()]);

Wrong arrangement of data from 'for loop'

I have the following code. I added my text fields dynamically. My desired result shown in Genymotion 5.0 (Google Nexus 5) but when I run my app in other devices/actual device the textfields get shuffled. Please help, Thanks in advance.
JSONObject jsonObject = new JSONObject(question.getSublabels());
final EditText[] editTextSublabels = new EditText[jsonObject.length()];
for (int i = 0; i < jsonObject.length(); i++) {
String names = jsonObject.names().get(i).toString();
editTextSublabels[i] = (EditText) LayoutInflater.from(activity).inflate(R.layout.sublabels, null);
editTextSublabels[i].setId(i);
editTextSublabels[i].setHint(jsonObject.getString(names));
sublabelsContainers.addView(editTextSublabels[i], params);
}
You cannot and should not rely on the ordering of elements within a JSON object.
In JSON, an object is defined thus:
An object is an unordered set of name/value pairs.
If you want order to be preserved, you need to redefine your data structure or put it inside a jsonarray
see http://www.json.org.
A JSONObject is a type of map. It does not preserve ordering. If you want to preserve ordering using JSON, you will need to use an array (and matching JSONArray in Java).

Saving multiple data one at a time in database in Android

I want to save multiple files to my database one by one.
And what happen here using my codes is this:
What I want to happen is like this one:
here is my code:
//Arraylist for getting the multiple brand code
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
//content.add(values);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.add(SubBrandCode);
//Casting and conversion for SubBrand Code
String subBrand = content.toString();
//SAVE SUBBRAND
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
Toast.makeText(getApplicationContext(), subBrand, Toast.LENGTH_LONG).show();
}
}
Mistakes:
content.add(SubBrandCode);
do you know how to remove the '[ ]' in the saved data? (e.g. [AC001]) All I want to save is the AC001 only.
Solutions:
Call clear() method of ArrayList before adding new values into it.
Its giving you [AC001] as you are subBrand by doing content.toString();. Don't convert it to string, instead use content.getString(position) and it will give you String value.

Categories

Resources