Set text defined by a dynamically created EditText in android studio - java

I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}

I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}

Related

passing data from a bottom sheet dialog in first Activity to second Activity

I have a problem with passing data in android. let me explain my problem.
there are two activities called MainActivity and ProductInformationActivity.
in mainActivity there is a settingButton and onClickListener of the button, a bottom sheet dialog will open up. in bottomSheetDialog there are saveButton and three editText. whenever a user click on saveButton it should pass editTexts data's as PercentageClass to productInformationActivity . (percentage Class is a model to save percentages and pass theme between activities).
I create an interface Called "OnPercentageClicked" then I created an instance of this interface and create setter for that (setOnAddPercentageClicked).
in saveButtonListener I create instance of percentege class and set EditTexts data to it and finally I add percentage to interface's method.
this is mainACtivity:
public class MainActivity extends AppCompatActivity {
private View bottomSheetView;
private BottomSheetDialog bottomSheetDialog;
private OnAddPercentageClicked onAddPercentageClicked;
public void setOnAddPercentageClicked(OnAddPercentageClicked onAddPercentageClicked) {
this.onAddPercentageClicked = onAddPercentageClicked;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
ImageButton settingbtn = findViewById(R.id.activityMain_settingBTN);
ViewPager2 viewPager2 = findViewById(R.id.activityMain_viewpager);
TabLayout tabLayout = findViewById(R.id.activityMain_tabLayout);
MainViewPagerAdapter adapter = new MainViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
createDialog();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setText("کالا ها"); break;
case 1 : tab.setText("دسته بندی ها"); break;
}
}
});
tabLayoutMediator.attach();
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.show();
TextInputEditText firstPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_firstPercentageET);
TextInputEditText secondPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_secondPercentageET);
TextInputEditText thirdPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_thirdPercentageET);
Button percentageSaveButton = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_saveBTN);
assert percentageSaveButton != null;
percentageSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstPercentage.getText().length()>0 && secondPercentage.getText().length()>0 && thirdPercentage.getText().length()>0){
Percentage percentage = new Percentage();
percentage.setFirstPercentage(Integer.parseInt(firstPercentage.getText().toString()));
percentage.setSecondPercentage(Integer.parseInt(secondPercentage.getText().toString()));
percentage.setThirdPercentage(Integer.parseInt(thirdPercentage.getText().toString()));
onAddPercentageClicked.onButtonClicked(percentage);
bottomSheetDialog.dismiss();
Toast.makeText(MainActivity.this, "ذخیره شد", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "لطفا همه ی فیلد ها را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void createDialog(){
bottomSheetDialog = new BottomSheetDialog(MainActivity.this,R.style.bottom_sheet_dialog_theme);
bottomSheetDialog.setContentView(getLayoutInflater().inflate(R.layout.price_increment_percentage,(LinearLayout)findViewById(R.id.priceIncrementPercentage_container),false));
}
}
in productInfomation Activity i want to get the percentage class which i used in MainActivity.
so I implement OnAddPercentageClicked then I create an instance of main activity and call the setter which I created in MainActivity (setOnAddPercentageClicked).
this is productInformationActivity :
public class ProductInformation extends AppCompatActivity implements View.OnClickListener ,OnAddPercentageClicked{
private Percentage percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_information);
MainActivity mainActivity = new MainActivity();
mainActivity.setOnAddPercentageClicked(this);
TextView productName = findViewById(R.id.activityProductInformation_productNameTV);
TextView productPrice = findViewById(R.id.activityProductInformation_productPriceTV);
TextView productPriceFirstPercentage = findViewById(R.id.productPriceFirstPercentage);
TextView productPriceSecondPercentage = findViewById(R.id.productPriceSecondPercentage);
TextView productPriceThirdPercentage = findViewById(R.id.productPriceThirdPercentage);
TextView productCategoryName = findViewById(R.id.activityProductInformation_categoryNameTV);
ImageButton close = findViewById(R.id.activity_product_information_closeIB);
close.setOnClickListener(this);
if (percentage !=null){
productPriceFirstPercentage.setText("قیمت کالا +"+percentage.getFirstPercentage()+" درصد");
productPriceSecondPercentage.setText("قیمت کالا +"+percentage.getSecondPercentage()+" درصد");
productPriceThirdPercentage.setText("قیمت کالا +"+percentage.getThirdPercentage()+" درصد");
}
//
// }
if (getIntent().hasExtra("PRODUCT")){
Product product = getIntent().getParcelableExtra("PRODUCT");
productName.setText(product.getTitle());
productPrice.setText(String.valueOf(product.getPrice()));
productCategoryName.setText(String.valueOf(product.getCategoryId()));
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.activity_product_information_closeIB){
finish();
}
}
#Override
public void onButtonClicked(Percentage percentage) {
Log.i(TAG, "onButtonClicked: " + percentage);
this.percentage = percentage;
}
}
and when i run this code i get an error which says that the interface in MainActicvity is null.
would you please help me ?
thanks.

