0

伙计们,我正在使用一个简单的列表视图。我有两个活动,一个主要活动,第二个活动添加朋友在第二个活动中,我在文本框中获取朋友的用户 ID,并将该行添加到数据库并更新数组列表。当我回到主要活动时,我在 onResume() 函数中调用 notifyDataSetChanged() 并且我还记录了 arraylist 值。Arraylist 非常好,并且该行也插入到数据库中,但 listview 没有得到更新。我不知道这个问题请帮忙。这是d代码。

public class VayuActivity extends Activity {
    /** Called when the activity is first created. */
    static boolean first_time=true;
    ListView friend_list;
    public static List<String> al;
    public  ArrayAdapter<String> aa;
    String dummyfriends[]={"prashant","monika","pramod","dhara"};
    public static MessengerDataSource mds;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
/*        if(first_time==true)
        {
            first_time=false;
            setContentView(R.layout.registration);
        }
        else */
            setContentView(R.layout.main);

        al=new ArrayList<String>();
        for(String i:dummyfriends)
            al.add(i);

        aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, al);

        friend_list=(ListView) findViewById(R.id.friend_list);

        friend_list.setAdapter(aa);

        mds= new MessengerDataSource(getApplicationContext());

        mds.open();

        System.out.println("I m in oncreate");

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        al=mds.getFriends();
        aa.notifyDataSetChanged();

        System.out.println("I m in on resume function");
        System.out.println("Value of arraylist in on resume fun"+al);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        System.out.println("I m in onpause function");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {


        MenuInflater mi=getMenuInflater();
        mi.inflate(R.menu.mainmenu, menu);

        return true;





    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId())
        {
        case R.id.add_friend:
            //Toast.makeText(this, "Add Friend", 2000).show();
            Intent i=new Intent(VayuActivity.this,AddFriendActivity.class);
            startActivity(i);
            break;

        case R.id.remove_friend:
            Toast.makeText(this, "Remove Friend", 2000).show();
            break;

        }


        return true;
    }
}



package com.pdd.vayu;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AddFriendActivity extends Activity implements OnClickListener{

    EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         super.onCreate(savedInstanceState);
        setContentView(R.layout.addfriend);

        et=(EditText) findViewById(R.id.E_friendadd);

        Button b=(Button) findViewById(R.id.add_friend_button);
        b.setOnClickListener(this);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        String userid=et.getText().toString();
        //VayuActivity.al.add(f);
        Friend f=new Friend();
        f.setUserid(userid);
        f.setFname("pratik");

        VayuActivity.mds.addFriend(f);
        VayuActivity.al=(ArrayList<String>) VayuActivity.mds.getFriends();
        System.out.println(VayuActivity.al);
        //VayuActivity.aa.notifyDataSetChanged();
    }
}

数据库类

package com.pdd.vayu;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MessengerDataSource {

    private SQLiteDatabase database;
    private MyDatabaseHelper mydbh;

    public static String USER_ID="userid";
    public static String F_NAME="fname";
    public static String CHAT_COUNT="chat_count";

    public static String M_TEXT="mtext";
    public static String SENDER="sender";
    public static String RECEIVER="receiver";
    public static String M_TYPE="type";



    public MessengerDataSource(Context c)
    {
        mydbh=new MyDatabaseHelper(c);
    }

    public void open()
    {
        try
        {
            database=mydbh.getWritableDatabase();   
        }
        catch(Exception e)
        {
            System.out.println(e.getLocalizedMessage());
        }
    }

    public void close() {
        mydbh.close();
    }

    public void addFriend(Friend f)

    {
        ContentValues cv = new ContentValues();
        cv.put(USER_ID,f.getUserid());
        cv.put(F_NAME, f.getFname());
        cv.put(CHAT_COUNT, f.getChat_count());

        try
        {
            database.insert(MyDatabaseHelper.TABLE_FRIEND, null, cv);
        }
        catch(Exception e)
        {
            System.out.println("Error while inserting  "+e.getLocalizedMessage());
        }

    }

    public void addMessage(Message m)

    {
        ContentValues cv = new ContentValues();
        cv.put(M_TEXT, m.getText());
        cv.put(SENDER,m.getSender());
        cv.put(RECEIVER,m.getReceiver());
        cv.put(M_TYPE, m.getType());


        database.insert(MyDatabaseHelper.TABLE_MESSAGE, null, cv);
    }

    public void deleteFriend(String fname)
    {
        database.delete(MyDatabaseHelper.TABLE_FRIEND,F_NAME+"="+fname , null);

    }

    public void deleteMessage(String text)

    {
        database.delete(MyDatabaseHelper.TABLE_FRIEND,M_TEXT+"="+text , null);
    }

    public List<String> getFriends()

    {
        List<String> friends= new ArrayList<String>();
        Cursor c=null;
        try
        {
        c=database.query(MyDatabaseHelper.TABLE_FRIEND, new String[]{F_NAME}, null, null, null, null,CHAT_COUNT);
        }
        catch(Exception e){System.out.println("Error while retrieving frnds list"+e.getLocalizedMessage());
        }

        if(c.moveToFirst())
        {
            do
            {
                String friend=c.getString(c.getColumnIndex(F_NAME));
                friends.add(friend);
            }
            while(c.moveToNext());
        }




        return friends;
    }

    public List<String> getMessages(String from)

    {
        List<String> messages= new ArrayList<String>();

        String where=SENDER+"="+from;

        Cursor c=database.query(MyDatabaseHelper.TABLE_MESSAGE, new String[]{M_TEXT},where , null, null, null,null);

        if(c.moveToFirst())
        {
            do
            {
                String message=c.getString(c.getColumnIndex(M_TEXT));
                messages.add(message);
            }
            while(c.moveToNext());
        }


        return messages;
    }




}

数据库助手

package com.pdd.vayu;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {


    public static String TABLE_FRIEND="friend";

    public static String TABLE_MESSAGE="message";

    public static String CREATE_FRIEND="create table if not exists "+ 
    TABLE_FRIEND+" (userid varchar primary key,fname varchar,chat_count int);";

    public static String CREATE_MESSAGE="create table if not exists "+
    TABLE_MESSAGE+"(mid integer primary key autoincrement," +
    "mtext varchar," +"sender varchar , receiver varchar , type varchar)";

    //public static String TABLE_FRIENDS="friends";

    public static String DB_NAME="MessengerDB.db";

    Context context;


    public MyDatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL(CREATE_FRIEND);
        db.execSQL(CREATE_MESSAGE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

请帮忙

4

2 回答 2

0

要使 notifyDataSetChanged() 起作用,您必须使用它的添加/删除方法而不是实际列表将对象添加到 ArrayAdapter 本身。

您的 onResume 应如下所示:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    //al=mds.getFriends();
    aa.clear();
    aa.addAll(mds.getFriends());
    aa.notifyDataSetChanged();

    System.out.println("I m in on resume function");
    System.out.println("Value of arraylist in on resume fun"+al);
}

ArrayAdapter 在启动时会创建列表的副本,因此在调用 notifyDataSetChanged 时,它只会查看自己的副本,而不是源列表。

于 2012-04-11T14:10:59.373 回答
0

你必须尝试这样的 notifyDataSetChanged() 方法

有时,当您未在 adpter 中加载新数据时,它不会加载数据,因此在调用此方法之前,您必须在 onresume() 方法而不是 onCreate() 中加载 arrayadpter 中的数据。

public void refresh()
    {

        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                ((EfficentAdapter)list.getAdapter()).notifyDataSetChanged(); 
                }           
        }, 100);

    }
于 2012-04-11T12:55:09.747 回答