简体   繁体   中英

notifyDataSetChanged not updating the listView

I am trying to update listView using a customAdapter class add function. However I am encountering strange behaviour. The first attempt at adding an element works, but after that, the listView does not get updated. I have looks at many forums (that is how I got so far in the first place) but this is where I am unable to make progress anymore.

Here is the code: HomeScreen.java

package com.apress.gerber.mathematicalcalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;


public class HomeScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onClickLogTable(View view){
        Intent logTableLauncherInternt = new Intent(this, LogTable.class);
        startActivity(logTableLauncherInternt);
    }
}

LogTable.java

package com.apress.gerber.mathematicalcalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;


public class LogTable extends AppCompatActivity {

    public customAdapter c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_table);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    public void onClickCalculate(View view){
        EditText logBaseValue = (EditText) findViewById(R.id.logBaseValue);

        if(logBaseValue.getText().toString().length()<=0) {
            Toast.makeText(LogTable.this, "Input Something", Toast.LENGTH_LONG).show();
            return;
        }

        int logBase = Integer.parseInt(logBaseValue.getText().toString());
        logBaseValue.setText(String.format("%d",logBase));

        if(logBase != logBase)
            Toast.makeText(LogTable.this, "Invalid Input", Toast.LENGTH_LONG).show();



        String[] numbers = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
        c = new customAdapter(this, numbers, logBase);
        ListAdapter logTableAdapter = c;

        ListView logTable = (ListView) findViewById(R.id.logTable);
        logTable.setAdapter(logTableAdapter);


        logTable.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(firstVisibleItem+visibleItemCount>=(totalItemCount-3)){
                    Integer asd = (int) Math.ceil(Math.random()*100);
                    Log.d("RedMango", "" + asd);
                    c.add(Integer.toString(asd));
                }
            }
        });

    }

}

customAdapter.java

package com.apress.gerber.mathematicalcalculator;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by as on 10/10/15.
 */
class customAdapter extends ArrayAdapter<String>{

    private static List<String> ListValues = new ArrayList<String>();
    private static List<String> LogValues = new ArrayList<String>();
    private Integer BaseValue;

    public customAdapter(Context context, String[] listValues, int baseValue) {
        super(context, R.layout.infiniteloglayout, listValues);
        for(int i=0; i<listValues.length-1; i++){
            ListValues.add(listValues[i]);
            LogValues.add(Double.toString(Math.log(Double.parseDouble(listValues[i])) / Math.log(baseValue)));
        }
        BaseValue = baseValue;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater logInflater = LayoutInflater.from(getContext());
        View infiniteloglayout = logInflater.inflate(R.layout.infiniteloglayout, parent, false);

        TextView value = (TextView) infiniteloglayout.findViewById(R.id.value);
        TextView logValue = (TextView) infiniteloglayout.findViewById(R.id.logValue);

        value.setText(ListValues.get(position));
        logValue.setText(LogValues.get(position));
        return infiniteloglayout;

    }

    public void add(String value) {
        ListValues.add(value);
        LogValues.add(Double.toString(Math.log(Double.parseDouble(value)) / Math.log(BaseValue)));
        Log.d("RedMango", "ListValues " + ListValues.size());
        this.notifyDataSetChanged();
    }
}

The problem is that after the onScrollListner gets called, first random element gets added to the list on screen. However after that, there are not additions to the list on screen. I tried logging the data, and I can confirm that the functions are running, data is being added to the list in the adapter, however the data is not being updated (except for the first entry). Can any one point out where I have made a mistake. I also tried moving the notifyDataSetChanged out of class but that did not change the behaviour.

Note: This is my first post on stackoverflow, so if I have made any mistake (like breaching some unspoken rules), please let me know.

You have declared two different collections one array and another list and used one of them ie array as actual data for adapter and another is just used in getView to getItem. there are two ways to solve this problem:

  1. In your add method on customAdapter. Instead of

     public void add(String value) { ListValues.add(value); 

    you should use

      public void add(String value) { super.add(value); 

    remove ListValues variable from custom adapter and in getView use

      value.setText(getItem(position)); 

    instead. And you are using for(int i=0; i<listValues.length-1; i++){ you should change it to for(int i=0; i<listValues.length; i++){

  2. Or you should pass data as arraylist from activity instead. example: In your activity change adapter to:

     String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"}; ArrayList<String> arrayListValues = new ArrayList<>(Arrays.asList(numbers)); c = new customAdapter(this, arrayListValues, logBase); 

    Now change your adapter to:

     private static ArrayList<String> ListValues; private static List<String> LogValues = new ArrayList<String>(); private Integer BaseValue; public customAdapter(Context context, ArrayList<String> listValues, int baseValue) { super(context, R.layout.infiniteloglayout, listValues); this.ListValues = listValues; for (int i = 0; i < listValues.size(); i++) { LogValues.add(Double.toString(Math.log(Double.parseDouble(listValues[i])) / Math.log(baseValue))); } BaseValue = baseValue; } 

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