新数据插入listview时Android自动刷新

新数据插入listview时Android自动刷新,第1张

概述我一直在开发android应用程序.我有后端(Web应用程序)和前端(Android应用程序).在我的应用程序中,它的类别包含一堆项目列表.当我选择一个类别时,它将调用一个用于调用DB中所有数据的任务.任务完成后调用所有数据,它将直接指向活动.活动将显示ListView中的所有数据.现在,例如,我

我一直在开发android应用程序.
我有后端(Web应用程序)和前端(Android应用程序).

在我的应用程序中,它的类别包含一堆项目列表.
当我选择一个类别时,它将调用一个用于调用DB中所有数据的任务.
任务完成后调用所有数据,它将直接指向活动.
活动将显示ListVIEw中的所有数据.

现在,例如,我从后端(Web)插入新数据.
我只想说我插入一个新的行包含一个拳击到运动类别.
因此,在DB中,它将在桌上运动中进行拳击.

在我的AndroID应用程序中,我目前处于运动类别.
因此,当拳击插入新数据库时,它应该有自动刷新并显示列表中的拳击.

但是,当我点击类别列表中的某个类别时,如果该任务仅运行一次,我该怎么办呢?
我想比较数据库中的数据总数和AndroID应用程序中显示的数据.
当数据不相同时,它将再次调用该任务.

