jjzjj

android - 如何在 Android 中管理 Activity 的 onPause、onResume 自定义适配器

coder 2023-12-22 原文

我有一个适配器,用于在 ListView 中显示消息,在聊天应用程序中查看类似的消息。创建 Activity 后,我能够完美地显示内容,但是当我返回并再次创建 Activity 时,适配器无法正常工作。

调试时发现如下:

  • 函数 receives() 在收到消息时调用并更新 注册,正如我上面提到的,显示是没有问题的 创建 Activity 后 ListView 中的数据,但一旦我返回 并重新启动我无法显示收到的消息的 Activity 。

关于自定义适配器的 onResume() onPause 或 onStart() 方法是否缺少某些内容,例如再次注册或取消自定义适配器?感谢您的帮助。

以下是我的 Activity 类的代码,它使用自定义适配器来显示已发送和已接收的消息:

public class hotListener extends ListActivity {


    private XMPPConnection connection;
    private IBinder binder;
    private Handler mHandler = new Handler();
    private ArrayList<String> messages = new ArrayList<String>();
    ArrayList<ChatMessage> messagex= new ArrayList<ChatMessage>();;
    ChattingAdapter adaptex;

    Intent mIntent ;
    private ListView listview;
    EditText sender_message ;
    String msg;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.listener);
        //messagex.add(new ChatMessage("Hello", false));
        adaptex  = new ChattingAdapter(getApplicationContext(),messagex);
        setListAdapter(adaptex);

        Button send_button = (Button) findViewById(R.id.chat_send_message);
        sender_message = (EditText) findViewById(R.id.chat_input);
        send_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msg = sender_message.getText().toString();
                sender_message.setText("");
                if(!(msg.length()==0)){
                    messagex.add(new ChatMessage(msg, true));
                    //addNewMessage(new ChatMessage(msg, true));
                    adaptex.notifyDataSetChanged();
                    getListView().setSelection(messagex.size()-1);
                }

            }
        });
        if(!isMyServiceRunning()){
            System.out.println("seems like service not running");
            startService(new Intent(this,xService.class));
            System.out.print(" now started ");
        }       
    }

    @Override
    protected void onStart(){
        super.onStart();
        Boolean kuch = bindService(new Intent(this,xService.class), mConnection,Context.BIND_AUTO_CREATE);
        //System.out.println(kuch);
        System.out.println("bind done");        
    }

    private void receives(XMPPConnection connection2) {
            //ChatManager chatmanager = connection.getChatManager();
            connection2.getChatManager().addChatListener(new ChatManagerListener() {

                @Override
                public void chatCreated(Chat arg0, boolean arg1) {
                    arg0.addMessageListener(new MessageListener() {

                        @Override
                        public void processMessage(Chat chat, Message message) {

                            final String from = message.getFrom();
                            final String body = message.getBody();
                            mHandler.post(new Runnable() {
                                ChatMessage kudi = new ChatMessage(body, false);

                                @Override
                                public void run() {

                                    messagex.add(kudi);
                                    adaptex.notifyDataSetChanged();
                                    getListView().setSelection(messagex.size()-1);
                                    Toast.makeText(hotListener.this,body,Toast.LENGTH_SHORT).show();                                }
                            });
                        }
                    });
                }
            });
    }

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
            if(xService.class.getName().equals(service.service.getClassName())){
                return true;
            }
        }
        //System.out.print("false");
        return false;
    }

    @Override
      protected void onResume() {
        bindService(new Intent(this, xService.class), mConnection, Context.BIND_AUTO_CREATE);
        super.onResume();
      }
     @Override
      protected void onPause() {
        unbindService(mConnection);
        super.onPause();
      }

     private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
                connection = null;
                service = null;
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                //System.out.println("binding in hot listener");
                service = ((xService.MyBinder)binder).getService();
                connection = service.getConnection();
                receives(connection);
                Log.wtf("Service","connected");
            }
        };

        void addNewMessage(ChatMessage m)
        {
            System.out.println("1");
            messagex.add(m);
            System.out.println("2");
            adaptex.notifyDataSetChanged();
            System.out.println("3");
            getListView().setSelection(messagex.size()-1);
        }
}

这是我的自定义适配器(自定义适配器没有问题,但添加以明确说明):

public class ChattingAdapter extends BaseAdapter{
    private Context mContext;
    private ArrayList<ChatMessage> mMessages;


    public ChattingAdapter(Context context, ArrayList<ChatMessage> messages) {
        super();
        this.mContext = context;
        this.mMessages = messages;
    }
    @Override
    public int getCount() {
        return mMessages.size();
    }
    @Override
    public Object getItem(int position) {       
        return mMessages.get(position);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ChatMessage message = (ChatMessage) this.getItem(position);

        ViewHolder holder; 
        if(convertView == null)
        {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);
            holder.message = (TextView) convertView.findViewById(R.id.text1);
            convertView.setTag(holder);
        }
        else
            holder = (ViewHolder) convertView.getTag();

        holder.message.setText(message.getMessage());
        LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();      

        //Check whether message is mine to show green background and align to right

        if(message.isMine())

        {           holder.message.setBackgroundResource(R.drawable.msgbox_new_selected_go_up);         

                lp.gravity = Gravity.RIGHT;     
        }
        //If not mine then it is from sender to show orange background and align to left

        else        
        {
            holder.message.setBackgroundResource(R.drawable.msgbox_other_go_up);

            lp.gravity = Gravity.LEFT;

        }
            holder.message.setLayoutParams(lp);
            //holder.message.setTextColor(R.color.textColor);   

        return convertView;
    }
    private static class ViewHolder
    {
        TextView message;
    }

    @Override
    public long getItemId(int position) {
        //Unimplemented, because we aren't using Sqlite.
        return position;
    }

}

p.s:我没有在 sqlite 中存储任何消息,因为我现在不想恢复消息,但我希望至少在 Activity 恢复时显示新消息。我可以在按下发送按钮后显示已发送的消息,但没有收到消息,这在第一次创建 Activity 时工作正常。

编辑:我做了更多的调试,结果发现问题不在恢复 Activity 中,如果我第一次不使用 receives() 函数,并且在返回后恢复 Activity ,那么 receives() 将起作用,这意味着,函数在 receives() 内部:getListView().setSelection(messagex.size()-1); 只工作一次。 要么是第一次收到消息,要么是下一次,当且仅当它不是第一次在 Activity 中被调用。

最佳答案

我认为问题在于当您尝试恢复 Activity 时,您仍在运行之前的 mHandler 运行,因此您的消息实例没有被破坏,当您恢复 Activity 时它会产生问题。确保您的 mhandler 在调用 unstop 时销毁​​所有对象实例。

关于android - 如何在 Android 中管理 Activity 的 onPause、onResume 自定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21966891/

有关android - 如何在 Android 中管理 Activity 的 onPause、onResume 自定义适配器的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  3. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  8. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