How to load, save, and show array to list? - java

I have XML layout like this:
[....textedit....][addbutton]
=======list1=========
=======list2=========
=======list3=========
=======list4=========
What to do if I want to Load and Show the list onCreate from SharePreferences, be able to Add "item" to the list, and save it to SharedPreferences? Any extra simple beginner explanation are welcome since I'm a total newb.
My code below is a big mess, and I got it 100% from stitching from one example to another example that I got from anywhere.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Toast;
import android.view.View;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends Activity {
String FileName = "myFile";
Button BtnSave;
EditText editName;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnSave = findViewById(R.id.btn1);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
lv = (ListView) findViewById(R.id.list1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,empty);
lv.setAdapter(adapter);
//Setting onClickListener on ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Item Clicked: "+i,Toast.LENGTH_SHORT).show();
}
});
editName = findViewById(R.id.edit1);
}
private void saveFile() {
String strName = editName.getText().toString();
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", strName);
editor.commit();
Toast.makeText(this,"Data Saved Successfully",Toast.LENGTH_SHORT).show();
}
}

I think this should help you.
fun addProduct(productsItem: Product) {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
var gson=Gson()
var cartProduct=getAllProducts()
cartProduct.add(productsItem)
var json=gson.toJson(cartProduct)
println(json)
sharedPreferences.edit().putString("cart_products",json).apply()
}
fun getAllProducts(): ArrayList<Product?> {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
val listType =
object : TypeToken<List<Product?>?>() {}.type
var productsItemList:ArrayList<Product?> = ArrayList();
val json=sharedPreferences.getString("cart_products",null)
if (json !=null){
var gson=Gson()
productsItemList=gson.fromJson(json,listType)
}
return productsItemList
}

Okay, so you need to:
1)input some word in EditText
2) show it in ListView
3) save it to preferences
right?
I think you must do next steps:
Create private ArrayList<String> list = new ArrayList();
When you input something in EditText and clicked on button, call list.add(editName.getText.toString()); and then call saveFile and save list.toString();
When you need to load file, create function
private void loadFile() {
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
String string = sharedPref.getString("name", "");
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(string.split(", ")));
}
Load in adapter your newList.

Related

ANDROID: Get next item from listview to editText after 1st item is saved

