Home > Blockchain >  My ListView updates the first change after doing a second one
My ListView updates the first change after doing a second one

Time:09-17

I have a ListView and an 'add' button in my MainActivity. When the button is pressed, you are taken to a second activity with a form that takes some input (tokenName, tokenID and averagePrice) and creates an object 'Token' . The second activity also has a button that saves the token to a TokenList and takes you to the MainActivity again. The thing is that the token you just created isn't showing but if you create a new one, the first one appears in the ListView

MainActivity code:

public class MainActivity extends AppCompatActivity {

    public static ListView listView;
    ArrayList<String> arrayList = new ArrayList<>();
    private Button addButton;
    public static ArrayAdapter<String> arrayAdapter;
    private EditText name;
    public static TokenList tokenList = new TokenList();



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

        addButton = (Button) findViewById(R.id.addbutton);
        listView = (ListView)findViewById(R.id.listview);
        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(arrayAdapter);


        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openAddToken();
                arrayList.clear();
                for(Token token : tokenList.tokenList){
                    addToList(token.getTokenName());
                }
            }
        });

    }

    //Calls addToList method in TokenList class
    public void addToList(String tokenName){
        arrayList.add(tokenName);
    }

    //Opens the second activity with the new token form
    public void openAddToken(){
        Intent intent = new Intent(this, AddToken.class);
        startActivity(intent);
    }
}

Second activity code:

public class AddToken extends AppCompatActivity {
    private Button addButton;
    EditText tokenName, tokenID, averagePrice;
    TokenList tokenList = MainActivity.tokenList;
    Token token = new Token();

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

        tokenName=(EditText) findViewById(R.id.tokenname2);
        tokenID=(EditText) findViewById(R.id.tokenid2);
        averagePrice=(EditText) findViewById(R.id.averageprice);

        addButton = (Button) findViewById(R.id.add);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                token.setTokenName(tokenName.getText().toString());
                token.setTokenID(tokenID.getText().toString());
                token.setTokenName("err2");
                token.setAveragePrice(Double.parseDouble(averagePrice.getText().toString()));
                tokenList.addToTokenList(token);

                finish();

            }
        });
    }
}

enter image description here

How can I update the ListView in MainActivity the moment you press the 'accept' button in the second activity? I'm new to java and even more to android development so feel free to point out any bad practice.

Thank you!

CodePudding user response:

A better implementatiojn would be using a local database with for example the ROOM library.
A simpler approach to your problem, and better for mantainability would be using the startActivityForResult() and onActivityResult() in your main.
An example would be, in your AddToken.class in the .onClick() method add:

Intent resultIntent = new Intent();
resultIntent.putExtra("some_key", "String data"); 
setResult(Activity.RESULT_OK, resultIntent);
finish();

And in MainActivity.class add the following:

//Inside the onClick() method in the onCreate()
//...
Intent intent = new Intent(MainActivity.this, AddToken.class);  
startActivityForResult(intent, ANY_NOT_NEGATIVE_NUMBER);
//...
//Add the following outside onCreate() as a new method
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (ANY_NOT_NEGATIVE_NUMBER) : {
      if (resultCode == Activity.RESULT_OK) {
        // TODO Extract the data returned from the child Activity.
        String returnValue = data.getStringExtra("some_key");
      }
      break;
    } 
  }
}

In this code ANY_NOT_NEGATIVE_NUMBER is a number that you can define in your MainActivity.class. Instead of having a shared reference, then use the putExtra() method of the intent (in your AddToken.class to pass the data back to MainActivity and there add it to your list and notify the adapter of the change with notifyDataSetChanged() on your Listview adapter.


I would suggest to use a recyclerview for better performance and functions. You can check it out HERE: Create dynamic lists with RecyclerView

CodePudding user response:

You added the item to the list, but didn't notify the adapter. The adapter has no way of knowing that the data changed, unless you notify it or recreate it

  • Related