ListView只显示一个项目并在按下按钮时覆盖项目,需要根据测量结果不断添加项目

时间:2017-08-31 19:14:47

标签: java android arrays listview

当我在带有ListView的应用程序中按下按钮时,我替换了一个不断添加测试结果的TextView。按下每个按钮,我希望ListView添加一个项目。每次按下按钮,列表视图中的项目1都会被覆盖。我没有在listview中使用scrollview。

我原本以为是因为我放入ListView的字符串没有被声明为字符串数组。我用字符串数组复制了数组并添加了一些虚拟数据,但我的ArrayList除了字符串数组外没有。看起来我似乎陷入了困境22。

我不确定为什么我会被投票。我彻底研究了这一点,我尝试过的每一次尝试都来自例子和其他问题。如果有人至少可以告诉我为什么这是一个糟糕的问题并且对任何事情都没有贡献我会很感激。

我认为我的问题在于ArrayAdapter,我已经尝试了我在stackoverflow和其他任何地方看到过的所有建议,但我无法解决问题。有没有人有任何建议?

我的问题与关于此主题的类似问题之间的关键区别是,通过按下按钮,新数据将根据从蓝牙设备获取的测量结果写入字符串,包括日期,GPS坐标等。它不是已预定义的字符串数组。

.java文件中的所有代码都不适合这个问题。我将发布与此问题相关的代码,包括列表视图为textview时注释掉的代码。

ScannerFragment.java:

 private ListView mReadingLog;
 mReadingLog  = (ListView) view.findViewById(R.id.scanLogView);
    //mReadingLog.setMovementMethod(new ScrollingMovementMethod());//8/31
    //mReadingLog.setText(readFromFile());//8/31
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        setHasOptionsMenu(true);
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            FragmentActivity activity = getActivity();
            Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            activity.finish();
        }

        if(shouldAskPermission()) {
            if(!permissionGranted) {
                requestPermissions(perms, permsRequestCode);
            }
        }
    }

稍后......

 public void readIris(String readMessage) {
        if(!readoutStarted) {
            return;
        }

        String parsedData[];

        if(readMessage.contains(";")) {
            readoutStarted = false;
            if(readMessage.equals(";")) {
                parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
                bufferedMessage = "";
            } else {
                String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
                bufferedMessage += partialMessage[0].trim();
                parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
                bufferedMessage = "";
            }
        } else {
            bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
            return;
        }

        Log.d(TAG, Arrays.toString(parsedData));

        boolean passed = false;
        int v1 = 0;
        int v2 = 0;
        if(parsedData[3].equals("S")) {
            passed = true;
            String values[] = parsedData[7].split("\\s+");
            v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
            v2 = Integer.parseInt(values[values.length-1]);
        } else {
            Log.d(TAG, Arrays.toString(parsedData));
            String values[] = parsedData[5].split("\\s+");
            v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
            v2 = Integer.parseInt(values[values.length-1]);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateandTime = sdf.format(new Date());

        String saveData =
                "Device: " + mConnectedDeviceName +
                        System.getProperty("line.separator") +
                        "Timestamp: " + currentDateandTime +
                        System.getProperty("line.separator") +
                        "Location: " + latitude + " (lat) / " + longitude + " (lon)" +
                        System.getProperty("line.separator") +
                        "Phone id: "  + telephonyManager.getDeviceId() +
                        System.getProperty("line.separator") +
                        "Valid:" + (passed ? "YES" : "NO") +
                        System.getProperty("line.separator") +
                        "Values: " + "T" + v1 + " / " + v2 +
                        System.getProperty("line.separator") +
                        "=========================" +
                        System.getProperty("line.separator");

      String saveData2 =  "Device: " + mConnectedDeviceName +
                        System.getProperty("line.separator") +
                        "Timestamp: " + currentDateandTime +
                        System.getProperty("line.separator") +
                        "Location: " + latitude + " (lat) / " + longitude + " (lon)" +
                        System.getProperty("line.separator") +
                        "Phone id: "  + telephonyManager.getDeviceId() +
                        System.getProperty("line.separator") +
                        "Valid:" + (passed ? "YES" : "NO") +
                        System.getProperty("line.separator") +
                        "Values: " + "T" + v1 + " / " + v2 +
                        System.getProperty("line.separator") +
                        //"=========================" + //8/31/17
                        System.getProperty("line.separator");


        String csvData = mConnectedDeviceName + "," +
                currentDateandTime + "," +
                "\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
                "Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
                "\"" + telephonyManager.getDeviceId() + "\"" +
                System.getProperty("line.separator");


        ArrayList<String> listItems = new ArrayList<String>(); //8/31/17
        listItems.add(saveData2.toString()); //8/31/17
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, listItems); //8/31
        mReadingLog.setAdapter(adapter);  //8/31
        adapter.notifyDataSetChanged();
      // mReadingLog.setText(saveData + mReadingLog.getText()); 8/31/17
        mShowData.setText(saveData); //kg 8/25/17

        if(SP.getBoolean("writeToFile", true)) {
            writeToFile(saveData, csvData, true);
        }
    }