这是我希望我的应用程序刷新的代码

ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);    if(mWifi.isConnected())     {        refresh = new Runnable() {            public voID run() {                // Do something                handler.postDelayed(refresh, 1000);            }        };        handler.post(refresh);        /*grIDArray = new ArrayList<FlipItem>();        adapter = new PackageListItemAdapter(this, this, grIDArray);                adapter.notifyDataSetChanged();*/    }    else    {        refresh = new Runnable() {            public voID run() {                // Do something                handler.postDelayed(refresh, 60000);            }        };        handler.post(refresh);        /*grIDArray = new ArrayList<FlipItem>();        adapter = new PackageListItemAdapter(this, this, grIDArray);                adapter.notifyDataSetChanged();*/    }

我在那里评论的代码,使我的列表只显示9我在DB上有15个项目.
这就是为什么我评论这条线

解决方法:

在适配器上调用notifyDataSetChanged().

有关如何/何时调用notifyDataSetChanged()的一些其他细节可以在此Google I/O video中查看.

使用Handler及其postDelayed方法使列表的适配器无效,如下所示:

final Handler handler = new Handler()handler.postDelayed( new Runnable() {    @OverrIDe    public voID run() {        adapter.notifyDataSetChanged();        handler.postDelayed( this, 60 * 1000 );    }}, 60 * 1000 );

您只能更新主(UI)线程中的UI.

通过在主线程中创建处理程序,您可以确保发布到处理程序的所有内容也在主线程中运行.

try                {                    valIDat_user(receivedname);                    final Handler handler = new Handler();                    handler.postDelayed( new Runnable() {                        @OverrIDe                        public voID run() {                            todoItems.clear();                            //alertDialog.cancel();                            valIDat_user(receivedname);                            handler.postDelayed( this, 60 * 1000 );                        }                    }, 60 * 1000 );                }                catch(Exception e)                {                    display("Network error.\nPlease check with your network settings.");                }

首先验证用户是第一次加载数据,使用处理程序后我可以每隔一分钟更新一次值

我的完整代码如下

package com.example.employeeinduction;import java.io.BufferedReader;import java.io.IOException;import java.io.inputStream;import java.io.inputStreamReader;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;import org.apache.http.httpResponse;import org.apache.http.nameValuePair;import org.apache.http.clIEnt.httpClIEnt;import org.apache.http.clIEnt.entity.UrlEncodedFormEntity;import org.apache.http.clIEnt.methods.httpPost;import org.apache.http.impl.clIEnt.DefaulthttpClIEnt;import org.apache.http.message.BasicnameValuePair;import org.apache.http.params.BasichttpParams;import org.apache.http.params.httpconnectionParams;import org.apache.http.params.httpParams;import org.Json.JsONArray;import org.Json.JsONObject;import androID.app.Activity;import androID.app.AlertDialog;import androID.app.ProgressDialog;import androID.content.Context;import androID.content.DialogInterface;import androID.content.Intent;import androID.content.res.TypedArray;import androID.os.AsyncTask;import androID.os.Bundle;import androID.os.Handler;import androID.support.v4.Widget.DrawerLayout;import androID.util.Log;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.vIEw.VIEw;import androID.Widget.AdapterVIEw;import androID.Widget.AdapterVIEw.OnItemClickListener;import androID.Widget.ArrayAdapter;import androID.Widget.ImageVIEw;import androID.Widget.ListVIEw;import androID.Widget.PopupMenu;import androID.Widget.PopupMenu.OnMenuItemClickListener;import androID.Widget.Toast;public class pdf extends Activity{    ImageVIEw iv;    public boolean connect=false,logged=false;    public String db_select;    ListVIEw l1;    AlertDialog alertDialog;    String mPwd,Uname1="Success",Uname,ret,receivedname;    public Iterator<String> itr;    //private String SERVICE_URL = "http://61.12.7.197:8080/pdf";    //private String SERVICE_URL1 = "http://61.12.7.197:8080/url";    //private final String SERVICE_URL = "http://10.54.3.208:8080/Employee/person/pdf";    //private final String SERVICE_URL1 = "http://10.54.3.208:8080/Employee/person/url";    private final String SERVICE_URL = Urlmanager.Address+"pdf";    private final String SERVICE_URL1 = Urlmanager.Address+"url";    private final String TAG = "pdf";    ArrayList<String> todoItems;    Boolean isInternetPresent = false;    ConnectionDetector cd;    ArrayAdapter<String> aa;    public List<String> List1=new ArrayList<String>();    public DrawerLayout mDrawerLayout;    public ListVIEw mDrawerList;    //public ActionbarDrawerToggle mDrawerToggle;    // NavigationDrawer Title "Nasdaq" in this example    public CharSequence mDrawerTitle;    //  App Title "Navigation Drawer" in this example     public CharSequence mTitle;    // slIDer menu items details     public String[] navMenuTitles=null;    public TypedArray navMenuIcons;    public ArrayList<NavDrawerItem> navDrawerItems;    public NavDrawerlistadapter adapter;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState)     {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.slIDing_project);         iv = (ImageVIEw)findVIEwByID(R.ID.imageVIEw2);        l1 = (ListVIEw)findVIEwByID(R.ID.List);        mTitle = mDrawerTitle = getTitle();        // getting items of slIDer from array        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);        // getting Navigation drawer icons from res         navMenuIcons = getResources()                .obtainTypedArray(R.array.nav_drawer_icons);        mDrawerLayout = (DrawerLayout) findVIEwByID(R.ID.drawer_layout);        mDrawerList = (ListVIEw) findVIEwByID(R.ID.List_slIDermenu);        navDrawerItems = new ArrayList<NavDrawerItem>();        // List item in slIDer at 1 Home Nasdaq details        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceID(0, -1)));        // List item in slIDer at 2 Facebook details        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceID(1, -1)));        // List item in slIDer at 3 Google details        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceID(2, -1)));        // List item in slIDer at 4 Apple details        // Recycle array        navMenuIcons.recycle();        mDrawerList.setonItemClickListener(new SlIDeMenuClickListener());        // setting List adapter for Navigation Drawer        adapter = new NavDrawerlistadapter(getApplicationContext(),                navDrawerItems);        mDrawerList.setAdapter(adapter);        if (savedInstanceState == null) {              displayVIEw(0);        }          iv.setonClickListener(new VIEw.OnClickListener() {                @OverrIDe                public voID onClick(VIEw v) {                    PopupMenu popup = new PopupMenu(getBaseContext(), v);                    /** Adding menu items to the popumenu */                    popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());                    popup.setonMenuItemClickListener(new OnMenuItemClickListener() {                        @OverrIDe                        public boolean onMenuItemClick(MenuItem item) {                            switch (item.getItemID()){                            case R.ID.Home:                                Intent a = new Intent(pdf.this,Design_Activity.class);                                startActivity(a);                                //Projects_Accel.this.finish();                            //  return true;                                break;                            case R.ID.logout:                                /*Intent z = new Intent(this,MainActivity.class);                                z.addFlags(Intent.FLAG_ACTIVITY_CLEAR_top);                                startActivity(z);                                this.finish();*/                                Intent z = new Intent(pdf.this,MainActivity.class);                                z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_top |                                         Intent.FLAG_ACTIVITY_CLEAR_TASK |                                        Intent.FLAG_ACTIVITY_NEW_TASK);                                startActivity(z);                                pdf.this.finish();                            //  return true;                                break;                            }                            return true;                        }                    });                        popup.show();                }            });             todoItems = new ArrayList<String>();                aa = new ArrayAdapter<String>(this,R.layout.List_row,R.ID.Title,todoItems);                l1.setAdapter(aa);                todoItems.clear();                Intent intent = getIntent();                receivedname = (String) intent.getSerializableExtra("PROJECT");                cd = new ConnectionDetector(getApplicationContext());                isInternetPresent = cd.isConnectingToInternet();                if(isInternetPresent)                {                try                {                    valIDat_user(receivedname);                    final Handler handler = new Handler();                    handler.postDelayed( new Runnable() {                        @OverrIDe                        public voID run() {                            todoItems.clear();                            //alertDialog.cancel();                            valIDat_user(receivedname);                            handler.postDelayed( this, 60 * 1000 );                        }                    }, 60 * 1000 );                }                catch(Exception e)                {                    display("Network error.\nPlease check with your network settings.");                }                }                else                {                    display("No Internet Connection..");                }                l1.setonItemClickListener(new OnItemClickListener() {                    public voID onItemClick(AdapterVIEw<?> parent, VIEw vIEw,                        int position, long ID) {                     String name=(String)parent.getItemAtposition(position);                     /*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();                      Intent i = new Intent(getBaseContext(),WebvIEw.class);                      i.putExtra("USERname", name);                      startActivity(i);*/                     cd = new ConnectionDetector(getApplicationContext());                        isInternetPresent = cd.isConnectingToInternet();                     if(isInternetPresent)                        {                     try                        {                            valIDat_user1(receivedname,name);                        }                        catch(Exception e)                        {                            display("Network error.\nPlease check with your network settings.");                        }                        }                     else                        {                            display("No Internet Connection..");                        }                    }                });             }          private class SlIDeMenuClickListener implements    ListVIEw.OnItemClickListener {@OverrIDepublic voID onItemClick(AdapterVIEw<?> parent, VIEw vIEw, int position,        long ID) {    // display vIEw for selected item    displayVIEw(position);}}@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);//setMenuBackground();return true;}/*@OverrIDepublic boolean onoptionsItemSelected(MenuItem item) {//  Title/iconif (mDrawerToggle.onoptionsItemSelected(item)) {    return true;}// Handle action bar actions clickswitch (item.getItemID()) {case R.ID.action_settings:    return true;default:    return super.onoptionsItemSelected(item);}}*///called when invalIDateOptionsMenu() invoke @OverrIDepublic boolean onPrepareOptionsMenu(Menu menu) {// if Navigation drawer is opened, hIDe the action items//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);//menu.findItem(R.ID.action_settings).setVisible(!drawerOpen);return super.onPrepareOptionsMenu(menu);}private voID displayVIEw(int position) {// update the main content with called Fragmentswitch (position) {case 1:    //fragment = new Fragment2Profile();    Intent i = new Intent(pdf.this,Design_Activity.class);    startActivity(i);    pdf.this.finish();    break;case 2:    //fragment = new Fragment3logout();    Intent z = new Intent(pdf.this,MainActivity.class);    z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_top |              Intent.FLAG_ACTIVITY_CLEAR_TASK |             Intent.FLAG_ACTIVITY_NEW_TASK);        startActivity(z);        pdf.this.finish();    break;default:    break;}}        public voID display(String msg)         {            Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();        }        private voID valIDat_user(String st)        {            WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");           wst.addnameValuePair1("table_name", st);           // wst.addnameValuePair("Emp_PWD", stg2);           // db_select=stg1;            //display("I am");            wst.execute(new String[] { SERVICE_URL });            //display(SERVICE_URL);        }        private voID valIDat_user1(String stg1,String stg2)        {            db_select=stg1;            WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");            wst.addnameValuePair1("pdf_name", stg1);            wst.addnameValuePair1("table_name1", stg2);            wst.execute(new String[] { SERVICE_URL1 });        }        @SuppressWarnings("deprecation")        public voID no_net()        {            display( "No Network Connection");            final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();            alertDialog.setTitle("No Internet Connection");            alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");            //alertDialog.setIcon(R.drawable.error_info);            alertDialog.setCancelable(false);            alertDialog.setbutton("Close", new DialogInterface.OnClickListener()             {                public voID onClick(DialogInterface dialog, int which)                {                       alertDialog.cancel();                    pdf.this.finish();                    System.exit(0);                }            });            alertDialog.setbutton2("Use Local DataBase", new DialogInterface.OnClickListener()             {                public voID onClick(DialogInterface dialog, int which)                {                    display( "Accessing local DataBase.....");                    alertDialog.cancel();                }            });            alertDialog.show();        }        private class WebServiceTask extends AsyncTask<String, Integer, String> {            public static final int POST_TASK = 1;            private static final String TAG = "WebServiceTask";            // connection timeout, in milliseconds (waiting to connect)            private static final int CONN_TIMEOUT = 12000;            // socket timeout, in milliseconds (waiting for data)            private static final int SOCKET_TIMEOUT = 12000;            private int taskType = POST_TASK;            private Context mContext = null;            private String processMessage = "Processing...";            private ArrayList<nameValuePair> params = new ArrayList<nameValuePair>();            private ProgressDialog pDlg = null;            public WebServiceTask(int taskType, Context mContext, String processMessage) {                this.taskType = taskType;                this.mContext = mContext;                this.processMessage = processMessage;            }            public voID addnameValuePair1(String name, String value) {                params.add(new BasicnameValuePair(name, value));            }            @SuppressWarnings("deprecation")            private voID showProgressDialog() {                pDlg = new ProgressDialog(mContext);                pDlg.setMessage(processMessage);                pDlg.setProgressDrawable(mContext.getWallpaper());                pDlg.setProgressstyle(ProgressDialog.STYLE_SPINNER);                pDlg.setCancelable(false);                pDlg.show();            }            @OverrIDe            protected voID onPreExecute() {                showProgressDialog();            }            protected String doInBackground(String... urls) {                String url = urls[0];                String result = "";                httpResponse response = doResponse(url);                if (response == null) {                    return result;                } else {                    try {                        result = inputStreamToString(response.getEntity().getContent());                    } catch (IllegalStateException e) {                        Log.e(TAG, e.getLocalizedMessage(), e);                    } catch (IOException e) {                        Log.e(TAG, e.getLocalizedMessage(), e);                    }                }                return result;            }            @OverrIDe            protected voID onPostExecute(String response) {                handleResponse(response);                pDlg.dismiss();            }            // Establish connection and socket (data retrIEval) timeouts            private httpParams gethttpParams() {                httpParams htpp = new BasichttpParams();                httpconnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);                httpconnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);                return htpp;            }            private httpResponse doResponse(String url) {                // Use our connection and data timeouts as parameters for our                // DefaulthttpClIEnt                httpClIEnt httpclIEnt = new DefaulthttpClIEnt(gethttpParams());                httpResponse response = null;                try {                    switch (taskType) {                    case POST_TASK:                        httpPost httppost = new httpPost(url);                        // Add parameters                        httppost.setEntity(new UrlEncodedFormEntity(params));                        response = httpclIEnt.execute(httppost);                        break;                    }                } catch (Exception e) {                    display("Remote DataBase can not be connected.\nPlease check network connection.");                    Log.e(TAG, e.getLocalizedMessage(), e);                    return null;                }                return response;            }            private String inputStreamToString(inputStream is) {                String line = "";                StringBuilder total = new StringBuilder();                // Wrap a BufferedReader around the inputStream                BufferedReader rd = new BufferedReader(new inputStreamReader(is));                try {                    // Read response until the end                    while ((line = rd.readline()) != null) {                        total.append(line);                    }                } catch (IOException e) {                    Log.e(TAG, e.getLocalizedMessage(), e);                }                // Return full string                return total.toString();            }        }        public voID handleResponse(String response)         {    //display("JsON responce is : "+response);            if(!response.equals(""))            {           try {                JsONObject Jso = new JsONObject(response);                      int Uname = Jso.getInt("status1");                      if(Uname==1)                      {                            String status = Jso.getString("reps1");                            ret=status.substring(12,status.length()-2);                            todoItems.add(0, ret);                            aa.notifyDataSetChanged();                      }                      else if(Uname==-1)                      {                          String status = Jso.getString("status");                          //ret=status.substring(12,status.length()-2);                          //display(status);                            Intent intObj=new Intent(pdf.this,WebvIEw.class);                             intObj.putExtra("USERname",status);                            startActivity(intObj);                      }                      else if(Uname>1)                      {//                       int count=Integer.parseInt(Uname);//                       display("Number of Projects have been handling in AFL right Now: "+count);                        List1=new ArrayList<String>();                        JsONArray array=Jso.getJsONArray("reps1");                        for(int i=0;i<array.length();i++)                        {                            List1.add(array.getJsONObject(i).getString("pdfname"));                        }Collections.sort(List1);                        Collections.reverse(List1);                        itr=List1.iterator();                        while(itr.hasNext())                        {                             //str1=itr.next()+"\n";                            todoItems.add(0, itr.next().toString());                            aa.notifyDataSetChanged();                        }                        //tv1.setText(str1);                      }                        else                      {                          final Context context = this;                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(                                context);                            // set Title                            alertDialogBuilder.setTitle("");                            // set dialog message                            alertDialogBuilder                                .setMessage("Records unavailable for this project!")                                .setCancelable(false)                                .setPositivebutton("Exit",new DialogInterface.OnClickListener() {                                    public voID onClick(DialogInterface dialog,int ID) {                                        // if this button is clicked, close                                        // current activity                                        pdf.this.finish();                                    }                                  });                                // create alert dialog                                alertDialog = alertDialogBuilder.create();                                // show it                                alertDialog.show();                      }            } catch (Exception e) {                Log.e(TAG, e.getLocalizedMessage(), e);                return;            }            }            else            {                display("unable to reach the server");            }        }        /**         * SlIDer menu item click Listener         * */        /*private class SlIDeMenuClickListener implements                ListVIEw.OnItemClickListener {            @OverrIDe            public voID onItemClick(AdapterVIEw<?> parent, VIEw vIEw, int position,                    long ID) {                // display vIEw for selected item                displayVIEw(position);            }        }        private voID displayVIEw(int position) {            // update the main content with called Fragment        //  Fragment fragment = null;            switch (position) {            case 0:            //  fragment = new Fragment1User();                break;            case 1:            //  fragment = new Fragment2Profile();                break;            case 2:            //  fragment = new Fragment3logout();                break;            default:                break;            }        }*/}
总结

以上是内存溢出为你收集整理的新数据插入listview时Android自动刷新全部内容,希望文章能够帮你解决新数据插入listview时Android自动刷新所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1096403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存