sending and receiving Arraylist using intent? Android - java

I'm trying to create a list of countries, that's to be added by the user during run time.
I'm using intent & adapter, and listview to show the countries.
When the activity start"MyCountries"the user click on the button add country, a new activity will start" Add Country", my question here is why I can't see any country on the list? i'm I sending and receiving correctly?
code for MyCountries:
public class MyCountries extends Activity {
private ListView lv;
private ArrayAdapter<String> adapter;
private ArrayList<String>list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_countries);
//Button compute=(Button)findViewById(R.id.cancel);
lv=(ListView)findViewById(R.id.listView1);
list=new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
Intent i = getIntent();
list = i.getStringArrayListExtra("country&year");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_countries, menu);
return true;
}
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddCountry.class);
startActivityForResult(intent,1);
}
code for "AddCountry"
public class AddCountry extends Activity {
private EditText name;
private EditText year;
public String country_name;
public int visited_year;
public ArrayList<String>arr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_country);
name = (EditText) findViewById(R.id.country);
year = (EditText) findViewById(R.id.year);
arr= new ArrayList<String>();
Button button=(Button)findViewById(R.id.add);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
//Toast.makeText(this, "Add was clicked", Toast.LENGTH_LONG).show();
//new activity
Intent sending = new Intent();
country_name = name.getText().toString();
visited_year = Integer.parseInt(year.getText().toString());
for(int i=0;i<arr.size();i++){
arr.add(country_name+""+visited_year);
//startActivity(sending);
}
sending.putStringArrayListExtra("country&year", arr);
}
}

you are sending empty list to adapter:
list=new ArrayList<String>();// empty list
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
// get data from intent(to your list) before initializing your adapter and you don't need to notify
list = i.getStringArrayListExtra("country&year");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);

Related

filling listView when button clicked in other activity

Is there a way how you can add a string to an arraylist, which then fills a listview when a button is clicked in another activity? To be more clear: In activity A, I have a Listview and a menu item where I can go to Activty B. In Activtiy B I have got an EditText and a button. I want to achieve that everytime I click on the Button in activty B, the new String gets listed in the Listview. As a "clicklistener" I used a boolean. Is there a better way? Because with the code below I can only make one list entry which gets changed by every next button click.
Java Code Activity A:`package com.example.schoolapp;
public class MainActivity extends AppCompatActivity {
TextView tvSubjects;
ListView listView;
static ArrayList<String> arrayList = new ArrayList<>();
static ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSubjects = findViewById(R.id.tv_subjects);
listView = findViewById(R.id.listView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
if (NewNoteActivity.buttonClicked){
Intent intent = getIntent();
String string = intent.getStringExtra("Subject");
arrayList.add(string);
arrayAdapter.notifyDataSetChanged();
}
}
//Code for the menu, works fine
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.item_newSubject:
Intent intent = new Intent(this, NewNoteActivity.class);
startActivity(intent);
return true;
default:
return false;
}
}
}`
Java Code for Activity B:
public class NewNoteActivity extends AppCompatActivity {
EditText et_subject;
Button btn_createSubject;
String subject;
static boolean buttonClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
et_subject = findViewById(R.id.et_subject);
btn_createSubject = findViewById(R.id.btn_createSubject);
btn_createSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonClicked = true;
subject = et_subject.getText().toString();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Subject", subject);
startActivity(intent);
}
});
buttonClicked = false;
}
}

How to send a value from TextView to RecyclerView in another Activity

I'm trying to send a value from TextView to RecyclerView (in an another Activity).
MainActivity.class
There is i want to use a method onClickYes for send each of word to my recyclerView in an another activity.
public class MainActivity extends AppCompatActivity {
TextView display, progress;
private List<String> worldList;
private ArrayList<RecyclerItems> recyclerItems;
private WordDataBase wordDatabaseForYes;
int counter = 1;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.dispalay);
progress = findViewById(R.id.progress);
recyclerItems = new ArrayList<>();
worldList = new ArrayList<>();
worldList.add("cat");//i want to display this word firstly
worldList.add("dog");//it after click
worldList.add("monkey");//after it
worldList.add("bird");//after it
worldList.add("fish");//etc
worldList.add("home");//etc
worldList.add("car");//etc
}
public void onClickYes(View view) {
if (i >= worldList.size()) return;
display.setText(worldList.get(i));
progress.setText(counter + "");
//заполняем наш recyclerView
//Intent intent = new Intent(MainActivity.this, YesActivity.class);
//intent.putExtra("word", user + ", вам передали: " + gift);
//startActivity(intent);
i++;
counter++;
}
public void onClickNo(View view) {
Toast.makeText(this, "Size is " + worldList.size(), Toast.LENGTH_SHORT).show();
//recyclerItems.add(new RecyclerItems(worldList.get(i)));
i = 0;
counter = 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
startActivity(intent);
break;
case R.id.no:
intent = new Intent(MainActivity.this, NoActivity.class);
startActivity(intent);
break;
case R.id.about:
Toast.makeText(this, "By SaturnPRO", Toast.LENGTH_SHORT).show();
//openDialogAbout
break;
}
return true;
}
}
My Second Activity
public class YesActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<RecyclerItems> yesWordList;
private WordDataBase wordDatabaseForYes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yesWordList = new ArrayList<>();
recyclerView = findViewById(R.id.rvYes);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(yesWordList);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
}
Also i have an Adapter but i couldn't show it here.
How can i do it? enter code here Please help.
Send the word in intent extras:
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
intent.putExtra("key", worldList.get(i));
startActivity(intent);
break;
In your second activity:
String name = intent.getStringExtra("key");
You can make the wordList a static member. Then you can access it in your adapter.

