简体   繁体   中英

Add item to listview from another activity (it only adds one item)

I have a problem in my code. I want to add items to a listview from another acivity onclickButton , but it only adds one item. And if I reapeat it, it only replaces the last added item. I can't figure out whats the problem some help please.

my code : MainActivity:

package com.example.nasreddine.mtodubled; // project package

import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity; //imports statements
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem; 
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import android.content.DialogInterface;

public class MainActivity extends AppCompatActivity {
AlertDialog.Builder alert;
public ArrayList<City> listItems;
ArrayAdapter adapter;
ListView cityListView;

@Override
protected void onCreate(Bundle savedInstanceState) { //onCreate State
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listItems=new ArrayList<>();
    adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);

        //Displaying Data on ListView
    cityListView=(ListView)findViewById(R.id.cityListView);
    cityListView.setAdapter(adapter);
    registerForContextMenu(cityListView);
    listItems.add(new City("a","b","","","","",""));
    listItems.add(new City("v","c","","","","",""));
    updateListView();
    cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        }
    });
    cityListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
            AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
            alert.setTitle("Delete Item from list");
            alert.setMessage("Are you sure you want to delete?");
            alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    listItems.remove(position);
                    adapter.notifyDataSetChanged();
                }
            });
            alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alert.show();
            return true;
        }
    });
}
public void updateListView() {
    Bundle bundle = getIntent().getExtras();
    Intent intent=getIntent();
    if (bundle != null) {
        City a=new City(intent.getStringExtra("city"),intent.getStringExtra("country"),"/","/","/","/","/");
        //listItems.add(a);
        adapter.add(a);
        adapter.notifyDataSetChanged();
    }
}
public boolean onOptionsItemSelected(MenuItem item){
    if (item.getItemId()==R.id.action_add){

        Intent intent=new Intent(MainActivity.this,AddCity.class);
        startActivity(intent);
        return (true);
    }
    return (super.onOptionsItemSelected(item));
}
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main,menu);
    return super.onCreateOptionsMenu(menu);
}
}

AddCity.java

package com.example.nasreddine.mtodubled;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AddCity extends AppCompatActivity {

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

    Button addButton=(Button)findViewById(R.id.addButton);
    final TextView cityAddText=(TextView)findViewById(R.id.cityAddText);
    final TextView countryAddText=(TextView)findViewById(R.id.countryAddText);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String city= cityAddText.getText().toString();
            String country=countryAddText.getText().toString();
            Intent intent =new Intent(AddCity.this,MainActivity.class);
            intent.putExtra("city",city);
            intent.putExtra("country",country);
            startActivity(intent);
        }
    });
}
}

You are restarting the MainActivity from AddCity Activity.

Rather than doing this, you need to start AddCity Activity, using method startActivityForResult().

And in AddCity Activity, rather than starting new MainActivity, you need to use setResult() method to send data to previous activity.

Also you need to override the onActivityResult method in MainActivity Class to owner the response from AddCity Activity.

Cheers!!!

In your MainActivity.class start the AddCity.class using startActivityForResult().

public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){

    Intent intent=new Intent(MainActivity.this,AddCity.class);
    startActivityForResult(intent, requestCode); //ex: requestCode = 1
    return (true);

}
return (super.onOptionsItemSelected(item));
}

After that in AddCity change add button click listener code with below:

addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        String city= cityAddText.getText().toString();
        String country=countryAddText.getText().toString();
        Intent intent =new Intent();
        intent.putExtra("city",city);
        intent.putExtra("country",country);
        setResult(RESULT_OK, intent);
        finish();
    }
});

After that in MainActivity's onActivityResult() get data and add it to list. Also remove updatListView() method from MainActivity.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    getActivity().invalidateOptionsMenu();
    if (resultCode == Activity.RESULT_OK) {

        if (data != null) {
            City a=new City(data.getStringExtra("city"),data.getStringExtra("country"),"/","/","/","/","/");
            listItems.add(a);
            adapter.add(a);
            adapter.notifyDataSetChanged();
            }

        }

    }

}

Here is the code:

Class Main Activity,

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
{
    AlertDialog.Builder alert;
    public List<City> listItems;
    ArrayAdapter<City> adapter;
    ListView cityListView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    { //onCreate State
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listItems = new ArrayList<>();
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);

        //Displaying Data on ListView
        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivityForResult(new Intent(MainActivity.this, AddCity.class), 1);
            }
        });

        cityListView = (ListView) findViewById(R.id.cityListView);
        cityListView.setAdapter(adapter);
        registerForContextMenu(cityListView);
        listItems.add(new City("a", "b"));
        listItems.add(new City("v", "c"));
        updateListView();
    }

    public void updateListView()
    {
        Bundle bundle = getIntent().getExtras();
        Intent intent = getIntent();
        if(bundle != null)
        {
            City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
            //listItems.add(a);
            adapter.add(a);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);

        if(requestCode == 1 && resultCode == RESULT_OK)
        {
            City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
            //listItems.add(a);
            adapter.add(a);
            adapter.notifyDataSetChanged();
        }
    }
}

Class Add City,

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_city);

        Button addButton = (Button) findViewById(R.id.addButton);
        final TextView cityAddText = (TextView) findViewById(R.id.cityAddText);
        final TextView countryAddText = (TextView) findViewById(R.id.countryAddText);

        addButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String city = cityAddText.getText().toString();
                String country = countryAddText.getText().toString();

                Intent intent = new Intent();
                intent.putExtra("city", city);
                intent.putExtra("country", country);

                setResult(RESULT_OK, intent);
            }
        });
    }
}

Hopefully, this will help you.

Cheers!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM