Dynamically created EditTexts by Add button, and also I have assigned them unique ID's using setId(), Now what I want to do is to get values from the dynamically created EditTexts when the user taps a button, then store all of them as Sharedpreferences
This is the code
Thank you guys
ADDED CODES
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave, btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout) findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(ActivityOptions.this);
ed.setId(ed.generateViewId());
ed.setTag(allEds.size());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
EditText ed = new EditText(ActivityOptions.this);
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
}
});
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
}
}
While creating every new EditText, you generate ids by setId() but I don't see how these are going to be useful in your code.
Instead set the tag of the EditText like this:
ed.setTag(allEds.size());
and add it to the list:
allEds.add(ed);
Now in each EditText's tag you have stored its ordinal number (zero based) in the list and when you want to store its value in SharedPreferences you can do:
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
editor.commit();
or by using a loop through all the items in the list:
for (EditText ed : allEds) {
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
}
editor.commit();
This way you stored all the text values of the EditTexts with keys like:
"key0", "key1", "key2",...
Edit
Of you want to open another activity and pass the list to it:
Intent intent = new Intent(this, AnotherActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString())
}
intent.putExtra("Text", (Serializable) allTexts);
and in the other activity's onCreate():
ArrayList<String> list = (ArrayList<String>) getIntent().getSerializableExtra("Texts");
Edit2
Replace the code in btnSave.setOnClickListener() and the lines below, with this code:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
startActivity(intent);
}
});
You forgot to add the EditText's to your list, so the save button will know about them and get their inputs.
After that you need to specify the save button (which I believe you did, but I cannot see a reference of it in your code).
Lastly just implement the logic for the save button in its onClick() (save in SharedPreferences).
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave,btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout)findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(MainActivity.this);
ed.setId(ed.generateViewId());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (EditText ed : allEds) {
editor.putString("saved_text_key", ed.getText().toString());
editor.commit();
}
}
});
}
Related
I am trying to bring all the items from the ArrayList getting saved in EditActivity to the MainActivity using SharedPreferences. But only the last entered data gets displayed in the ListView on the first MainActivity. How can I make all the text entered into the EditText get displayed as a different item in the ListView and not replace the earlier item.
Here is my Code:
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView list;
private Button nextButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
nextButton = (Button) findViewById(R.id.nextButton);
loadData();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
list.setAdapter(adapter);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextActivity();
}
});
}
public void nextActivity(){
Intent intent = new Intent(this, EditActivity.class);
startActivity(intent);
}
public void loadData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
arrayList = gson.fromJson(json, type);
if(arrayList == null){
arrayList = new ArrayList<String>();
}
}}
EditActivity
public class EditActivity extends AppCompatActivity {
private EditText input;
private Button addButton;
public ArrayList<String> list = new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
input = (EditText) findViewById(R.id.input);
addButton = (Button) findViewById(R.id.addButton);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
}
public void saveData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString("list", json);
editor.apply();
}}
I think you forget to add item to list before save and thus the result is you are saving only the last item.
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
list.add(getInput); //add this line
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
I have an app, where a user can enter a number and save to listView. The app is split into 3 activities.
The first activity is the MainActivity, which does something else. The second activity is where I enter a number and save it. The code Is below
public class HomeTeamScored extends Activity {
protected static EditText display;
protected static ArrayAdapter<String> adapter;
Button addButton;
CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_home_goal_player);
display = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.btn);
checkBox = (CheckBox) findViewById(R.id.checkBox);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
protected void SavePreferences() {
// TODO Auto-generated method stub
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0; i < adapter.getCount(); ++i){
// This assumes you only have the list items in the SharedPreferences.
editor.putString(String.valueOf(i), adapter.getItem(i));
}
editor.commit();
}
}
In my third activity, I retrieve the saved number.
public class ScoreBoardOverview extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_score_board_overview);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv = (ListView) findViewById(R.id.listView);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
loadPreferences();
}
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
}
All this is working fine, and it adds a number to listView, but the problem is that it overrides the old value, were instead it should add a second row.
Anyone who can help??
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
here your adapter item size will be 0 when you call second activity each time. if you want to add second or third item you should write your
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
method in second activity too. and call loadPreferences() after this line
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
your adapter data size will be changed.
I am trying to pass an array list to another activity but it seems that is not enough. I searched all day to pass the array list with "intent" but with no success. I wrote a code for learning purposes. How to pass the data and show the Arraylist in a second activity?
The action button is btn_save. If you want further details let me know.
The code is in
MainActivity (first activity):
public class MainActivity extends AppCompatActivity {
ArrayList<String> addArray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editTextOne = (EditText) findViewById(R.id.editTextOne);
final EditText editTextTwo = (EditText) findViewById(R.id.editTextTwo);
Button btn_showText = (Button) findViewById(R.id.buttonShow);
final TextView textView = (TextView) findViewById(R.id.textResults);
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
Button btn_close = (Button) findViewById(R.id.btn_close);
Button btn_save = (Button) findViewById(R.id.btn_save);
final ListView showMe = (ListView) findViewById(R.id.list_items);
btn_showText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
if (text.length() == 0 || textTwo.length() == 0){
textView.setText("You must enter Name & Surname");
}else {
textView.setText(Html.fromHtml(
"<font color=\"red\">"+ text + "</font> " +
"<font color=\"blue\"><b>" + textTwo + " </b></font>"));
}
}
});
btn_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Context context = getApplicationContext();
// CharSequence mytext = "Hahahaha";
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,mytext,duration);
// toast.show();
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
String getInput = text + textTwo;
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item already Added!", Toast.LENGTH_LONG).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "Input field is empty", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
((EditText)findViewById(R.id.editTextOne)).setText(" ");
((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
}
});
}
public void onButtonClick(View v){
if (v.getId() == R.id.btn_list){
Intent i = new Intent(MainActivity.this, ListOfNames.class);
startActivity(i);
}
}
}
ListOfNames second activity: (almost empty)
public class ListOfNames extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
}
}
If you are trying to pass a arraylist of string then it will be easy. Just pass arraylist with intent like this:
ArrayList<String> list = new ArrayList<String>();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putStringArrayListExtra("key", list);
startActivity(intent);
And receive it in ActivityTwo like this:
ArrayList<String> list = getIntent().getStringArrayListExtra("key");
I found a temporary solution for this (The app is not broke). The only problem is the arraylist didn't increased. It contains and show only the last value.
Main Activity:
...
else{
// addArray.add(getInput);
// ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
// showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
intent.putExtra("data", getInput);
startActivity(intent);
// ((EditText)findViewById(R.id.editTextOne)).setText(" ");
// ((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
...
ListOfNames (Second Activity):
public class ListOfNames extends Activity {
ArrayList<String> addArrayT = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("data");
Button btn_more = (Button) findViewById(R.id.btn_more);
ListView showMe = (ListView) findViewById(R.id.list_items);
addArrayT.add(data);
ArrayAdapter<String> adapterT = new ArrayAdapter<>(ListOfNames.this, android.R.layout.simple_list_item_1, addArrayT);
showMe.setAdapter(adapterT);
}
public void onClickMore(View v){
if (v.getId() == R.id.btn_more){
Intent i = new Intent(ListOfNames.this, MainActivity.class);
startActivity(i);
}
}
}
sharedpreferences does not store data. Error shows in getSharedPreferences this method. Error is in DetailPref key. And catlog error is : Unable to start activity ComponentInf com.example.add_fetch_data.MainActivity java.lang.NullPointerException. please any one help me what to do to store data Because I am new in Android.
public class MainActivity extends Activity {
Button addData, viewData, saveData, fetchData;
EditText editName, editAdd;
TextView textName, textAdd;
Dialog AddDialog, ViewDialog;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("DetailPref", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences.Editor edit = pref.edit();
// Storing data using SharedPreferences
edit.putString("Name", name);
edit.putString("Address", address);
edit.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});
}
}
Try edit.apply() instead of commit().
Please clear your sharedPreferences first to test. You can do this with code or in application settings
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
And, you are using 3 different tags. "Name", "Address" and "DetailPref":
FIRST OPTION
You need to save all in DetailPref.
Maybe you need a structure for this. Something like this
{"Name": "xxxxx" , address: "home"}
So you can do this:
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPref.edit();
JSONObject jsonToSave = new JSONObject();
jsonToSave.put("Name", name);
jsonToSave.put("Address", address);
// Storing data using SharedPreferences
edit.putString("DetailPref", jsonToSave.toString());
edit.commit();
AddDialog.dismiss();
}
SECOND OPTION
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefName = getSharedPreferences("Name", MODE_PRIVATE);
prefAddress = getSharedPreferences("Address", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPrefearences.Editor editName = prefName.edit();
SharedPreferences.Editor editAddress = prefAddress.edit();
// Storing data using SharedPreferences
editName.putString("Name", name);
editAddress.putString("Address", address);
editName.commit();
editAddress.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});
I need to creat a linearLayout containing some views when clicking on a button , thsi button is triggerd by an action made in another activity ,so i used a performClick , but it seems that doesn't work ; here is my code :
Button click = new Button(rootView.getContext());
SharedPreferences participant;
Editor editor;
SharedPreferences visible;
Editor vis;
participant = rootView.getContext().getSharedPreferences("participant", rootView.getContext().MODE_PRIVATE);
visible = rootView.getContext().getSharedPreferences("visible", rootView.getContext().MODE_PRIVATE);
editor = participant.edit();
final String name= participant.getString("key", "toto");
final String view = participant.getString("view","non");
if(view.equalsIgnoreCase("yes")) click.performClick();
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
// Creating a new LinearLayout
final LinearLayout ln = new LinearLayout(v.getContext());
// Setting the orientation to horizontal
ln.setOrientation(LinearLayout.HORIZONTAL);
formbis.addView(ln);
TextView tv1 = new TextView(v.getContext());
tv1.setText(name);
tv1.setTextSize(14);
tv1.setTypeface(null, Typeface.BOLD);
tv1.setPadding(0, 15, 0, 10);
tv1.setLayoutParams(new LayoutParams(
500,
LayoutParams.WRAP_CONTENT));
ln.addView(tv1);
final ImageButton edit = new ImageButton(v.getContext());
Drawable checked = getResources().getDrawable( R.drawable.content_edit );
edit.setImageDrawable(checked);
edit.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
edit.setBackgroundColor(Color.WHITE);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
i = new Intent(v.getContext(), EditParticipantActivity.class);
startActivity(i);
}
});
ln.addView(edit);
final ImageButton delete = new ImageButton(v.getContext());
Drawable deleted = getResources().getDrawable( R.drawable.content_discard );
delete.setImageDrawable(deleted);
delete.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
delete.setBackgroundColor(Color.WHITE);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(v.getContext(),
"Deleted ", Toast.LENGTH_LONG).show();
formbis.removeView(ln);
}
});
ln.addView(delete);
ln.setVisibility(View.GONE);
if(view.equalsIgnoreCase("yes"))ln.setVisibility(View.VISIBLE);
}
});
EDIT
Here (another Activity ) I set the value to yes so that the linearLayout gets added to the view of the first activity
Button members = (Button) findViewById(R.id.submit);
members.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
name = firstname.getText().toString();
editor.putString("key", name);
editor.commit();
editor.putString("view", "yes");
editor.commit();
i = new Intent(v.getContext(), ManageActivity.class);
startActivity(i);
//finish();
}
});
Define the onClickListener first.
Then call the if(view.equalsIgnoreCase("yes")) click.performClick(); line after defining the click.onClickListner code.