如何在更新行后使用notifyDataSetChanged()

时间:2014-05-04 07:43:10

标签: android listview

我有一个自定义适配器如下(声明全局e)

CustomAdapter adapterE;

我正在进行数据库调用,以便在onItemClick listView的{​​{1}}侦听器中更新数据库中的行。 db行正在正确更新

之后我收到listItem的更新结果并调用List<TVShow>以便notifyDataSetChanged()刷新

但它在视野中并不令人耳目一新。如果我按回去然后再回到listView活动,那么我会看到结果。正如我的理解notifyDataSetChanged()应该在运行中那样做。

那么,问题是什么?

请参阅下面的代码

ActivityTVShowEpisode

}

2 个答案:

答案 0 :(得分:1)

这是一个常见的错误。应在现有notifyDataSetChanged上调用Adapter。还应注意,数据的更改应在与Adapter关联的数据存储上进行。

<强>更新

请查看您的代码。您在致电new之前创建的notifyDataSetChanged适配器与您的ListView无关。所以它不知道如何更新ListView。同样,listOfShows也会分配新值。但现有的Adapter仍然是对旧值的引用。

而不是:

listOfShows = tvService.getEpisodeOfASeason(context, tvShowName,tvShowSeasonName); 

使用:

listOfShows.clear(); 
listOfShows.addAll(tvService.getEpisodeOfASeason(context, tvShowName,tvShowSeasonName)); 

此外,在致电notifyDataSetChanged之前删除以下行:

adapterE = new TvShowEpisodAdapter(ActivityTVShowEpisode .this, R.layout.list_row_episod, listOfShows); 

答案 1 :(得分:-1)

final Handler handler = new Handler();
                    handler.postDelayed( new Runnable() {

                        @Override
                        public void run() {

                            handler.postDelayed( this, 60 * 1000 );
                        }
                    }, 60 * 1000 );

使用处理程序,您可以自动刷新列表视图,

进一步参考使用以下代码

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.SharedPreferences;
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 MainActivity extends Activity{
    ImageView iv;
    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;
    public TypedArray navMenuIcons;
    AlertDialog alertDialog;

    public ArrayList<NavDrawerItem> navDrawerItems;
    public NavDrawerListAdapter adapter;

           public boolean connect=false,logged=false;
        public String db_select;
        ListView l1;
        String mPwd,UName1="Success",UName,ret;

        public Iterator<String> itr;
        private final String SERVICE_URL = "http://10.54.3.208:8080/";
        public static final String PREFS_NAME = "MyPrefsFile";
        private final String TAG = "Project_Accel";
        ArrayList<String> todoItems;
        Boolean isInternetPresent = false;
        ConnectionDetector cd;
        ArrayAdapter<String> aa;
        public List<String> list1=new ArrayList<String>();
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sliding_project);
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
            final String myVariable = prefs.getString("EMP_ID", "mUname");
             l1 = (ListView)findViewById(R.id.list);
             iv = (ImageView)findViewById(R.id.imageView2);

          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(Projects_Accel.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(Projects_Accel.this,MainActivity.class);
                                    z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
                                            Intent.FLAG_ACTIVITY_CLEAR_TASK |
                                            Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(z);
                                    Projects_Accel.this.finish();
                                //  return true;
                                    break;
                                }

                                return true;
                            }
                        });
                            popup.show();
                    }
                });


             todoItems = new ArrayList<String>();
                aa = new ArrayAdapter<String>(this,R.layout.project_list,R.id.title,todoItems);
                l1.setAdapter(aa);
                todoItems.clear();

                //receivedName = 
                cd = new ConnectionDetector(getApplicationContext());
                isInternetPresent = cd.isConnectingToInternet();
                if(isInternetPresent)
                {
                try
                {
                    validat_user(myVariable);
                    final Handler handler = new Handler();
                    handler.postDelayed( new Runnable() {

                        @Override
                        public void run() {
                            todoItems.clear();
                            validat_user(myVariable);
                            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) 
                    {
                        int i3=(int) parent.getItemIdAtPosition(position);
                        int i4=i3+1;
                        Toast.makeText(getApplicationContext(), ""+i3+""+i4, Toast.LENGTH_LONG).show();
                        String name=(String)parent.getItemAtPosition(i4);
                        Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
                       Intent i = new Intent(getBaseContext(),pdf.class);
                       i.putExtra("PROJECT", name);
                       startActivity(i);
                    }
                });





        }
        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);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    //setMenuBackground();
    return true;
}


/*@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //  title/icon
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.action_settings:
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}*/

//called when invalidateOptionsMenu() invoke 

@Override
public 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 Fragment
    switch (position) {

    case 1:
        //fragment = new Fragment2Profile();
        Intent i = new Intent(Projects_Accel.this,Design_Activity.class);
        startActivity(i);
        Projects_Accel.this.finish();
        break;
    case 2:
        //fragment = new Fragment3Logout();
        Intent z = new Intent(Projects_Accel.this,MainActivity.class);
        z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
                 Intent.FLAG_ACTIVITY_CLEAR_TASK |
                 Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(z);
            Projects_Accel.this.finish();
        break;

    default:
        break;
    }



}

        public void display(String msg) 
        {
            Toast.makeText(Projects_Accel.this, msg, Toast.LENGTH_LONG).show();
        }
        private void validat_user(String stg1)
        {

            WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");

              wst.addNameValuePair("EMP_ID1", stg1);
              // wst.addNameValuePair("Emp_PWD", stg2);
              // db_select=stg1;
            //display("I am");
               wst.execute(new String[] { SERVICE_URL });
               //display(SERVICE_URL);

        }

        @SuppressWarnings("deprecation")
        public void no_net()
        {
            display( "No Network Connection");
            final AlertDialog alertDialog = new AlertDialog.Builder(Projects_Accel.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();
                    Projects_Accel.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 addNameValuePair(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("alert");

                         if(UName==1)
                         {

                          String status = jso.getString("proj");
                          ret=status.substring(10,status.length()-2);
                          todoItems.add(0, ret);
                            aa.notifyDataSetChanged();

                         }
                         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("proj");
                            for(int i=0;i<array.length();i++)
                            {
                                list1.add(array.getJSONObject(i).getString("PName"));

                            }Collections.sort(list1);
                            Collections.reverse(list1);
                            itr=list1.iterator();
                            while(itr.hasNext())
                            {
                                 //str1=itr.next().e+"\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("No Records Found!")
                        .setCancelable(false)
                        .setPositiveButton("Exit",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, close
                                // current activity
                                Projects_Accel.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");
            }


           }

    }