view_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:id="@+id/viewList"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:visibility="visible">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:id="@+id/button_holder"
            android:orientation="horizontal">

            <Button
                android:id="@+id/flipperReturn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Return"/>

            <Button
                android:id="@+id/button_clear_log"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/clear_log"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/listview_holder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@id/button_holder"
            android:layout_alignParentTop="true"
            android:orientation="vertical">


            <ListView
                android:id="@+id/scanLogView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:divider="@android:color/black"
                android:dividerHeight="1dp"
                android:footerDividersEnabled="false"
                android:headerDividersEnabled="false"
                android:maxLines="4096"
                android:paddingTop="15dp"
                android:scrollbars="vertical"
                android:text="@string/app_name"
                android:textAppearance="?android:attr/textAppearanceSmall"/>

        </LinearLayout>


    </RelativeLayout>


</LinearLayout>

fragment_bluetooth_scanner.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:weightSum="1">



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <Button
            android:id="@+id/button_connect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:text="@string/connect" />

        <Button
            android:id="@+id/button_disconnect"
            android:layout_width="wrap_content"
            android:layout_weight=".3"
            android:layout_height="wrap_content"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/button_poweroff"
            android:layout_width="wrap_content"
            android:layout_weight=".3"
            android:layout_height="wrap_content"
            android:text="@string/poweroff" />


    </LinearLayout>


    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="#ccc"/>




    <View
        android:layout_width="fill_parent"
        android:layout_marginBottom="5dp"
        android:layout_height="2dp"
        android:background="#ccc"/>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="fill_parent" android:layout_height="wrap_content"
                  android:id="@+id/layoutContainer" android:orientation="horizontal">

        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="0dip"
            android:layout_weight="0.15"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal">

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginLeft="8dp"
                android:id="@+id/batimg"
                android:src="@drawable/battery" />
        </RelativeLayout>

        <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="0dip"
            android:layout_weight="0.2"
            android:layout_height="wrap_content"
            android:layout_gravity="left">

            <ProgressBar
                style="@android:style/Widget.ProgressBar.Horizontal"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:progress="0"
                android:id="@+id/progressBar" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_marginTop="18dp"
                android:layout_marginLeft="20dp"
                android:textColor="#000"
                android:layout_height="wrap_content"
                android:inputType="none"
                android:ems="10"
                android:text="N/A%"
                android:textSize="@dimen/margin_medium"
                android:textAlignment="center"
                android:id="@+id/label_batterypct" />


        </RelativeLayout>

        <RelativeLayout
            android:orientation="horizontal"
            android:paddingLeft="4dp"
            android:layout_width="0dip"
            android:layout_weight="0.35"
            android:layout_height="wrap_content"
            android:layout_gravity="left">


            <View
                android:layout_marginLeft="5pt"
                android:layout_width="2dp"
                android:layout_height="50dp"
                android:background="#ccc"/>


            <Button
                android:layout_marginLeft="10pt"
                android:layout_width="fill_parent"
                android:layout_height="10pt"
                android:background="#ff2b0f"
                android:clickable="false"
                android:textSize="12dp"
                android:text="OFFLINE"
                android:id="@+id/button_connectionblink"
                />

            <Button
                android:layout_marginLeft="10pt"
                android:layout_marginTop="12pt"
                android:layout_width="fill_parent"
                android:layout_height="10pt"
                android:clickable="false"
                android:textSize="12dp"
                android:background="#cccccc"
                android:text="DATA"
                android:id="@+id/button_communication"
                />


        </RelativeLayout>

        <RelativeLayout
            android:orientation="horizontal"
            android:paddingLeft="4dp"
            android:layout_width="0dip"
            android:layout_weight="0.30"
            android:layout_height="wrap_content"
            android:layout_gravity="left">


            <View
                android:layout_width="2dp"
                android:layout_height="50dp"
                android:background="#ccc"/>


            <Button
                android:layout_marginLeft="5pt"
                android:layout_width="fill_parent"
                android:layout_height="10pt"
                android:background="#fff"
                android:clickable="false"
                android:textSize="12dp"
                android:text="NAME"
                android:id="@+id/button_devicename"
                />

            <Button
                android:layout_marginLeft="5pt"
                android:layout_marginTop="12pt"
                android:layout_width="fill_parent"
                android:layout_height="10pt"
                android:clickable="false"
                android:textSize="12dp"
                android:background="#fff"
                android:text="S/N"
                android:id="@+id/button_devicesn"
                />



        </RelativeLayout>


    </LinearLayout>


    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:layout_marginTop="6dp"
        android:background="#ccc"/>


    <LinearLayout
        android:orientation="horizontal"
        android:paddingTop="@dimen/margin_small"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">


        <Button
            android:layout_width="match_parent"
            android:layout_weight=".3"
            android:layout_height="80pt"
            android:padding="12dp"
            android:clickable="false"
            android:textSize="12dp"
            android:background="#ffc4ab"
            android:text="NO TAGGANT DETECTED"
            android:id="@+id/button_present"
            />



    </LinearLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:paddingTop="6dp"
        android:layout_height="match_parent">


        <Button
            android:id="@+id/viewLog"
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:padding="12dp"
            android:layout_height="wrap_content"
            android:text="View Log"/>

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:padding="12dp"
            android:layout_above="@id/viewLog"
            android:layout_height="match_parent"
            />


    </RelativeLayout>




