Reputation: 208
I have activity that has Listview. Data from the ListView must be save in sharedPreferences. And I have two methods LoadPreferences and SavePreferences. But the problem is that they don't work together. Both methods work then I use them separatly, into one adapter. But I need both of them. There I make mistake? MainActivity is:
public class MainPage extends AppCompatActivity {
SharedPreferences prefs;
EditText input;
Button btnAdd, btnDel;
ListView list;
ArrayAdapter<String> adapter, adapter2;
public static ArrayList<String> taskList = new ArrayList<String>();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prefs = getSharedPreferences("myUsers", MODE_PRIVATE);
input = (EditText) findViewById(R.id.txtItem);
btnAdd = (Button) findViewById(R.id.btnAdd);
list = (ListView) findViewById(R.id.list1);
btnDel = (Button) findViewById(R.id.btnDel);
userName();
LoadPreferences();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
///adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,taskList);
list.setAdapter(adapter);
list.setAdapter(adapter2);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = input.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
}
}
);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1, menu);//What Options Menu to present
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String msg = "";
switch (item.getItemId()) {//selected menu item
case R.id.first:
///msg="first selected";
Logout();
break;
case R.id.second:
msg = "Second selected";
break;
}
/// Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
public void Logout() {
JSONObject userJson = getUserByName(userName());
Toast.makeText(this, "found" + userJson, Toast.LENGTH_LONG).show();
String status = "status";
try {
userJson.put(status, false);//local json change
prefs.edit().putString(userJson.getString("name"), userJson.toString()).commit();//save changed JSON
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(this, Login.class);
this.startActivity(i);
}
private JSONObject getUserByName(String name) {
try {
return new JSONObject(prefs.getString(name, ""));
} catch (JSONException e) {
return null;
}
}
public String userName() {
String msg =null;
Intent i = getIntent();//get Intent - that started this Activity
if (i.hasExtra("userName")) {//if has data by key: "msg"
msg = i.getStringExtra("userName");//get data by key "msg" as String
//// Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
return msg;
}
protected void SavePreferences() {
JSONObject ExistUser = getUserByName(userName());
////Toast.makeText(this,ExistUser+"found",Toast.LENGTH_LONG).show();
String ag = input.getText().toString().trim();
if (ag.length() != 0) {
taskList.add(ag);
input.setText("");
try {
ExistUser.put("task", new JSONArray(taskList));
prefs.edit().putString(ExistUser.getString("name"), ExistUser.toString()).commit();
Toast.makeText(this, ExistUser + "found", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
public ArrayList<String> LoadPreferences() {
JSONObject ExistUser = getUserByName(userName());
try {
if(ExistUser.getJSONArray("task")!=null){
JSONArray jArray = ExistUser.getJSONArray("task");
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
taskList.add(jArray.getString(i));
}
}
}
else{
return null;
}
} catch (JSONException e) {
e.printStackTrace();
}
return taskList;
}
}
Layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="@string/hintTxtItem"
/>
<Button
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/lblBtnAdd"
android:layout_toRightOf="@id/txtItem"
android:background="#009900"
/>
<TextView
android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtItem"
android:text="@string/txtEmpty"
android:gravity="center_horizontal"
/>
<ListView
android:id="@+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtItem"
android:choiceMode="multipleChoice" >
</ListView>
<Button
android:id="@+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/lblBtnDel"
android:background="#009900"
/>
</RelativeLayout>
Upvotes: 0
Views: 589
Reputation: 191711
It's unclear what the problem is, but here is what I would try
You want to load strings from an array by username...
public ArrayList<String> loadUserTasks(String userName) {
List<String> taskList = new ArrayList<String>();
JSONObject user = getUserByName(userName);
try {
JSONArray tasks = user.getJSONArray("task");
if(tasks != null){
for (int i = 0; i < jArray.length(); i++){
taskList.add(tasks.getString(i));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return taskList;
}
Then, when you create the adapter, you can get that list.
String userName = userName();
List<String> tasks = loadUserTasks(userName);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tasks);
list.setAdapter(adapter);
And you want to save strings from an adapter into JSON
protected void saveTasksForUser(String userName) {
// Store value currently in input field
String currentTask = input.getText().toString().trim();
if (!currentTask.isEmpty()) {
adapter.add(currentTask);
input.setText("");
}
// Save values from adapter into JSON
JSONArray tasks = new JSONArray();
for (int i = 0; i < adapter.getCount(); i++) {
tasks.put(adapter.getItem(i));
}
// Update the User
JSONObject user = getUserByName(userName);
user.put("task", tasks);
prefs.edit().putString(userName, user.toString()).commit();
}
Upvotes: 0