What I have: (1st Functionality)
I have a listview activity populated with items from JSON url. I have another activity where I get the listItem to editText field and then click "save", which saves the value to dB.
What I additionally want: (2nd Functionality)
When I click save, rather than going back to listview and select next listItem, I want the editText to fill the new listItem for me. But I am making errors in every step.
Below is the code that I have for 1st Functionality. I know it is just few lines to achieve the 2nd functionality but struggling with that.
The problem here is I cannot call the list String variable from one
activity to another and assign position or a counter to it. Suggest me
what to change here.
MainActivity.java (Class containing ListView populated with item from json url)
package com.example.app.listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> tutorialList = new ArrayList<String>();
private final static String URL = "-----json------url----file";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FetchDataTask().execute(URL);
}
private class FetchDataTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result= null;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(httpGet);
inputStream = response.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
Log.i("App", "Data received:" +result);
}
else
result = "Failed to fetch data";
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String dataFetched) {
//parse the JSON data and then display
parseJSON(dataFetched);
}
private String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private void parseJSON(String data){
try{
JSONArray jsonMainNode = new JSONArray(data);
int jsonArrLength = jsonMainNode.length();
for(int i=0; i < jsonArrLength; i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String postTitle = jsonChildNode.getString("codeid");
tutorialList.add(postTitle);
}
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Define a new Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, tutorialList);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, AddFlowerInfo.class);
intent.putExtra("Code", listView.getItemAtPosition(i).toString());
startActivity(intent);
}
});
}catch(Exception e){
Log.i("App", "Error parsing data" +e.getMessage());
}
}
}
}
editText.java (class containing editText field and save to dB)
package com.example.app.listview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;
import android.view.View;
public class AddFlowerInfo extends AppCompatActivity {
EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
private static final String TAG = "AddFlowerInfo";
Button savedata;
String noneditcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_flower_info);
editText = (EditText) findViewById(R.id.codeid);
savedata = (Button) findViewById(R.id.saveflowerinfo);
final String Codeholder = getIntent().getStringExtra("Code");
editText.setText(Codeholder);
}
public void dataflowerinfo(View view){
noneditcode = editText.getText().toString();
String method = "FlowerInfo";
BackgroundTask2 backgroundTask2 = new BackgroundTask2(this);
backgroundTask2.execute(method, noneditcode);
finish();
}
UPDATE AddFlowerInfo.java (OnCreate) and (OnClick)
public class AddFlowerInfo extends AppCompatActivity {
EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
private static final String TAG = "AddFlowerInfo";
Button savedata;
int i=0;
String noneditcode;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_flower_info);
editText = (EditText) findViewById(R.id.codeid);
savedata = (Button) findViewById(R.id.saveflowerinfo);
Intent i =getIntent();
final ArrayList<String> list = i.getStringArrayListExtra("key");
pos = i.getIntExtra("position", 0);
// final String Codeholder = getIntent().getStringExtra("Code");
editText.setText(list.get(pos));
savedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
startActivity(intent);
++pos;
if(pos<=list.size()-1)
list.get(pos);
}
});
Pass your data from activity like this
ArrayList<String> tutorialList = new ArrayList<String>();
Intent intent = new Intent(ActivityName.this, Second.class);
intent.putStringArrayListExtra("key", tutorialList);
startActivity(intent);
To retrive at AddFlowerInfo
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("key");
Then as you are retrieving data from list using position ,each time after saving call data at next position
You need to send complete array to AddFlowerInfo with the position, so change your onItemClick code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, AddFlowerInfo.class);
intent.putExtra("position", i);
intent.putStringArrayListExtra("array",tutorialList);
startActivity(intent);
}
});
Now in AddFlowerInfo:
Intent i = getIntent();
ArrayList<String> tutorialList = i.getStringArrayListExtra("array");
int pos=i.getIntExtra("position",0);
Use this position to get item from tutorialList.
To update data when user gets back to previous activity, place this code:
new FetchDataTask().execute(URL);
into onResume method.
Update
After saving first item to edit second item use:
++pos;
if(pos<=tutorialList.size()-1)
editText.setText(tutorialList.get(pos));
else
{
// you are after last item do whatever you want
}

Clicked list item into a String and transported to another activity

I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();

Delete a listview item from activity on button click from another activity

I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted to create a button that should delete the listview item that was clicked on. Here is the code I came with.
MainActivity
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
ArrayList<String> new_post = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView post_view = findViewById(R.id.news_feed);
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
//create click event and pass values of arrays
post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
intent.putExtra("Subject", new_subject);
intent.putExtra("Post", new_post);
intent.putExtra("position", id);
// getApplicationContext().startActivity(intent);
startActivityForResult(intent, 2);
}
});
//create button connection and create keylistener
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final ListView post_view = findViewById(R.id.news_feed);
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
//get subject and post from second activity
String new_subject_value = data.getStringExtra("newSubject");
String new_post_value = data.getStringExtra("newPost");
new_subject.add(new_subject_value);
new_post.add(new_post_value);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
if (requestCode == 2) {
if(resultCode == Activity.RESULT_OK){
String item2delete = data.getStringExtra("id");
new_subject.remove(item2delete);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
}
}
SecondActivity
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class full_post_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_post_activity);
final int id = getIntent().getExtras().getInt("id");
//create view reference
final TextView subject_edit = findViewById(R.id.subject_input);
final TextView post_edit = findViewById(R.id.post_input);
//create button reference
Button delete_button = findViewById(R.id.full_post_delete_btn);
//create click event
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("id", id);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");
String subject_string = subject_array.get(0);
String post_string = post_array.get(0);
//set textview text
subject_edit.setText(subject_string);
post_edit.setText(post_string);
}
}
My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?
You cannot get id value to MainActivity. This line in second activity cause problem
final int id = getIntent().getExtras().getInt("id");
In Main Activity, You can put id value using name index "position"
intent.putExtra("position", id);
So you should change them to
In Second Activity
final int id = getIntent().getExtras().getInt("position");
or Main Activity
intent.putExtra("id", id);
UPDATED try this in Main Activity
intent.putExtra("id", position);
If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).
You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter.
Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.
Edit: here are some code samples
Getter and Setter:
public ArrayList<String> getNewPost() {
return this.new_post;
}
public void setNewPost(ArrayList<String> np) {
this.new_post = np;
}
delete_button OnClick methode:
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity main=new MainActivity();
ListView<String> np=main.getNewPost();
np.remove("StringToRemove");
main.setNewPost(np);
}
});
I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.

