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.
Related
I would like to make a game, if i press play button, random level (activity) will open. I got code for this: https://stackoverflow.com/a/29579373/13101103
This is working, but i would like to edit, example, all levels have 2 different answer, answer1 is fail, answer2 is pass the level, if user pass level1, and in level2 fail, than go back to mainactivity, and if start again, then the passed levels will not show again.
Example:
There are 5 levels, user start random level, example level3, it passed, go to next random level, example level2, it pass, go to next... level4, it failed, go back to mainactivity, user start again, but the already passed levels will not show, only unpassed... example start level3... if passed then go to level1....
How can i edit this code for my solution? Can somebody give me some tips? Because in this if i go back to mainactivity and start again, then it start with all levels... I tried to edit, but i'm stucked and not works...
Plus i would like to save progress when user leave the app. In sharedpreferences how can i save the passed levels (arraylist)....?
MainActivity:
enter code here
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
activityList.add(Level2Activity.class);
activityList.add(Level3Activity.class);
activityList.add(Level4Activity.class);
activityList.add(Level5Activity.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = Level1Activity.class;
// We are adding the number of the activity to the list
activityList.remove(Level1Activity.class);
break;
case 2:
activity = Level2Activity.class;
activityList.remove(Level2Activity.class);
break;
case 3:
activity = Level3Activity.class;
activityList.remove(Level3Activity.class);
break;
case 4:
activity = Level4Activity.class;
activityList.remove(Level4Activity.class);
break;
default:
activity = Level5Activity.class;
activityList.remove(Level5Activity.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
});
Level1Activity:
enter code here
failbutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
//Class activity = null;
Intent intent = new Intent(Level1Activity.this, Main2Activity.class);
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
});
buttonlevel1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
// Do something when after all activities have been opened
//startActivity(new Intent(Level1Activity.this, Main2Activity.class));
//Intent intent = new Intent(Level1Activity.this, Main2Activity.class);
//intent.putExtra("ACTIVITY_LIST", activityList);
//startActivity(intent);
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
}
});
level2, level3.... is same just different id-s
I'd suggest using the Singleton pattern to handle passing data between activities.
You can pass the list by intent's putExtra() or by SharedPreferences but with a Singleton class, it looks much better and easier to manipulate your data because they are encapsulated. So much so in your situation where you want to save your levels' states (e.g. when they are already completed).
However, if you really insist on using SharedPreferences to save the list then I suggest converting it to Json by using Gson. (Check below my answer on how to implement this.)
As I said, I'd use the Singleton pattern to avoid creating unnecessary boilerplate code and to encapsulate the levels' states.
LevelManager class (the singleton)
final class LevelManager {
// constants
private static final String LEVELS_SHARED_PREFERENCES_NAME = "app_name.LEVELS";
// variables
private static LevelManager instance;
private List<Class> levels;
private SharedPreferences sharedPreferences;
private LevelManager(Context context) {
sharedPreferences =
context.getSharedPreferences(LEVELS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
levels = new ArrayList<>();
initializeList();
}
private void initializeList() {
// Initialize levels, ie. add levels that are not yet completed/passed
// Check in SharedPreferences if level has already been completed
boolean alreadyPassed;
alreadyPassed = sharedPreferences.getBoolean(Level1Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level1Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level2Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level2Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level3Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level3Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level4Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level4Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level5Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level5Activity.class);
}
static LevelManager getInstance(Context context) {
if (instance == null) {
instance = new LevelManager(context);
}
return instance;
}
Class getRandomLevel() {
if (levels.isEmpty()) {
return null; // Return null if all levels are already completed
}
Collections.shuffle(levels);
return levels.get(0);
}
void saveLevelState(Class levelClass, boolean passed) {
sharedPreferences.edit().putBoolean(levelClass.getSimpleName(), passed).apply();
if (passed) {
// Remove level from list if user passed it so that it won't
// be included in next levels
levels.remove(levelClass);
}
}
void reset() {
// Clears all entries in SharedPreferences and re-initialize list
sharedPreferences.edit().clear().apply();
initializeList();
}
}
Inside onCreate in MainActivity
// Get LevelManager singleton instance
final LevelManager levelManager = LevelManager.getInstance(this);
Button startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get next random level
Class levelToStart = levelManager.getRandomLevel();
// If all levels are already completed
if (levelToStart == null) {
Toast.makeText(MainActivity.this, "All levels are completed!",
Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(MainActivity.this, levelToStart);
startActivity(intent);
}
});
// I added a new button to reset all levels
Button resetButton = findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the method reset() from LevelManager to restart everything
levelManager.reset();
Toast.makeText(MainActivity.this, "All levels have been reset!",
Toast.LENGTH_LONG).show();
}
});
Inside of onCreate on each Level Activity
// Get LevelManager
final LevelManager levelManager = LevelManager.getInstance(this);
// I created two buttons to simulate pass and fail
Button pass = findViewById(R.id.passButton);
Button fail = findViewById(R.id.failButton);
pass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Save state (Don't forget to change 'N' below)
levelManager.saveLevelState(LevelNActivity.class, true);
// Get next level
Class levelToStart = levelManager.getRandomLevel();
// Check if all are levels already completed
if (levelToStart == null) {
Toast.makeText(LevelNActivity.this, "Completed all levels",
Toast.LENGTH_LONG).show();
finish(); // Must implement to avoid going back to previous level (ie. Activity)
return;
}
Intent intent = new Intent(LevelNActivity.this, levelToStart);
startActivity(intent);
finish();
}
});
fail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
As you can see, you can simply use the finish() method if the user failed the level whereas you use the code below to proceed to the next level:
// Get LevelManager
LevelManager levelManager = LevelManager.getInstance(this);
// Set that the user passed this level (Change 'N' to the current level we are in)
levelManager.saveLevelState(LevelNActivity.class, true);
// Get next level
Class nextLevel = levelManager.getRandomLevel();
// If all levels are completed then 'nextLevel' will be null
if (nextLevel == null) {
// ...
}
// Start next level and finish current
Intent intent = new Intent(this, nextLevel);
startActivity(intent);
finish();
Note: To avoid calling finish() explicitly when starting the next level, you can put android:noHistory="true" in your levels' activity tag inside your manifest file.
How to save list to SharedPreferences by converting it to Json using Gson
To actually use Gson, you'll have to add implementation 'com.google.code.gson:gson:2.8.6' inside your app gradle dependencies.
Also, there's a problem on Gson when parsing Class objects to Json: You need to create your own serializer and deserializer for these objects and register it to your GsonBuilder.
ClassAdapter class (this is where we create our own custom serializer and deserializer for Class objects)
public class ClassAdapter implements JsonSerializer<Class>, JsonDeserializer<Class> {
#Override
public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
// Get our class 'src' name
return new JsonPrimitive(src.getName());
}
#Override
public Class deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
// Get class
return Class.forName(json.getAsString());
} catch (ClassNotFoundException e) {
// If class could not be found or did not exists, handle error here...
e.printStackTrace();
}
return null;
}
}
Here's a sample usage of saving a list to SharedPreferences by Json using Gson:
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Initialize our list of levels (ie. classes)
List<Class> classes = new ArrayList<>();
classes.add(Level1Activity.class);
classes.add(Level2Activity.class);
classes.add(Level3Activity.class);
classes.add(Level4Activity.class);
classes.add(Level5Activity.class);
// Create Gson from GsonBuilder and convert list to json
Gson gson = gsonBuilder.create();
String json = gson.toJson(classes);
// Save json to SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
sharedPreferences.edit().putString("levels", json).apply();
And to retrieve the list back:
// Retrieve json from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
String json = sharedPreferences.getString("levels", null);
// Handle here if json doesn't exist yet
if (json == null) {
// ...
}
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Create Gson from GsonBuilder and specify type of list
Gson gson = gsonBuilder.create();
Type type = new TypeToken<ArrayList<Class>>(){}.getType();
// Convert json to list
List<Class> classes = gson.fromJson(json, type);
I hope you gained valuable tips to tackle this problem! And as always, happy coding!
I am new in Android. I need your help. My Problem is - I have 2 classes Nplist.java and Addcustomer.java. In my AddCustomer class,One TextView and one Button is there to go Nplist class. In my Nplist class there is checklist and this checklist is coming from database and all the checked values are stored in ArrayList<String> and one Button is used to go back to AddCustomer class. I want that ArrayList<String> which is in Nplist to by display in my AddCustomer class Textview . I haved tried these but my Addcustomer class crashed.
1.Nplist.class
add.setOnClickListener(new View.OnClickListener() {<br>
#Override<br>
public void onClick(View view) {<br>
Bundle extra=new Bundle();<br>
extra.putSerializable("objects",checkedList);<br>
Intent intent = new Intent(Nplist.this, AddCustomer.class);<br>
intent.putExtra("extra",extra);<br>
startActivity(intent);<br>
});
2.AddCustomer.class
onCrete()...{
Bundle extra = getIntent().getBundleExtra("extra");<br>
ArrayList<String> object = (ArrayList<String>)extra.getSerializable("objects");<br>
for (String str : object) {<br>
getnp.append(str + "\n");<br>
}
}
What do you expect the result to be?
- What is the actual result you get? (Please include any errors.)
When i go like this Nplist-->AddCustomer its working well but crash on ( AddCustomer-->Nplist-->AddCustomer)
It's because when you are coming back to your AddCustomer Activity the list is null . You can solve this problem by making a global class which will store the list in a Static Field , And You can access that list from any class or Activity you want to. Try out below solution .
Global.java Class is as below :
public class Global {
private static ArrayList<String> object = new ArrayList<>();
public static ArrayList<String> getObject() {
return object;
}
public static void setObject(ArrayList<String> object) {
Global.object = object;
}
}
From NpList.java class set the value of the list as below :
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.setObject(checkedList);
Intent intent = new Intent(Nplist.this, AddCustomer.class);
startActivity(intent);
}
});
Now Access in AdCustomer.java as below :
onCreate()...{
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<String> object = Global.getObject();
for (String str : object) {
getnp.append(str + "\n");
}
}
This maybe helpful for you.
Using putStringArrayListExtra method you can send an array list of strings along with the intent.
Sender side:
Intent intent = ...
intent.putStringArrayListExtra("THE_KEY", theList);
Receiver side:
ArrayList<String> theList = intent.getStringArrayListExtra("THE_KEY");
I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences
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).
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.