rollcage
rollcage

Reputation: 101

how to add items to list view from an other activity (android studio 2.1.2)

i tried searching github and here on how to add an item to list view from an other activery.

im currently working on my project for school and what i need to do is:

manually add items to a list view from other acticity(called thet screen "edit screen")

my problem is that when i add a movie it will always overwrite the movie i previously entered on the list view

public class MainActivity extends AppCompatActivity{

Button btnChooseScreen ;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //reading the sharedpref to popluate the listview
    SharedPreferences save = getSharedPreferences("movie info" , MODE_PRIVATE);
    final String movieName = save.getString("MOVIE NAME" , "defualt");
    final String movieSummery = save.getString("MOVIE SUMMERY" , "defualt");
    final String imageURL = save.getString("IMAGE URL" , "defualt");
    final ArrayList<String> arrayOfMovies = new ArrayList<String>();
    //arrayOfMovies.add(movieName);


    btnChooseScreen= (Button) findViewById(R.id.btnChooseScreen);
    btnChooseScreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //make an alert dialog to ask the user which screen would he like to go
            final AlertDialog.Builder adChooseScreen = new AlertDialog.Builder(MainActivity.this) ;
            adChooseScreen.setTitle("WHAT TO DO?");
            adChooseScreen.setPositiveButton("ADD MANUALLY", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intentToManualScreen = new Intent(MainActivity.this,EditScreen.class);
                    startActivity(intentToManualScreen);
                }
            });
            adChooseScreen.setNeutralButton("ADD FROM THE INTERNET", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intentInternetScreen = new Intent(MainActivity.this , OnlineSearchScreen.class);
                    startActivity(intentInternetScreen);
                }
            });
            adChooseScreen.show();
        }
    });

    //will call the listView widget
    final ListView myMovieListView = (ListView) findViewById(R.id.listView);
    //to set the arrayList into the listView I need the component Adapter
    final ArrayAdapter<String> myMoiveArrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayOfMovies );
    myMovieListView.setAdapter(myMoiveArrayAdapter);
    myMovieListView.setClickable(true);
    myMoiveArrayAdapter.add(movieName);
    myMoiveArrayAdapter.notifyDataSetChanged();
    myMovieListView.setOnItemClickListener(new AdapterView.OnItemClickListener()        {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Intent intentFromListViewToEditScreen = new Intent(MainActivity.this, EditScreen.class);
            intentFromListViewToEditScreen.putExtra("movieName" ,movieName);
            intentFromListViewToEditScreen.putExtra("movieSummary", movieSummery);
            intentFromListViewToEditScreen.putExtra("imageUrl",imageURL);
            startActivity(intentFromListViewToEditScreen);


        }
    });

}
//calling the menu and the menu inflater
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu , menu);
    return super.onCreateOptionsMenu(menu);
}
//set what happens when cliking an item in the menu
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.settings :
            //build an alert dialog for the option menu
            final AlertDialog.Builder adOptionMenue = new AlertDialog.Builder(MainActivity.this) ;
            //build an alert dialog for confirmation of deleting the list
            final AlertDialog.Builder adbmakesure = new AlertDialog.Builder(MainActivity.this) ;
            adOptionMenue.setTitle("SETTINGS") ;
            //delete button
            adOptionMenue.setPositiveButton("DELETE ALL ITEMS?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                //making sure he didnt pressed delete by mistake
                adbmakesure.setTitle("ARE YOU SURE YOU WANT TO DELETE ALL ITEMS?");
                    adbmakesure.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ///////////////////////////////////
                            /////////WRITE DELETE CODE/////////
                            ///////////////////////////////////
                            ///////////////////////////////////
                        }
                    });

                adbmakesure.setNeutralButton("NO TAKE ME BACK!", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                adbmakesure.show();
                }
            }) ;
            //EXIT BUTTON
            adOptionMenue.setNeutralButton("EXIT", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //making sure he didnt pressed exit by mistake
                    adbmakesure.setTitle("CLOSE APPLICATION?");
                    adbmakesure.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            System.exit(0);
                        }
                    });
                    adbmakesure.setNeutralButton("NO I WANT TO SEE MORE!", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    });
                    adbmakesure.show();
                }
            });
            adOptionMenue.show();
            return true ;
    }
    return super.onOptionsItemSelected(item);

and this the editscreen

public class EditScreen extends AppCompatActivity {

EditText etMovieName ;
EditText etMoviewSummery;
EditText etURL ;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_screen);


    etMovieName = (EditText) findViewById(R.id.etMovieName);
   // String inputMovieName = etMovieName.getText().toString();
    etMoviewSummery = (EditText) findViewById(R.id.etSummery);
    //String inputMovieSummery = etMoviewSummery.getText().toString();
    etURL = (EditText) findViewById(R.id.etURL);
    //String inputURL = etURL.getText().toString();
    Button btnsave = (Button) findViewById(R.id.btnsave);
    btnsave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (etMovieName.getText().toString().isEmpty() || etMoviewSummery.getText().toString().isEmpty()
                    || etURL.getText().toString().isEmpty()) {
                Toast.makeText(EditScreen.this, "Must write details!!!", Toast.LENGTH_SHORT).show();
            }
            else {
                Savedetails();
                Intent intentgoback = new Intent(EditScreen.this, MainActivity.class);
                startActivity(intentgoback);
            }
        }
    });

    //when item clicked at the mainactiveryscreen the details come from here
    final String sMovieName= getIntent().getStringExtra("movieName");
    final String sMovieSummery= getIntent().getStringExtra("movieSummary");
    final String sURL= getIntent().getStringExtra("imageUrl");
    if (sMovieName!=null && sMovieSummery !=null && sURL!=null ) {
        etMovieName.setText(sMovieName);
        etMoviewSummery.setText(sMovieSummery);
        etURL.setText(sURL);
    }
    else {

    }

}


//a method to save the info input
public void Savedetails() {
    SharedPreferences save = getSharedPreferences("movie info", MODE_PRIVATE);
    SharedPreferences.Editor edit = save.edit();
        edit.putString("MOVIE NAME", etMovieName.getText().toString());
        edit.putString("MOVIE SUMMERY", etMoviewSummery.getText().toString());
        edit.putString("IMAGE URL", etURL.getText().toString());
        edit.apply();
        Toast.makeText(EditScreen.this, "DETAILS SAVED!", Toast.LENGTH_SHORT).show();


}

}

thanks for any help and have a great day :D

Upvotes: 0

Views: 1204

Answers (1)

MrWasdennnoch
MrWasdennnoch

Reputation: 156

You always only put one item in the list - in onCreate. There will never be a second item added. 2 Reasons:

  1. You are setting a new adapter on the list that overrides an existing one

  2. You are creating a new activity when you go back. This is a complete fresh one that doesn't contain anything, no stored list item. It's basically the same state as when you first launch the activity.

I won't fix everything here for you as you have to learn it yourself (It's a school project ;) ), but I can give you some hints:

  • Set the main Activity as the parent Activity of the Edit Activity in the mainfest (many Activities...)
  • Start the edit activity via startActivityForResult() and override onActivityResult to listen for e.g. new states
  • in the EditActivity call finish() instead of launching the new main Activity
  • Before you call finish() call setResult() with the result code (RESULT_OK or RESULT_CANCELLED) and an Intent with information for the main Activity
  • In the Main Activity use that result in onActivityResult to add a new item to the adapter

Upvotes: 1

Related Questions