简体   繁体   English

notifyDataSetChanged不更新listView

[英]notifyDataSetChanged not updating the listView

I am trying to update listView using a customAdapter class add function. 我正在尝试使用customAdapter类的add函数更新listView。 However I am encountering strange behaviour. 但是我遇到了奇怪的行为。 The first attempt at adding an element works, but after that, the listView does not get updated. 第一次尝试添加元素是可行的,但此后,listView不会得到更新。 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 这是代码: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 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 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. 问题是在调用onScrollListner之后,第一个随机元素被添加到屏幕上的列表中。 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. 我还尝试将notifyDataSetChanged移出类,但这并没有改变行为。

Note: This is my first post on stackoverflow, so if I have made any mistake (like breaching some unspoken rules), please let me know. 注意:这是我关于stackoverflow的第一篇文章,因此,如果我犯了任何错误(例如违反了一些潜规则),请告诉我。

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. 您已经声明了两个不同的集合,一个数组和另一个列表,并使用了其中的一个,即数组作为适配器的实际数据,另一个仅在getView中用于getItem。 there are two ways to solve this problem: 有两种方法可以解决此问题:

  1. In your add method on customAdapter. 在您的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 从自定义适配器中删除ListValues变量,并在getView中使用

      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++){ 并且您正在使用for(int i=0; i<listValues.length-1; i++){您应该将其更改为for(int i=0; i<listValues.length; i++){

  2. Or you should pass data as arraylist from activity instead. 或者,您应该改为通过活动将数据作为arraylist传递。 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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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