</LinearLayout>

项目中还包含其他文件,我认为这些文件与问题无关,但我是Android编程的新手,我刚刚继承了这个项目,所以如果我遗漏了重要信息,请告诉我! / p>

我尝试在readIris()函数结束时更改内容。我将saveData2更改为字符串数组,并添加了一个列表和used.add以添加不同的字符串。它不会添加两个项目,但会使用相同的数据覆盖它们。如何连续添加数组条目,然后在每次按下按钮时将它们添加到列表视图中?

来自readIris的

    String saveData =
            "Device: " + mConnectedDeviceName +
                    System.getProperty("line.separator") +
                    "Timestamp: " + currentDateandTime +
                    System.getProperty("line.separator") +
                    "Location: " + latitude + " (lat) / " + longitude + " (lon)" +
                    System.getProperty("line.separator") +
                    "Phone id: "  + telephonyManager.getDeviceId() +
                    System.getProperty("line.separator") +
                    "Valid:" + (passed ? "YES" : "NO") +
                    System.getProperty("line.separator") +
                    "Values: " + "T" + v1 + " / " + v2 +
                    System.getProperty("line.separator") +
                    "=========================" +
                    System.getProperty("line.separator");

  String[] saveData2 = new String[]{  "Device: " + mConnectedDeviceName +
                    System.getProperty("line.separator") +
                    "Timestamp: " + currentDateandTime +
                    System.getProperty("line.separator") +
                    "Location: " + latitude + " (lat) / " + longitude + " (lon)" +
                    System.getProperty("line.separator") +
                    "Phone id: "  + telephonyManager.getDeviceId() +
                    System.getProperty("line.separator") +
                    "Valid:" + (passed ? "YES" : "NO") +
                    System.getProperty("line.separator") +
                    "Values: " + "T" + v1 + " / " + v2 +
                    System.getProperty("line.separator") +
                    //"=========================" + //8/31/17
                    System.getProperty("line.separator")
  };


    String csvData = mConnectedDeviceName + "," +
            currentDateandTime + "," +
            "\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
            "Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
            "\"" + telephonyManager.getDeviceId() + "\"" +
            System.getProperty("line.separator");

    final List<String> dataList = new ArrayList<String>(Arrays.asList(saveData2));
    /*ArrayList<String> listItems = new ArrayList<String>(); //8/31/17
    listItems.add(saveData2.toString()); //8/31/17*/
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, dataList); //8/31
    mReadingLog.setAdapter(adapter);  //8/31
    adapter.notifyDataSetChanged();
  // mReadingLog.setText(saveData + mReadingLog.getText()); 8/31/17
    mShowData.setText(saveData); //kg 8/25/17
    dataList.add(saveData);

