I have a Parse Object that has a value which contains an ArrayList of User Id's. I'm having trouble figuring out how to retrieve that entire ArrayList (NOT just 1 value from the list) My code looks something like this.. but always comes with errors (Array comes back empty):
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Food");
query.whereEqualTo("objectId", parseId);
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
ArrayList<String> list = (ArrayList<String>)
parseObject.get("userList");// This is where I don't know what to use to get the Array
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ThisActivity.this);
builder.setTitle(R.string.error_title)
.setMessage("error")
.setPositiveButton("ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
I want to just load the array of user id's (from the object) and use the array elsewhere in this activity. All the other values in the object are String values and load just fine with the .getString.
I know I'm probably way off so any help would be appreciated.
//Try This To Retrieve All Records In Server using findInBackground()
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Food");
query.whereEqualTo("objectId", parseId);
query.findInBackground(new GetCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObject, ParseException e) {
if (e == null) {
for (int i = 0; i<parseObject.size(); i++){
ParseObject stObj = parseObject.get(i);
List<String>list = stObj.getList("userList");
//Transfer list content to array stockArr
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
//list contains userlist - To add to list without transferring content to array use next line of code below
list.add("Add This To The List");
//To save updated list use next two lines of code below
stObj.put("userList", list);
stObj.saveInBackground();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(ThisActivity.this);
builder.setTitle(R.string.error_title)
.setMessage("error")
.setPositiveButton("ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
//Try This To Retrieve ONLY First Record In Server using getFirstInBackground()
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Food");
query.whereEqualTo("objectId", parseId);
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObject, ParseException e) {
if (e == null) {
ParseObject stObj = parseObject.get(0);
List<String>list = stObj.getList("userList");
//Transfer list content to array stockArr
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(ThisActivity.this);
builder.setTitle(R.string.error_title)
.setMessage("error")
.setPositiveButton("ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
You should replace this line:
parseObject.get("userList");// This is where I don't know what to use to get the Array
to:
JSONArray array = parseObject.getJSONArray("userList");
And it shall work without any problem.
I think that you don't have to use getFirstInBackground (that retrieve only one element) but you have to use findInBackground (to retrieve all the objects).
Related
Hey Stackoverflow community, when I pass the JSON Array to another Activity, it just gives "null" back, could you give me a solution ?
EDIT it stops, after the onClick
First Activity:
eingabe = (TextView) findViewById(R.id.tv_dish_name);
send.setOnClickListener(this);
save.setOnClickListener(this);
speicher = getApplicationContext().getSharedPreferences("jsondata", 0);
zugreifen können (hier private --> 0)
editor = speicher.edit();
}
#Override
public void onClick(View v) {
if (v == save) {
FavDishes.add(eingabe);
for (int i = 0; i < 4; i++) {
}
JSONArray jsArray = new JSONArray(FavDishes);
editor.putString("jsondata", jsArray.toString());
editor.commit();
second Activity:
anzeige = (TextView)findViewById(R.id.anzeige);
SaveDish(anzeige.getText().toString());
speicher = getApplicationContext().getSharedPreferences("jsondata",0);
editor = speicher.edit();
private void SaveDish(String jsondata){
String strJson = speicher.getString("jsondata","0");//second parameter is necessary ie.,Value to return if this preference does not exist.
if(strJson != null) try {
JSONObject jsonData = new JSONObject(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
editor.putString("jsondata",strJson);
editor.commit();
//"Data 1" als key für "Schublade Data1", value Inhalt (übergebener String)
anzeige.setText(speicher.getString("jsondata", null));
}
anzeige = (TextView)findViewById(R.id.anzeige);
Help would be appreciated, thanks for your time!
You need to iterate over you array and for each element into you array you can parse it to JSON object then push to your json array.
Regards,
I'm new to android programming so you'll need to bear with me.
I'm trying to retrieve a column from parse server and display it in a ListView. So far i have produced the following code however I've encountered an issue. In my for loop it should fetch each item from the "name" column from the "Absences" class and add it to the ArrayList called "teachers".
The issue is the app crashes because the array is null (after printing it in the logs) and it therefore can't assign it to the ArrayAdapter. I believe the reason for this is that the objects are fetched in the background some time after the arrayadapter code is executed meaning its trying to display an empty array.
I'm assuming i need to delay it somehow - any ideas on what i should do?
Affected code inside the onCreate() method:
final ArrayList<String> teachers = new ArrayList<String>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Absences");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
for(ParseObject object : objects){
String name = String.valueOf(object.get("name"));
Log.i("teacherName", name);
teachers.add(name);
}
} else {
Log.i("Get data from parse", "There was an error getting data!");
e.printStackTrace();
}
}
});
Log.i("teacherOutput", teachers.toString());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachers);
ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(arrayAdapter);
Many thanks in advance!
You need to learn what asynchronous means.
Your code should be something like:
final ListView lv = (ListView) findViewById(R.id.listView);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
ArrayList<String> teachers = new ArrayList<String>();
for (ParseObject object : objects) {
String name = String.valueOf(object.get("name"));
Log.i("teacherName", name);
teachers.add(name);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachers);
lv.setAdapter(arrayAdapter);
} else {
Log.i("Get data from parse", "There was an error getting data!");
e.printStackTrace();
}
}
});
The title says it all, I'm trying to do that because I obtain a list from parse and the user must choose one of them from a spinner and based on the user's choice it responds and sets another filter to another spinner. The problem I'm having (really not much of a deal, but it's something that I'd like to do) is that when the list gets obtained from Parse it automatically selects the first one it retrieves and fills all the spinners automatically (of course you can change it and it will work perfectly).
The question is, how do I retrieve a list from parse, add it into a spinner in a way that it doesn't fill everything by itself ?
Here's my piece of code where I obtain the list and add it into a spinner:
groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Group Item Selected Ran");
final String spinI1 = groupSpinner.getSelectedItem().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("grupo", spinI1);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
int size = 0;
size = parseObjects.size();
String[] mod = new String[size];
for (int i = 0; i < parseObjects.size(); i++) {
mod[i] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i]);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(HandsetLocation.this, android.R.layout.simple_spinner_item, mod);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
hospitalSpinner.setAdapter(spinnerArrayAdapter);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Any help would be appreciated greatly!
At my phone so cannot properly indent the code but here it goes:
String[] mod = new String[size+1];
mod[0] = "select value";
for (int i = 0; i < parseObjects.size(); i++) {
mod[i+1] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i+1]);
}
I compile the list: titleList.add(0, title), apply it in sharedpreferences: prefs.putString(TITLES, title).apply() and now need to retrieve it.
I have looked at a lot of the solutions here and none seem to fit my problem well.
The program is suppose to take text a user inputs and save it using SharedPreferences, so it can be used in a ListActivity later. This list is currently an ArrayList (I believe I need it in an array list because I am using AutoCompleteEditText for suggestions from the array list, so I need the adapter).
Based on the above logic,prefs is a sharedpreference object full of string objects. I have tried using prefs.getAll().values.toArray(new String[0...100]). I found that in an "Android" book. It works, but only gets the first item. After trying methods, Set<?> and a few others, that was the method that got anything at all.
It is all I need to have the program working PERFECTLY. Can someone please help getting this list to save in sharedpreferences, retrieving it as a complete, split, list (that can be indexed) and passing it to a ListActivity?
ArrayList<String> titleList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_lyric);
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
titlePref = getSharedPreferences(titlePrefFile, MODE_PRIVATE);
//titleList = titlePref.getAll().values().toArray();
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
warnSave.show();
}
else
warnEmpty.show();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//update song title list adapter
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
titleList.add(0,title);
prefEditor = titlePref.edit();
prefEditor.putString("titleList", title).apply();
}
Sorry, formatting the code just wont work for me.
Thank you and Happy Holidays!
I think you need to use ObjectSerializer.
Save :
ArrayList<String> strings = new ArrayList<String>();
string.add("Hello!");
//save list into SP
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString("LIST", ObjectSerializer.serialize(strings));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Restore :
// load list from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
ArrayList<String> strings = new ArrayList<String>();
try {
strings = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString("LIST", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Or use parcelable wrapping to save/retrieve your data
Sergey's answer may be just fine. Also, take a look at JPM's answer and class, on this thread. I used it yesterday.
So, using JPM's class, here's writing myBigArrayList:
// write data file for later use
String ser = SerializeObject.objectToString(myBigArrayList);
if (ser != null && !ser.equalsIgnoreCase("")) {
SerializeObject.WriteSettings(c, ser, "myobject.dat");
} else {
SerializeObject.WriteSettings(c, "", "myobject.dat");
}
And, here's a method I adapted, that returns a complete, intact arraylist:
private ArrayList<yabbaData> getYabbaData() {
String ser = SerializeObject.ReadSettings(getActivity().getApplicationContext(), "myobject.dat");
ArrayList<yabbaData> give = null;
if (ser != null && !ser.equalsIgnoreCase("")) {
Object obj = SerializeObject.stringToObject(ser);
// Then cast it to your object and
if (obj instanceof ArrayList) {
// Do something
give = (ArrayList<yabbaData>) obj;
}
}
return give;
}
In the write, I use c as my application context, where I had passed in getApplicationContext().
In the read, I used getActivity().getApplicationContext() because I was in a fragment. Sub in String for my yabbaData object, in ArrayList, and I think it's ready to use.
How to show Alert Dialog in static method, i am trying to put a condition, in which i am checking for the folder inside the SD Card, if exist then listing Items, otherwise i want to show AlertDialog - with message no folder found with Church Name
public static List <String> fromSDCard()
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// here i want to put AlertDialog
}
return listChurchWall;
}
Pass your app context to the static method.
public static List <String> fromSDCard(Context context)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
// 4. Show the dialog
dialog.show()
}
return listChurchWall;
}
If calling from your activity.
public MyActivity extends Activity
{
....
private void Method()
{
List<String> list = fromSdCard(this);
}
....
}
public static List<String> fromSDCard(Context mContext) {
List<String> listChurchWall = new ArrayList<String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File(string + name + "/");
if (f.exists()) {
files = f.listFiles();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.stat_sys_warning;
Drawable image = mContext.getResources().getDrawable(imageResource);
builder.setTitle("title").setMessage("your Message").setIcon(image).setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
return listChurchWall;
}
Try the following way--
public static List <String> fromSDCard(Activity a, String title, String message)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}
else
{
AlertDialog.Builder dialog = new AlertDialog.Builder(a);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setNeutralButton("OK", null);
dialog.create().show();
}
return listChurchWall;
}
Then in your class do---
public MyActivity extends Activity
{
....
private Method()
{
List<String> list = fromSdCard(this, "Your Title", "Your message");
}
....
}
UPDATE:
You get a NullPointerException because something is null that shouldn't be. It happens while sorting the array, so perhaps one of the array elements is null. Take a look at how you assign values to your array.
Perhaps at the top of it, see if any of the objects Object o1 or Object o2 themselves are null.