filling listView when button clicked in other activity - java

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

Related

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.

RecyclerView Adapter returns null, when trying to remove items

I have stumpled upon a problem with my RecyclerView. I'm at the moment trying to make it so that my context menu(Which appear on Long CLick) can remove an item in my recycler view, but without luck.
I have debugged my app, and every time i click on the button which should delete the item, my app crashes, and i get the information, that my adapter returns null.
My MainActivity:
public class MainActivity extends AppCompatActivity {
//Til LongClickListener
CalculationsAdapter adapter;
ArrayList<Calculation> calculations = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
RecyclerView rvCalculations = (RecyclerView) findViewById(R.id.rvCalculations);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(MainActivity.this, DividerItemDecoration.VERTICAL);
rvCalculations.addItemDecoration(itemDecoration);
//Til CostumItemDecoration
//RecyclerView.ItemDecoration CostumItemDecoration = new DividerItemDecoration(MainActivity.this, DividerItemDecoration.VERTICAL);
//rvCalculations.addItemDecoration(CostumItemDecoration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()){
case R.id.add_new_calculation:
/* for at starte newcalculation activiteten, gør det i gråt.
Intent intent = new Intent(MainActivity.this, newcalculation.class);
startActivity(intent);
*/
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_namecalculation, null);
final EditText mNameEditText = (EditText) mView.findViewById(R.id.editText_calculationName);
Button mNameButton = (Button) mView.findViewById(R.id.button_nameCalculation);
//Viser Alertdialogen
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
mNameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Her skal der være noget der gør at jeg ikke kan give to af samme navn
//if (mNameEditText.getText() == .getName) ){
//}
if (mNameEditText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, R.string.ErrorMessageNameCalculation,Toast.LENGTH_SHORT).show();
}else{
RecyclerView rvCalculations = (RecyclerView) findViewById(R.id.rvCalculations);
//calculations = Calculation.createCalculationsList(50);
calculations.add(0, new Calculation(" " + mNameEditText.getText()));
CalculationsAdapter adapter = new CalculationsAdapter(calculations);
rvCalculations.setAdapter(adapter);
rvCalculations.setLayoutManager(new LinearLayoutManager(MainActivity.this));
adapter.notifyItemInserted(0);
rvCalculations.scrollToPosition(0);
Toast.makeText(MainActivity.this, R.string.SuccesMessageNameCalculation,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
}
return super.onOptionsItemSelected(item);
}
//Til LongClickListener
#Override
public boolean onContextItemSelected(MenuItem item) {
//Hvad itemet i LongClicket skal gøre
switch (item.getItemId()){
case 1:
adapter.removeItem(item.getGroupId());
Toast.makeText(MainActivity.this, "Regningen blev slettet", Toast.LENGTH_SHORT).show();
return true;
case 2:
Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
LogCat:
08-03 23:33:44.443 1481-1481/hndvrkerregner.hndvrkerregner E/AndroidRuntime: FATAL EXCEPTION: main
Process: package, PID: 1481
java.lang.NullPointerException: Attempt to invoke virtual method 'void package.CalculationsAdapter.removeItem(int)' on a null object reference
at package.MainActivity.onContextItemSelected(MainActivity.java:128)
You have declared the class variable CalculationsAdapter adapter; at the top of your Activity class "MainActivity". But in the onOptionsItemSelected() method you are overriding this declaration in this line of code:
CalculationsAdapter adapter = new CalculationsAdapter(calculations);
This line should be:
adapter = new CalculationsAdapter(calculations);
Explanation:
By doing this:
CalculationsAdapter adapter = new CalculationsAdapter(calculations);
you are turning adapter into a local variable--local only to the method onOptionsItemSelected() and thus, adapter is then null inside onContextItemSelected().
In order to keep adapter as a valid class variable with this line of code instead:

sending and receiving Arraylist using intent? Android

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

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.

How I can fill a ListView in Android from a other Activity?

I want built a Android App and use Eclipse for this. It is my first App and I have read on http://developer.android.com how I can create a App and more.
To my Appliation:
I use three Activitys.
The First Activity ist the main. On the Second Activity can I input a string and have a Button. On my third Activity I have a ListView but its empty. If I click on the second Activity of the Button I want that the string will be send to the ListView on the Third Activity.
a other Question is how I can save Informations in a Android App. Can I use a database or what is the right way. I want save the listview and if I open the Activity from the Main Activity i want see the Listview with the Informations.
MyCode:
FirstActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void createPlan(View view)
{
Intent intent = new Intent(this,CreateActivity.class);
startActivity(intent);
}
}
Second Activity:
public class CreateActivity extends Activity {
public final static String ListViewMessage = "de.linde.KSDILLPlan";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
FillSpinnerViews();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
public void FillSpinnerViews()
{
Spinner spinner = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.daysArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinner Spinner2 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.zeitArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner2.setAdapter(adapter2);
}
public void createPlan(View view)
{
String PlanName;
//String StundenZahl;
//String Wochentag;
//Boolean doppelstunde;
Intent intent = new Intent(this,OpenActivity.class);
EditText planName = (EditText)findViewById(R.id.editText1);
PlanName = planName.getText().toString();
intent.putExtra(ListViewMessage, PlanName);
startActivity(intent);
}
Third Activity: The ListView
public class OpenActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_open2, menu);
return true;
}
}
You can pass the data from one activity to another using intent as follows,
In second activity in onclick of button,
Intent in=new Intent(currentclass.this,nextactivity.class);
in.putExtras("value_name",value);
startActivity(in);
finish();
In third activity,
If(getIntent().getExtras!=null)
{
String msg=getIntent().getStringExtra("value_name"); // value_name is the attribute given in second activity
}
You can store the data in the database or sharedpreference. it depends upon your needs.
If you want to store bulk data as large number of person details, you can store in database using SQLite or if you want to store small data like login details you can store in SharedPreferences.
Refer the link for Database and SharedPreferences as
SQLite
SharedPreferences
Use following code to get the string from intent's bundle.
public class OpenActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open);
String text = getIntent().getStringExtra( CreateActivity.ListViewMessage );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_open2, menu);
return true;
}
}
Refer this link for persistent storage question.

Categories

Resources