How to add items from Edittext to listview?

I have been striving for a couple of hours but I still can't figure out why my latest edittext value overwrites my old listview item.
The problem is that, suppose I type a string s1 in my edittext and press the add to listview button, then the string s1 gets entered successfully. Now if I type a string s2 in my edittext and press the add to listview button, the string s2 now replaces s1 in the listview, and thus now it is just showing s2 in my listview. How do I fix this?
Here is my code:
String str=edittext.getText().toString();
List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(str.length()!=0) {
list.add(str);
}
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
});
Edit: I am trying to take the input string from one activity and trying to add it to the listview of another activity. This is where the problem arises. Please help me.
1st Activity:
public static String str;
add.setOnClickListener(new (new View.OnClickListener() {
#Override
public void onClick(View view) {
str=edittext.gettext().toString();
}
});
2nd Activity:
List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
if (Main_activity.i == R.id.event_1 || Main_activity.i == R.id.rem_1) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
if(str.length()!=0) {
list.add(str);
adapter.notifyDataSetChanged();
}
else{
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "No
text found", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
public class ListViewExample extends AppCompatActivity {
List<String> list = new ArrayList<String>();
ListView listView;
EditText editText;
ArrayAdapter<String> adapter;
FloatingActionButton fab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view_example);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.listView);
editText = (EditText) findViewById(R.id.et);
fab = findViewById(R.id.fab);
adapter = new ArrayAdapter<String>(ListViewExample.this, android.R.layout.simple_list_item_multiple_choice, list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString().trim();
if(!name.isEmpty()) {
list.add(name);
adapter.notifyDataSetChanged();
editText.setText("");
}
}
});
}
This is my Activity, and this is work for me.
Although the above code is correct, please try to modularize your code. It will make your life easier when comes to debugging it and sequentially follow it. See below
private final List<String> list = new ArrayList<>();
private ArrayAdapter<String> mAdapter;
private EditText editText;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
public void initViews() {
editText = findViewById(R.id.et);
Button addOptionsBtn = findViewById(R.id.button);
addOptionsBtn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
addOptionToList();
}
});
mAdapter =
new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_multiple_choice,
list);
ListView listView = findViewById(R.id.options_list_view);
listView.setAdapter(mAdapter);
}
private void addOptionToList() {
String option = editText.getText().toString();
if (option.isEmpty()) {
return;
}
list.add(option);
mAdapter.clear();
mAdapter.addAll(list);
mAdapter.notifyDataSetChanged();
}
I've finally found the solution. I guess the adapter wasn't updating after getting a new item. So what I did was:
1st Activity:
public static String str;
add.setOnClickListener(new (new View.OnClickListener() {
#Override
public void onClick(View view) {
str=edittext.gettext().toString();
list.add(s3);
}
});
2nd Activity:
public static List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(My_activity.this, android.R.layout.simple_list_item_multiple_choice, list);
adapter.notifyDataSetChanged();
if (Main_activity.i == R.id.event_1 || Main_activity.i == R.id.rem_1) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
if(str.length()!=0) {
list.add(str);
}
else{
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "No
text found", Snackbar.LENGTH_LONG);
snackbar.show();
}
}

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();
}
});
}
}

How to retrieve data without using database,it has to display in listview

I am creating one dynamic list view i don't need database to store the data,whatever i am adding the data,it has to display in my list view. Right now its not displaying in my list view.
Projectlistactivity.java
public class Prayers extends ListActivity{
private static final int ACTIVITY_CREATE=0;
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_list);
fillData();
registerForContextMenu(getListView());
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//btn.setOnClickListener(listener);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
private void fillData() {
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_insert:
createProject();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, PrayersEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_prayers_list, menu);
return true;
}
}
This is my projecteditactivity.java
public class PrayersEditActivity extends Activity{
private EditText mTitleText;
private Button mConfirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_edit);
mTitleText = (EditText) findViewById(R.id.title);
mConfirmButton = (Button) findViewById(R.id.confirm);
registerButtonListenersAndSetDefaultText();
}
private void registerButtonListenersAndSetDefaultText() {
mConfirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//saveState();
String title = mTitleText.getText().toString();
mTitleText.setText("");
//adapter.notifyDataSetChanged();
setResult(RESULT_OK);
Toast.makeText(PrayersEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
finish();
}
});
}
/*private void saveState() {
//mTitleText = (EditText) findViewById(R.id.title);
String title = mTitleText.getText().toString();
mTitleText.setText("");
adapter.notifyDataSetChanged();
}*/
}
In my listview if i click the menu button it has to go to the edit page,in their i have to add project after clicking the save button,it has to display in my listview,Right now its not display in my listview.
startActivityForResult(i, 1); and override this method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
list.add(result);
adapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
in your projecteditactivity.java change the onClick to following code
#Override
public void onClick(View view) {
String title = mTitleText.getText().toString();
mTitleText.setText("");
Intent returnIntent = new Intent();
returnIntent.putExtra("result",title);
setResult(RESULT_OK,returnIntent);
finish();
}
Why cant you store the data in a file, so that, you can retrive it when the application goes to background and after a few time, when come back, you can retrive it from file if memory lost happend.
I used to keep data in a Json formatted string, Dont know how and from where you get the list data.
you may use the life_cycle function. In addtion, you may transmit the data between Activities. So that you can use the edit data to display.
keep your data with ondestroy, onpause and onresume method.. and second option is to keep it with sharedprefence or sqlite.

Categories

Resources