Reputation: 426
I am trying to save a simple name and load it – just to make everything clear to myself – there is no error, but when it loads it loads something different. It has something to do with Android itself.
Here is the class where I save and load (I don't use any libraries):
public class Serializer
{
private Context context;
private String fn;
public Serializer(Context con , String filename){
this.context = con;
this.fn = filename;
}
public void save(ArrayList<String> usernames) throws JSONException, IOException {
JSONArray JsonArray = new JSONArray();
JSONObject obj = new JSONObject();
for(String s : usernames){
obj.put("username" , s);
JsonArray.put(obj);
}
Writer writer = null;
OutputStream out = context.openFileOutput(fn , 0);
writer = new OutputStreamWriter(out);
writer.write(JsonArray.toString());
if(writer != null){
writer.close();
}
}
public ArrayList<String> load () throws IOException, JSONException {
ArrayList<String > strings = new ArrayList<>();
InputStream in = context.openFileInput(fn);
InputStreamReader reader = new InputStreamReader(in);
BufferedReader Reader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String Line;
while((Line = Reader.readLine() ) != null){
builder.append(Line);
}
JSONArray array = (JSONArray)new JSONTokener(builder.toString()).nextValue();
for(int i = 0 ; i < array.length() ; i++){
String jack = (String) array.getJSONObject(i).get("username");
strings.add(jack);
}
if(reader!=null){
reader.close();
}
return strings;
}
}
Here is my main activity whose layout is a simple layout with one TextEdit:
public class MainActivity extends AppCompatActivity {
Serializer serializer;
ArrayList<String> usernames;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serializer = new Serializer(this,"Jacop");
TextView txtView = findViewById(R.id.txt);
usernames = new ArrayList<>();
usernames.add(txtView.toString());
try {
ArrayList<String> username = serializer.load();
txtView.setText(username.get(0));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
try {
serializer.save(usernames);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output (e.g what the text view shows after I close and reopen the app).
android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt}
Upvotes: 1
Views: 71
Reputation: 21043
You are adding an Object
as String .
usernames.add(txtView.toString());
Change it to
usernames.add(txtView.getText().toString());
toString()
is a method of Object class so each class have it . and android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt}
is the string representation of the TextView
object .
Upvotes: 1