Not able to pass data between activities.Data is blank

I am trying to pass some data from one activity to another and I have made a toast in the other activity to see if data is being passed.When the toast shows up it is blank.I have done everything right and tried many different times with different methods I have also created another app but the problem still stays.It gives me null.
My java code in the first activity
public class titleandcuisine extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public static final String TITLE_GET = "title";
public static final String CUISINE_GET = "cuisine";
ImageView imageView;
Button button;
Spinner spinner;
EditText dish;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titleandcuisine);
dish = findViewById(R.id.editText);
spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cuisines,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
button = findViewById(R.id.next);
imageView = findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), homepage.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = dish.getText().toString();
String text2 = spinner.getSelectedItem().toString();
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(TITLE_GET,text);
data.putExtra(CUISINE_GET,text2);
startActivity(data);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Second activity java code
public class reviewactivity extends AppCompatActivity {
TextView cuisine,title;
ImageView displayimage,back;
Uri myUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviewactivity);
Intent intent = getIntent();
String titleget = intent.getStringExtra(titleandcuisine.TITLE_GET);
String cuisineget = intent.getStringExtra(titleandcuisine.CUISINE_GET);
Toast.makeText(this, titleget + cuisineget, Toast.LENGTH_SHORT).show();
cuisine = findViewById(R.id.reviewcuisine);
title = findViewById(R.id.reviewtitle);
back = findViewById(R.id.backtopostvideo);
displayimage = findViewById(R.id.reviewdisplaimage);
// cuisine.setText(cuisineget);
// title.setText(titleget);
// myUri = Uri.parse(uri);
displayimage.setImageURI(myUri);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),videopost.class));
}
});
}
}
You need to read the text from the EditText when the button is clicked. Something like:
title = dish.getText().toString(); // Add this
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(Intent.EXTRA_TEXT, title);
...
One more thing: You are trying to read the Intent.EXTRA_TEXT at the reviewactivity activity. However, nothing is starting that activity (at least within the piece of code that you shared).

How to make an activity not reload/refresh every time I get into it?

I have an activity and I don't want it to reload every time I get into it. I want it to show the information which had the last time i got into it.
But I also want to have one Button in another activity that will refresh the other activity, so that when i get into it the information has changed. I say that the content changes because the activity show different recyclerviews everytime you get into it.
That is my MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And that is my activityWithButton.java:
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
Please help I don't know what to do.
Thanks
You have two fairly straight-forward options, SharedPreferences and SavedInstanceState.
SharedPreferences, you can access and save data anywhere context is available within your app assigning a key, value pair to any data to later be retreived. Generally you will want to save the data during certain lifecycle events such as onStop and retreive it somewhere else once the activity returns:
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
#Override
public void onStop() {
super.onStop();
editor.putString("key", "My string");
editor.commit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String myValue = editor.getString("key");
}
SavedInstanceState, comes with the onCreate override method in your activities. Utilising the available override method onSaveInstanceState, pass in the required data when the activity is temprarily destroyed to be retreived on its recreation.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String myValue = savedInstanceState.getString("key");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("key", "My string");
super.onSaveInstanceState(outState);
}
Further reading https://developer.android.com/guide/components/activities/activity-lifecycle

How to make an activity not reload every time I get into it, and make a button reload it?

