I have an ArrayList<String> that I save in shared preference in Activity A. I access the list from a second activity (ListActivity). Activity A starts ListActivity for a result. When an item is clicked the ListActivity sends the string at that position to Activity A for use. A long click allows you to delete.
When I delete from the list, I want to save the new (the latest) list in sharedpreferences. PLEASE! How can I do this? I just need the List to popup, you do your thing, and it goes away after saving the newest list.
I tried so many ways (code is patchwork at this point) but the deleted item persists when I open ListActivity again after deleting the item.
My code is below...
Activity A:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
...
lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
...
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()));
}
});
lyricHolder = (EditText) findViewById(R.id.lyricHolder);
newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
newSongBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (areFieldsNull(lyricTitle.getText().toString(),
lyricHolder.getText().toString()))
alertEmpty.show();
else {
/** There is some redundancy within performSave() here */
performSave();
lyricTitle.setText("");
lyricHolder.setText("");
}
}
});
...
findBtn = (Button) findViewById(R.id.findBtn);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
startActivityForResult(showListIntent, GET_SONG_CODE);
Log.i("TAG1", "Starting pickActivity.class for result");
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
...
// init sharedPreferences
colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);
// load defaults of sharedPreferences
titleList = new ArrayList<>();
try {
titleList = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetTitleListAdapter(titleList);
...
} //end onCreate
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
lyricTitle.setAdapter(autoCompleteAdapter);
}
...
private boolean areFieldsNull(String title, String song) {
// check if the text fields are empty
return (
title.isEmpty()||
title.equals(" ")||
title.equals(" ")||
song.isEmpty()||
song.equals(" ")||
song.equals(" ")
);
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
alertSave.show();
}
else
alertEmpty.show();
}
private void saveTitleArray() {
// save string array list in shared prefs
try {
prefEditor = titlePref.edit();
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
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 (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isExternalStoragePresent()&&externalSD_box.isChecked()){
// save to the SD card IF SD is found AND enableSD_box is checked
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File songFile = new File (path, title + ".txt");
try {
OutputStream os = new FileOutputStream(songFile);
byte[] data = song.getBytes();
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (but not updated songs) go to top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private String openSongFile(String title){
BufferedReader bufferReader = null;
StringBuilder builder = new StringBuilder();
try {
FileInputStream fis = openFileInput(title);
bufferReader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = bufferReader.readLine()) != null) {
builder.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when pickActivity ListView returns result
Log.i("TAG1", "Activity data returned from pickActivity.class");
if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
String title = data.getData().toString();
lyricTitle.setText(title);
lyricHolder.setText(openSongFile(title));
Log.i("TAG1", "Result success\nSong loaded into edittext");
Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
}
}
ListActivity:
public class pickActivity extends ListActivity {
ArrayList<String> songListArray;
SharedPreferences titlePref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song);
Log.i("TAG2", "pickActivity.class created");
// init string array from blank list or sharedPref saved data
titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
songListArray = new ArrayList<>();
try {
songListArray = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
Log.i("TAG2", "Extra received and set");
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Log.i("TAG2", "onItemLongClick()");
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
confirmDel.setTitle("Delete Song")
.setIcon(R.mipmap.ic_keeper)
.setMessage("Are you sure you want " +
"\"" + songListArray.get(position) +
"\"" + " gone?")
.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// system default is dismiss()
}
})
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete song, title, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
Log.i("TAG2", "Item deleted from list");
updateSharedPref(titlePref, writeActivity.TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("TAG2", "onListItemClick()");
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
Log.i("TAG2", "ArrayList adapter set");
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Log.i("TAG2", "SharedPref updated!");
}
}
Honestly, source code would help a lot in this case...
My best guess (without any code) would be, please make sure that you call
editor.apply();
and not
editor.commit();
Related
I have Created ToDo list app in android studio. i want to show a toast message when the button pressed while there is no text in it. like "Please enter Text". and also prevent creating any blank list. i have two java class files. MainActivity and FileHelper
MainActivity (code):
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private EditText ItemET;
private Button btn;
private ListView itemList;
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemET = findViewById(R.id.item_edit_text);
btn = findViewById(R.id.add_btn);
itemList = findViewById(R.id.item_list);
items = FileHelper.readData(this);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
itemList.setAdapter(adapter);
btn.setOnClickListener(this);
itemList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
}
}
FileHelper (code):
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> items, Context context){
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
itemList = (ArrayList<String>) ois.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return itemList;
}
}
Have a look at below code.
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
if(ItemEntered.trim().isEmpty()){
Toast.makeText(getApplicationContext(), "Please Enter some detail", Toast.LENGTH_LONG).show();
} else {
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}
break;
}
}
Check this code:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
if(!TextUtils.isEmpty(ItemET.getText().toString())){
String ItemEntered = ItemET.getText().toString();
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Please enter Text", Toast.LENGTH_SHORT).show();
}
break;
}
}
I'm nearly finished with my App!
It's working fine, but there's a little mistake in it..
My App is an "Note"-App with some notes that are prefabricated and are the first opening of the app.
Therefore I save this notes at the first start and get them everytime I start the app again.
Unfortunately I'm have 66 prefabricated notes and they are all saved, but in the ListView there are only 45 or so in it..
I don't think it's something with syntax because the app works fine except the loss of 21 prefabricated notes
Here's my MainActivity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean useDarkTheme = preferences.getBoolean(PREF_DARK_THEME, false);
SharedPreferences prefers = getApplicationContext().getSharedPreferences("prefs_daten", MODE_PRIVATE);
if (useDarkTheme) {
setTheme(R.style.AppTheme_dark);
}
super.onCreate(savedInstanceState);
if (VERBOSE) Log.v(TAG, "+ ON CREATE +");
setContentView(layout.activity_hauptmenu);
mListNotes = findViewById(id.listview);
itemTitel = new ArrayList<>();
itemTitel.addAll(Arrays.asList(string.Titel1, string.Titel2, string.Titel3, ...
string.Titel66));
itemStory = new ArrayList<>();
itemStory.addAll(Arrays.asList(string.Blackstory1, ...));
itemLosung = new ArrayList<>();
itemLosung.addAll(Arrays.asList(string.Losung1, ..));
}
private void StandardBS() {
if (Listensize==0){
anzahl_BS=66;
int a;
for(a=0; a<anzahl_BS; a++){
try{
tempTitel = getResources().getString(itemTitel.get(a));
tempStory = getResources().getString(itemStory.get(a));
tempLosung = getResources().getString(itemLosung.get(a));
Blackstory blackstory = new Blackstory(System.currentTimeMillis(), tempTitel, tempStory, tempLosung);
Log.w("Blackstory", ""+tempTitel);
Utilities.saveBlackstory(this, blackstory);
//Toast.makeText(this, "Blackstory wurde gespeichert!", Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e){
//Toast.makeText(this, "Standard wurde falsch ausgeführt", Toast.LENGTH_SHORT).show();
}
}
Log.w("Anzahl", ""+a);
}
#Override
protected void onResume() {
super.onResume();
try{
mListNotes.setAdapter(null);
}
catch (NullPointerException e){
Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show();
}
final ArrayList<Blackstory> blackstories = Utilities.getAllSavedBlackstory(getApplicationContext());
Listensize=blackstories.size();
anzahl_BS=Listensize;
if(blackstories != null && blackstories.size() > 0) { //check if we have any notes!
na = new BlackstoryAdapter(this, layout.item_layout1, blackstories);
try{
mListNotes.setAdapter(na);
}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch2", Toast.LENGTH_SHORT).show();
}
//set click listener for items in the list, by clicking each item the note should be loaded into NoteActivity
try{
mListNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//run the NoteActivity in view/edit mode
fileName = ((Blackstory) mListNotes.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent viewBlackstoryIntent = new Intent(getApplicationContext(), number1.class);
viewBlackstoryIntent.putExtra(Utilities.EXTRAS_NOTE_FILENAME, fileName);
startActivity(viewBlackstoryIntent);
}
});
mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//ask user if he really wants to delete the note!
Dialog_delete(position, id);
return true;
}});}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch3", Toast.LENGTH_SHORT).show();
}}
else { //remind user that we have no notes!
Toast.makeText(getApplicationContext(), "you have no saved notes!\ncreate some new notes :)"
, Toast.LENGTH_SHORT).show();
}
firstOpen=false;
}
My Utilities (to save and load notes):
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static final String EXTRAS_NOTE_FILENAME = "EXTRAS_NOTE_FILENAME";
public static boolean saveBlackstory(Context context, Blackstory blackstory){
String fileName = String.valueOf(blackstory.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try{
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(blackstory);
oos.close();
}
catch (IOException e) {
e.printStackTrace();
Log.w("Failed","");
return false;
}
return true;
}
public static ArrayList<Blackstory> getAllSavedBlackstory(Context context) {
ArrayList<Blackstory> blackstories = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> blackstoryFiles = new ArrayList<>();
int size = blackstoryFiles.size();
//add .bin files to the noteFiles list
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
blackstoryFiles.add(file);
Log.w("Included", ""+file);
}
}
//read objects and add to list of notes
FileInputStream fis;
ObjectInputStream ois;
for (int i = 0; i < blackstoryFiles.size(); i++) {
try{
fis = context.openFileInput(blackstoryFiles.get(i));
ois = new ObjectInputStream(fis);
blackstories.add((Blackstory)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return blackstories;
}
public static Blackstory getBlackstoryByFileName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
if(file.exists() && !file.isDirectory()) { //check if file actually exist
Log.v("UTILITIES", "File exist = " + fileName);
FileInputStream fis;
ObjectInputStream ois;
try { //load the file
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
Blackstory note = (Blackstory) ois.readObject();
fis.close();
ois.close();
return note;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
public static boolean deleteFile(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File file = new File(dirFiles, fileName);
if(file.exists() && !file.isDirectory()) {
return file.delete();
}
return false;
}
And my Adapter:
public class BlackstoryAdapter extends ArrayAdapter<Blackstory> {
public static final int WRAP_CONTENT_LENGTH = 50;
public BlackstoryAdapter(Context context, int resource, List<Blackstory> blackstories) {
super(context, resource, blackstories);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_layout1, null);
}
Blackstory blackstory = getItem(position);
if(blackstory != null) {
TextView title = convertView.findViewById(R.id.single_titel);
title.setText(blackstory.getTitel());
}
return convertView;
}
My Blackstory.java:
public class Blackstory implements Serializable {
private String mTitel;
private String mStory;
private String mLosung;
private long mDateTime;
public Blackstory(long dateInMills, String titel, String story, String losung) {
mDateTime = dateInMills;
mTitel = titel;
mStory = story;
mLosung = losung;
}
public void setDateTime(long dateTime) {
mDateTime = dateTime;
}
public long getDateTime() {
return mDateTime;
}
public String getDateTimeFormatted(Context context) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
, context.getResources().getConfiguration().locale);
formatter.setTimeZone(TimeZone.getDefault());
return formatter.format(new Date(mDateTime));
}
public String getTitel() {
return mTitel;
}
public void setTitel(String titel) {
mTitel = titel;
}
public String getStory() {
return mStory;
}
public void setStory(String story) {
mStory = story;
}
public String getLosung() {
return mLosung;
}
public void setLosung(String losung) {
mLosung = losung;
}
}
There need not be getCount() method as pointed out by AguThadeus. The array data is passed to the superclass so that will take care of the number of views.
I'm trying to get e-mail addresses from parse User class,
here I'm trying to get other users email id's when logging in a
user, logged in users email id is showing but other users email ids
are not showing always null
I try use master key also, still not working ,
below is my java code.
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
protected TextView individualOrganization;
Button emailPerson;
Button callPerson;
Button callPersonTelephone;
ParseObject personObject;
String personEmail;
String personNumber;
String personNumberTelephone;
ParseQuery query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_individual);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.coporateSector);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
individualOrganization =(TextView) findViewById(R.id.individualOrganization);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseUser> query = ParseUser.getQuery();
//query.put("useMasterKey", true);
query.setLimit(2000);
query.include("email");
query.getInBackground(objectId, new GetCallback<ParseUser>() {
#Override
public void done(final ParseUser object, com.parse.ParseException e) {
if (e == null) {
personObject = object;
String username = object.getString("firstname");
txtv.setText(username + " " + object.getString("lastname"));
String position = object.getString("position");
txtv1.setText(position);
String organizationName = object.getString("organizationName");
individualOrganization.setText(organizationName);
URL url = null;
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv2);
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv3);
// try{
// JSONObject jsonObject = parseObjectToJson(object);
// Log.d("Object", jsonObject.toString());
// Log.d("Email", "+" + object.get("email"));
// personNumber = jsonObject.getString("telephone");
// //personEmail = jsonObject.getString("email");
// personEmail= object.getEmail();
//
// }catch (JSONException je){
// }catch (ParseException pe){
// } catch (com.parse.ParseException e1) {
// e1.printStackTrace();
// }
} else {
}
callPerson = (Button) findViewById(R.id.individualMobile) ;
personNumber = object.getString("mobile");
callPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+personNumber));
startActivity(i);
}
});
if(personNumber==null || personNumber.equals("") || personNumber.equals(" ")){
callPerson.setClickable(false);
callPerson.setEnabled(false);
callPerson.setVisibility(View.GONE);
}
else{
callPerson.setEnabled(true);
callPerson.setClickable(true);
callPerson.setVisibility(View.VISIBLE);
}
callPersonTelephone = (Button) findViewById(R.id.individualTelephone);
personNumberTelephone = object.getString("telephone");
callPersonTelephone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+personNumberTelephone));
startActivity(i);
}
});
if(personNumberTelephone==null || personNumberTelephone.equals("") || personNumberTelephone.equals(" ") || personNumberTelephone.equals("6855")){
callPersonTelephone.setClickable(false);
callPersonTelephone.setEnabled(false);
callPersonTelephone.setVisibility(View.GONE);
}
else{
callPersonTelephone.setEnabled(true);
callPersonTelephone.setClickable(true);
callPersonTelephone.setVisibility(View.VISIBLE);
}
emailPerson = (Button)findViewById(R.id.individualEmail);
object.put("useMasterKey", true);
personEmail= object.getString("email");
emailPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setData(Uri.parse("mailto:"));
i.setType("plain/text");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {personEmail});
startActivity(i);
}
});
if(personEmail==null || personEmail.equals("") || personEmail.equals(" ")){
emailPerson.setClickable(false);
emailPerson.setEnabled(false);
emailPerson.setVisibility(View.GONE);
}
else{
emailPerson.setEnabled(true);
emailPerson.setClickable(true);
emailPerson.setVisibility(View.VISIBLE);
}
individualOrganization.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String organizationID = personObject.getString("organizationID");
if(organizationID == null || organizationID.equals("")){
Toast.makeText(SingleIndividual.this, "Sorry No Organization Available!", Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(getApplicationContext(), SingleCorporate.class);
i.putExtra("objectId", organizationID);
i.putExtra("image", organizationID);
startActivity(i);
}
}
});
}
});
}
private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {
JSONObject jsonObject = new JSONObject();
parseObject.fetchIfNeeded();
Set<String> keys = parseObject.keySet();
for (String key : keys) {
Object objectValue = parseObject.get(key);
if (objectValue instanceof ParseObject) {
jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
} else if (objectValue instanceof ParseRelation) {
} else {
jsonObject.put(key, objectValue.toString());
}
}
return jsonObject;
}
}
Master Key can only be used from your server code, not client code. Making your users public read is an option, albeit a very poor one. It would be a better idea to have a cloud code function in which you validate a user session, ensure they're able to access this information, and do the query from there, using the master key.
I've been searching on here but can't seem to find what works. I'm trying to write a simple object list to a serialized file and can't seem to locate the file in android. It's my first time building an app and I had this working in netbeans by pointing to src/list.ser, however, this doesn't work in android studio. I guess my question is where do I place the ser file and how do I point to it in the code? Here is my code:
ListActivity:
public class ListActivity extends Activity implements Serializable {
private ArrayList<Item> list;
public List() throws Exception {
list = new ArrayList<Item>();
}
public void addItem(String name) {
list.add(new Item(name));
}
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.separator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("NOPE NOPE NOPE NOPE");
}
}
public void addItem(String name, int price) {
list.add(new Item(name, price));
}
public ArrayList<Item> populate() {
return list;
}
public void record() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("src/list.ser"));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private List tester;
private ListView lv;
private EditText gg;
private Button button;
private Button clearButton;
private ArrayList list;
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder + File.separator + "list.ser";
#Override
protected void onDestroy() {
try {
tester.addCurrentList();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create the list
lv = (ListView) findViewById(R.id.listDisplay);
ListView mine = lv;
list = new ArrayList<String>();
try {
tester = new List();
}
catch (Exception e) {
}
for (Item item : tester.populate()) {
list.add(item);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(arrayAdapter);
final TextView firstTextView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
clearButton = (Button) findViewById(R.id.clear);
gg = (EditText) findViewById(R.id.item);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = gg.getText().toString();
if (!no.isEmpty()) {
tester.addItem(no);
arrayAdapter.add(no);
arrayAdapter.notifyDataSetChanged();
gg.setText("");
}
}
});
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrayAdapter.clear();
arrayAdapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = lv.getItemAtPosition(position).toString();
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
First of all make sure that you have permission to write to the external storage.
as,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use,
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.seperator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("");
}
}
and the use create a file path from that as,
String filePath = pathToAppFolder +File.seperator + "Test.text";
and then where ever you want to read this file again, you can recreate the path. Because you have access to the context from the android code
EDIT
You can not access the context as you do in your code. You can do it in your onCreate method. I have added only the necessary parts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
filePath = pathToAppFolder + File.separator + "list.ser";
//create the list
Oh my god, I had to go into great lengths to answer your question. Here it is, Your List class is not an Activity in your application. It is just a class. So I suggest you to remove those inheritance first. remove this extends Activity. And I suggest you to change the List class name to something else. Because, List is a defined keyword and its not a best practice to do so.
Change the method in List Activity as below.
public void addCurrentList(String filePath) throws Exception
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void record(String filePath) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
In your MainActivity, onDestroy Method,
change the code to,
tester.addCurrentList(filePath);
So I'm trying to make a simple application that makes stores group events in a MySQL database then retrieves them for people to join. In this fragment I list all the events by using a JSONParser class to query the database. I use an Async class to do the querying. The fragment will initially query the db on startup or whenever the user decides to limit the scope of the events by selecting something in a spinner or when the user pushes a refresh button. I have been getting messages like
Choreographer﹕ Skipped 95 frames! The application may be doing too much work on its main thread.
while running the program and I'm not sure why. I think it might be because I call the Async class too much, but I'm not sure.
public class mainActivityFragment extends Fragment {
final public String information = "information";
public Spinner specifySubject;
private ArrayList<String> list = new ArrayList<>();
private ArrayList<EventObject> eventList = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ListView test;
ArrayAdapter adapter;
// url to create new product
private static String url_get_event = "";
private ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
test = (ListView) v.findViewById(R.id.listView);
new CreateNewProduct().execute();
if(pDialog.isShowing()){
pDialog.dismiss();
}
test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent in = new Intent(getActivity(), AttendInformation.class);
EventObject clickedEvent = eventList.get(position);
String[] testInformation = {clickedEvent.getTo().toString(), clickedEvent.getLocation(), clickedEvent.getTitle(), clickedEvent.getDurationString(), clickedEvent.getDescription(), clickedEvent.getSubject()};
in.putExtra(information, testInformation);
startActivity(in);
}
});
Button createEventButton = (Button) v.findViewById(R.id.Button2);
createEventButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(getActivity(), createEvent.class);
startActivity(in);
}
});
specifySubject = (Spinner) v.findViewById(R.id.spinner);
specifySubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (position == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[position];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button refresh = (Button) v.findViewById(R.id.leftButton);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (specifySubject.getSelectedItemPosition() == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[specifySubject.getSelectedItemPosition()];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
});
return v;
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONArray jsonArr = jsonParser.getJSONFromUrl(url_get_event);
for(int n = 0; n < jsonArr.length(); n++)
{
try {
JSONObject object = jsonArr.getJSONObject(n);
if(!list.contains(object.getString("title"))){
String[] time = object.getString("time").split(":");
time[1] = time[1].substring(0, 2);
EventObject tempEven = new EventObject(object.getString("title"), object.getString("location"), object.getString("description"), object.getString("subject"), 0, new TimeObject(Integer.parseInt(time[0]), Integer.parseInt(time[1])));
eventList.add(tempEven);
list.add(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
test.setAdapter(adapter);
pDialog.dismiss();
}
}
}