RecycleView Wont update

I'm still new with both Java and android
My problem is that the recycleview only gets updated and adds the new added tag if I closed the app and run it again. How can I get the app to update the recycle view instantly to display the new tags.
java code
package com.deitel.favoritesites;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String SITES="Sites";
private EditText urlEditText; //where user enters the URL
private EditText tagEditText;
private FloatingActionButton saveFloatingActionButton;
private SharedPreferences savedSites;
private List<String> tags;
private SitesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
urlEditText = ((TextInputLayout) findViewById(
R.id.URLTextInputLayout)).getEditText();
urlEditText.addTextChangedListener(textWatcher);
tagEditText=((TextInputLayout)findViewById(R.id.tagTextInputLayout)).getEditText();
tagEditText.addTextChangedListener(textWatcher);
//get the shared prefrences containing the user saved URLs
savedSites = getSharedPreferences(SITES, MODE_PRIVATE);
//get the shared tags in an ArrayList then sort them
tags = new ArrayList<>(savedSites.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
//get reference to the recycle to configure it
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//use a linerlayout to display items in a vertical list
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//create recyclerView.Adopter to bind tags to the RecyclerView
adapter = new SitesAdapter(tags, itemClickListener, itemLongClickListener);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new ItemDivider(this));
//register listner to save a new or edit search
saveFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
saveFloatingActionButton.setOnClickListener(saveButtonListener);
updateSaveFAB();
}
private final TextWatcher textWatcher= new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateSaveFAB();
}
#Override
public void afterTextChanged(Editable s) {
}
};
//show or hide the saveFloatingActionButton
private void updateSaveFAB() {
//check if there is input in both EditButton
if (urlEditText.getText().toString().isEmpty() || tagEditText.getText().toString().isEmpty())
saveFloatingActionButton.hide();
else
saveFloatingActionButton.show();
}
//saveButtonListener save a tag query pair into sharedPrefrece
private final OnClickListener saveButtonListener=new OnClickListener() {
#Override
public void onClick(View view) {
String query = urlEditText.getText().toString();
String tag = tagEditText.getText().toString();
if (!query.isEmpty() && !tag.isEmpty()) {
//hide the virtual keyboard
((InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(),0);
addTaggedSites(tag, query);//add/update the search
urlEditText.setText("");//Clear queryEditText
tagEditText.setText("");//clear tagEditText
urlEditText.requestFocus();
}
}
};
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!tag.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
//itemClickListener launches web broswer to display search results
private final OnClickListener itemClickListener=new OnClickListener() {
#Override
public void onClick(View view) {
//get query string and create a URL represeting the search
String tag= ((TextView) view).getText().toString();
String urlString=getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag,""),"UTF-8");
//create an intent to lanuch a web broswer
Intent webIntent= new Intent(Intent.ACTION_VIEW,Uri.parse(urlString));
startActivity(webIntent);
}
};
//itemLongClickListener displays a dialog allowing the user to share edit or delete a saved search
private final OnLongClickListener itemLongClickListener= new OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
//get the tag that the user long touched
final String tag = ((TextView) view).getText().toString();
//creatw a new AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//set the alertDialog title
builder.setTitle(getString(R.string.share_edit_delete_title, tag));
//set list of items to display and create event handler
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0://share
shareSites(tag);
break;
case 1://edit
tagEditText.setText(tag);
urlEditText.setText(savedSites.getString(tag, ""));
break;
case 2: //delete
deleteSites(tag);
break;
}
}
}
);
//set the alertDialog negetive button
builder.setNegativeButton(getString(R.string.cancel), null);
builder.create().show();//display the alert dialog
return true;
}
};
//allow user to choose app for sharing URL of a saved search
private void shareSites(String tag){
//create the URL representing the search
String urlString= getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag, ""), "UTF-8");
//create an intent to share urlString
Intent shareIntent= new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
shareIntent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_message,urlString));
shareIntent.setType("text/plain");
//display app that can share plain text
startActivity(Intent.createChooser(shareIntent,getString(R.string.share_search)));
}
//delete search after user confirms
private void deleteSites(final String tag){
//create a new AlertDialog and set its message
AlertDialog.Builder confirmBuilder= new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirm_message, tag));
//cancel button configration
confirmBuilder.setNegativeButton(getString(R.string.cancel), null);
//positive DELETE button
confirmBuilder.setPositiveButton(getString(R.string.delete),new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog , int id){
tags.remove(tag);
//remove sharedPerefrences.Editor from Sharedprefrences
SharedPreferences.Editor preferenceEditor= savedSites.edit();
preferenceEditor.remove(tag);
preferenceEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
This is my adopter code
package com.deitel.favoritesites;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class SitesAdapter extends RecyclerView.Adapter<SitesAdapter.ViewHolder> {
private final View.OnClickListener clickListener;
private final View.OnLongClickListener longClickListener;
private final List<String> tags;
public SitesAdapter(List<String> tags, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
this.tags = tags;
this.clickListener = clickListener;
this.longClickListener = longClickListener;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView textView;
public ViewHolder(View itemView, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(clickListener);
itemView.setOnLongClickListener(longClickListener);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return (new ViewHolder(view, clickListener, longClickListener));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(tags.get(position));
}
#Override
public int getItemCount() {
return tags.size();
}
}
Change your code into this
if (!tags.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
Because, this below condition is always false
if(!tag.contains(tag))
Its because you are checking if a value contains in that value itself. SO it will be always true.
If you are checking the tag exist in the List<String> tags you should do like this below.
if(!tags.contains(tag))
change your code to....
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!this.tag.contains(tag)) {
this.tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
This may help:
create a setter method within your adapter allowing you to set/update the adapter ArrayList.
Whenever you make a change to your list i.e. remove Tag, pass this updated list to your adapter via your new setter method.
call notifyDataSetChanged().

I am trying to save a arrayadapter to sharedpreferences

I am trying to save a ArrayAdapter to shared preferences. I can get one string recovered using this code, but only one, I was not able to recover the entire ArrayAdapter.
package com.example.eduleito.listacompras;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edt_item;
private Button btn_limpar;
private ImageButton btn_adcionar;
private ListView lst_item;
private ArrayAdapter adp_item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
edt_item = (EditText) findViewById(R.id.edt_item);
btn_limpar = (Button) findViewById(R.id.btn_limpar);
btn_adcionar = (ImageButton) findViewById(R.id.btn_adcionar);
lst_item = (ListView) findViewById(R.id.lst_item);
btn_adcionar.setOnClickListener(this);
btn_limpar.setOnClickListener(this);
adp_item = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
lst_item.setAdapter(adp_item);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String item = sharedPreferences.getString("storeditem", "");
adp_item.add(item);
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
if (v == btn_adcionar) {
String item = edt_item.getText().toString();
adp_item.add(item);
savePreferences("storeditem", item);
edt_item.setText("");
} else if (v == btn_limpar) {
adp_item.clear();
}
}
}
Google:
Storage Options on developer.android.com
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.

Categories