1 个答案:

答案 0 :(得分:0)

我不确定这是否是一个正确的答案,但我的应用程序正在做我想要它做的事情。因为我无法适应整个文件,所以我会尽量清楚我实现更改的位置,而不会让所有内容混乱。

首先,在ScannerFragment.java中,我做了以下装饰:

int clickCounter = 0;
ArrayList<String> listItems = new ArrayList<String>(); //9/11/17
ArrayAdapter<String> adapter; //9/11/17

然后在onViewCreated()函数的同一个java文件中,我用这个连接了listview:

adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, listItems); //9/11/17
        mReadingLog.setAdapter(adapter);  //9/11/17

然后在同一文件的readIris()函数中,我将信息添加到列表中并通知适配器它已更新:

listItems.add(
                "Device: " + mConnectedDeviceName +
                        System.getProperty("line.separator") +
                        "Timestamp: " + currentDateandTime +
                        System.getProperty("line.separator") +
                        "Location: " + latitude + " (lat) / " + longitude + " (lon)" +
                        System.getProperty("line.separator") +
                        "Phone id: "  + telephonyManager.getDeviceId() +
                        System.getProperty("line.separator") +
                        "Valid:" + (passed ? "YES" : "NO") +
                        System.getProperty("line.separator") +
                        "Values: " + "T" + v1 + " / " + v2 +
                        System.getProperty("line.separator") +
                       // "=========================" +
                        System.getProperty("line.separator") );//9/11/17
        clickCounter++;//9/11/17
        adapter.notifyDataSetChanged();//9/11/17

我希望这可以在某些时候帮助别人,因为弄清楚这真的很痛苦。我认为以下答案总结了如何使用按钮在一般意义上将文本添加到列表视图中:

  1. 拥有一个带按钮和listview的xml文件:

    <LinearLayout
        android:orientation="horizontal"
        android:paddingTop="@dimen/margin_small"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
    
    
        <Button
            android:layout_width="match_parent"
            android:layout_weight=".3"
            android:layout_height="80pt"
            android:padding="12dp"
            android:clickable="false"
            android:textSize="12dp"
            android:background="#ffc4ab"
            android:text="text"
            android:id="@+id/button_present"
            />
    


        

  2. 为java类中的listview,button,arrayadapters等声明变量:

    private Button mPresence;
    private ListView mReadingLog;
    
    int clickCounter = 0;
    ArrayList<String> listItems = new ArrayList<String>(); //9/11/17
    ArrayAdapter<String> adapter; //9/11/17
    
  3. 创建一个链接运行一次的java和xml代码的函数,例如onCreate或onViewCreated,并将您的各个部分连接在一起:

    mReadingLog  = (ListView) view.findViewById(R.id.scanLogView);
    //mReadingLog.setMovementMethod(new ScrollingMovementMethod());//8/31
    //mReadingLog.setText(readFromFile());//8/31
    
    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, listItems); //9/11/17
    mReadingLog.setAdapter(adapter);  //9/11/17
    mPresence = (Button) view.findViewById(R.id.button_present);
    
  4. 按下按钮时更新arraylist和arrayadapter:

     mPresence.setOnClickListener(new View.OnClickListener)({
     @Override
        public void onClick(View view) {
        listItems.add("your text");//9/11/17
        clickCounter++;//9/11/17
        adapter.notifyDataSetChanged();//9/11/17}