首页 \ 问答 \ ListView仅在重新启动应用程序时更新条目(ListView updates the entry only when the application is restarted again)

ListView仅在重新启动应用程序时更新条目(ListView updates the entry only when the application is restarted again)

在这个应用程序中,我有一个listview和一个sqlitedatabase 。 有一个floating action button ,在单击时会显示一个dialog box其中包含两个edittext一个用于名称,另一个用于编号。 问题是,在单击dialog boxadd选项后,条目未显示在listview 。 但是当activity被销毁并且在activity上再次调用onCreate ,将显示该条目。

我尝试使用adapter.notifyDataSetChanged()但它不起作用。 代码如下所示:

public class DetailsActivity extends AppCompatActivity {

private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;

final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};

final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};


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

    manager = new DatabaseManager(getApplicationContext());
    manager.open();
    Cursor cursor=manager.fetch();

    listView = (ListView) findViewById(R.id.listViewId);
    listView.setEmptyView(findViewById(R.id.empty));

    adapter = new SimpleCursorAdapter(getApplicationContext(),
            R.layout.row_item, cursor, from, to, 0);
    adapter.notifyDataSetChanged();

    listView.setAdapter(adapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
            LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
            dialogBuilder.setView(dialogView);
            final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
            final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);

            dialogBuilder.setTitle("Add Details");
            dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!TextUtils.isEmpty(name.getText().toString()) &&
                            !TextUtils.isEmpty(phone.getText().toString())) {
                        /*adapter.notifyDataSetChanged();
                        manager.insert(name.getText().toString(), phone.getText().toString());
                        Toast.makeText(getApplicationContext(),
                                "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
                        insertData(name.getText().toString(),phone.getText().toString());
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Empty field(s)", Toast.LENGTH_SHORT).show();
                    }

                }
            });

            dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog b = dialogBuilder.create();
            b.show();
            //  listView.setAdapter(adapter);
            //adapter.notifyDataSetChanged();
        }
    });
}

public void insertData(String fname,String phnumber){
    manager.insert(fname,phnumber);
    listView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}
}

一些陈述被评论,因为我试图得到所需的结果,但无法得到它。


In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.

I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :

Code

public class DetailsActivity extends AppCompatActivity {

private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;

final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};

final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};


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

    manager = new DatabaseManager(getApplicationContext());
    manager.open();
    Cursor cursor=manager.fetch();

    listView = (ListView) findViewById(R.id.listViewId);
    listView.setEmptyView(findViewById(R.id.empty));

    adapter = new SimpleCursorAdapter(getApplicationContext(),
            R.layout.row_item, cursor, from, to, 0);
    adapter.notifyDataSetChanged();

    listView.setAdapter(adapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
            LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
            dialogBuilder.setView(dialogView);
            final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
            final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);

            dialogBuilder.setTitle("Add Details");
            dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!TextUtils.isEmpty(name.getText().toString()) &&
                            !TextUtils.isEmpty(phone.getText().toString())) {
                        /*adapter.notifyDataSetChanged();
                        manager.insert(name.getText().toString(), phone.getText().toString());
                        Toast.makeText(getApplicationContext(),
                                "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
                        insertData(name.getText().toString(),phone.getText().toString());
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Empty field(s)", Toast.LENGTH_SHORT).show();
                    }

                }
            });

            dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog b = dialogBuilder.create();
            b.show();
            //  listView.setAdapter(adapter);
            //adapter.notifyDataSetChanged();
        }
    });
}

public void insertData(String fname,String phnumber){
    manager.insert(fname,phnumber);
    listView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}
}

Some of the statements are commented because I tried to get the desired result but couldn't get it.


原文:https://stackoverflow.com/questions/46791482
更新时间:2021-08-10 09:08

最满意答案

我认为你是以错误的方式做的。我的意思是,以下工具栏没有任何PrimaryColor甚至背景:

<android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                app:layout_scrollFlags="scroll|enterAlways"/>

            <!--android:background="?attr/colorPrimaryDark"-->
                <!--app:theme="@style/AppTheme.AppBarOverlay">-->
                <!--android:layout_height="?attr/actionBarSize"-->
                <!--app:popupTheme="@style/AppTheme.PopupOverlay"-->

因此,这将适用于(v21)版本,只有没有任何背景或PrimaryColor正如您所看到的, 工具栏将像您的Activity Theme ,它具有:

 <item name="colorPrimary">@color/colorPrimary</item>

附:

Theme.AppCompat.Light.DarkActionBar

并且,如果您没有设置任何背景颜色或PrimaryColor ,因为:

 Theme.AppCompat.Light.DarkActionBar

和你的Toolbar它必须是这样的

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>

否则, 它应该崩溃(我猜,不确定)因为你有一个带有DarkActionBar的主题和一个没有背景的工具栏。

我想这就是问题所在!

编辑:

为了完成答案,既然这段代码很简单,我会在这里添加:

也可以在AppBarLayout添加它:

android:theme

I think you are doing it in the wrong way.I mean, the following Toolbar Hasn't any PrimaryColor or even Background:

<android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                app:layout_scrollFlags="scroll|enterAlways"/>

            <!--android:background="?attr/colorPrimaryDark"-->
                <!--app:theme="@style/AppTheme.AppBarOverlay">-->
                <!--android:layout_height="?attr/actionBarSize"-->
                <!--app:popupTheme="@style/AppTheme.PopupOverlay"-->

So, this will works on (v21) versions only without any background or PrimaryColor.and as you can see, Toolbar is going to be like your Activity Theme which that has:

 <item name="colorPrimary">@color/colorPrimary</item>

With:

Theme.AppCompat.Light.DarkActionBar

And, if you don't set any background color or PrimaryColor, because of:

 Theme.AppCompat.Light.DarkActionBar

and your Toolbar, it has to be like that:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>

Otherwise, it should crashed(i guess, not sure) because you have a Theme with DarkActionBar and one Toolbar with no background.

I think this is the problem!

Edit:

For completing the answer, since this code was simple anyway, i'll add it here:

Add this also in your AppBarLayout:

android:theme

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)