I have an activity and I don't want it to reload every time I get into it. I want it to show the information which had the last time I got into it.
But I also want to have one Button in another activity that will refresh the other activity, so that when I get into it the information has changed.
I say that the content changes because the activity shows different recyclerviews every time you get into it.
And that is my activityWithButton.java:
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
That is my MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
Please help I don't know what to do.
Thanks
you can`t prevent from reloading activity but you can retrieve last state of your activity every time onCreate() method is called by using savedInstanceState like this:
TextView textView;
// some transient state for the activity instance
String gameState;
#Override
public void onCreate(Bundle savedInstanceState) {
// call the super class onCreate to complete the creation of activity like
// the view hierarchy
super.onCreate(savedInstanceState);
// recovering the instance state
if (savedInstanceState != null) {
gameState = savedInstanceState.getString(GAME_STATE_KEY);
}
// set the user interface layout for this activity
// the layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// initialize member TextView so we can manipulate it later
textView = (TextView) findViewById(R.id.text_view);
}
// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}
// invoked when the activity may be temporarily destroyed, save the instance state here
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(GAME_STATE_KEY, gameState);
outState.putString(TEXT_VIEW_KEY, textView.getText());
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}
for more info about savedInstanceState and android lifecycles look at the official docs

How to display data entered in one activity in another activity in list one by one in android?

FirstActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Name = etName.getText().toString();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
// Create a bundle object
intent.putExtra("NAME", Name);
startActivity(intent);
}
});
My Second Activity.java is as follows:
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
String UName;
String iName;
ListView lvName;
Button btnBack;
Bundle savedInstanceState;
#Override
protected void onCreate(Bundle b) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
b = getIntent().getExtras();
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
UName=b.getString("NAME");
list.add(UName);
adapter.notifyDataSetChanged();
lvName.setAdapter(adapter);
lvName.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),
ThirdActivity.class);
// Create a bundle object
intent.putExtra("ITEMNAME", item);
startActivity(intent);
}
});
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
}
My problem is whenever I click on back button, activity is restarted. So that first item in list is overwritten by second item. I want to get the output as list(items one by one) in second activity, whatever the data I enter in first activity. How can I do this?
For example when I enter ABC in edittext its displaying the same data ABC in list.Its good.
But when I click on back button and again enter any data in edittext its not displaying the data as second item in list but it is over writing the first item.This is the thing I wanna get to be solved...
You can put all items into intent in the first activity:
intent.putStringArrayListExtra(ITEMS, list);
And then you can extract them from intent in the second activity:
List<String> items = getIntent().getStringArrayListExtra(ITEMS);
use the extends Application class
public class MyGlobal extends Application {
public ArrayList<String> selectedAppsPackageNames = new ArrayList<String>();
}
for getting this in your activity
private MyGlobal mMyGlobal = (MyGlobal) getApplicationContext();
declare in manifest inside the Application Tag(give the path)
<application
android:name="com.afbb.lockaddicted.core.MyControlList"
..............
.........
</application>
You Just have to create the global list somewhere in your app like you can create Singletone or Application Class where you have to store your username List.
In below code you have to update your arrayList in first activity and you have to get your nameList in SecondActivity
public class MySingleton
{
private static MySingleton _instance;
private ArrayList<String> nameList;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
public ArrayList<String> getNameList(){
return nameList;
}
public void setNameList(ArrayList<String> nameList(){
nameList = nameList;
}
}
You can save the names in the FirstActivity to shared preferences, with an id. Then retrieve those values in the SecondActivity. Also do not forget to clear the shared preferences when you destroy your FirstActivity.
FirstActivity
public class FirstActivity extends Activity {
private EditText etName;
private Button btnOk;
private String name;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id++;
SharedPreferences.Editor editor = getSharedPreferences("shared_pref", MODE_PRIVATE).edit();
editor.putString(Integer.toString(id), etName.getText().toString());
editor.commit();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences("shared_pref", MODE_PRIVATE).edit().clear().commit();
}
}
SecondActivity
public class SecondActivity extends Activity {
private ArrayList<String> list = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private String UName;
private String iName;
private ListView lvName;
private Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lvName.setAdapter(adapter);
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", MODE_PRIVATE);
Map<String,String> names = (Map<String, String>) sharedPreferences.getAll();
if(names != null){
for(String value: names.values()){
list.add(value);
}
adapter.notifyDataSetChanged();
}
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}

Categories

Resources