Don Nasroo Don Nasroo - 1 month ago 14
Java Question

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

Answer

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

        }

    }

}