2

I am implementing a chat using a database MySQL in a server. Now, I want to update my custom Listview in Thread but I dont know how??

Heres my code:

chat_con_activity.java

    import android.app.Activity;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.os.SystemClock;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.Toast;

    import com.example.classes.IpUpdater;
    import com.example.classes.Messages_con_adapter;
    import com.example.classes.Send_Message;
    import com.example.classes.View_Messages;
    import com.example.tabs.user_online;
    import com.example.wifivoip.R;

    public class chat_con_activity extends Activity implements Runnable{
        private ListView list = null;
        ArrayAdapter<String> la;
        Button send_btn;
        EditText chat_msg;
        String user;
        String cTo;
        String[] names;
        String[] namesfrm;
        String[] msgs;
        String[] datez;
        int stop = 0;
        Context cn = this;
        Thread x;
        int count;
        Messages_con_adapter mca;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.send_chat);
            send_btn = (Button) findViewById(R.id.chat_btn_send);
            chat_msg = (EditText) findViewById(R.id.chat_text_send);
            user = getIntent().getStringExtra("cFrom");
            cTo = getIntent().getStringExtra("cTo");



            list = (ListView) findViewById(R.id.chat_list_view);

            Toast.makeText(getApplicationContext(), ""+user+" "+cTo, Toast.LENGTH_SHORT).show();
            display(); 

            x = new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    while(true){
                        try{
                            //Thread.sleep(1000);

                            View_Messages vm = new View_Messages(user, cTo);
                            int cnt = vm.getIfNew();
                            System.err.println(""+cnt+" "+count);
                            if(cnt != count){
                                System.err.println(""+cnt+" "+count);


                                names = vm.getAllNamesTo();
                                namesfrm = vm.getAllNamesFrom();
                                msgs = vm.getAllMsgs();
                                datez = vm.getAllDates();
                                count = vm.getIfNew();

                                list.setAdapter(la);
                                list.setSelection(list.getAdapter().getCount() - 1);

                            }
                            if(stop == 1){
                                break;
                            }

                        }catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                }
            });x.start();

            send_btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    String msg = chat_msg.getText().toString().trim();
                    if(!msg.equals("")){
                        new Send_Message().sendMessage(user, cTo, msg);
                        display();
                        chat_msg.setText("");
                    }else{
                        Toast.makeText(getApplicationContext(), "No message to send!!", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }


        @Override
        public void onDestroy(){
            super.onDestroy();
            stop = 1;
        }



        public void display(){
            View_Messages vm = new View_Messages(user, cTo);
            names = vm.getAllNamesTo();
            namesfrm = vm.getAllNamesFrom();
            msgs = vm.getAllMsgs();
            datez = vm.getAllDates();
            count = vm.getIfNew();

            list.setDivider(null);

            la = new Messages_con_adapter(this, user, names, namesfrm,msgs,datez,cTo);
            list.setAdapter(la);
            list.setSelection(list.getAdapter().getCount() - 1);
        }

My Adapter is: Message_con_adapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class Messages_con_adapter extends ArrayAdapter<String>{
    String user;
    String[] name;
    String[] namefrm;
    String[] msgs;
    String[] dates;
    Context context;
    View rowView;


    public Messages_con_adapter(Context context,String user, String[] name,String[] namefrm, String[] msgs,String[] dates,String To) {
        super(context, R.layout.chat_con,name);

        this.user = user;
        this.context = context;
        this.msgs = msgs;
        this.name = name;
        this.namefrm = namefrm;
        this.dates = dates;
        this.To = To;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);




        if(namefrm[position].equals(user)){
            rowView = inflater.inflate(R.layout.chat_con_home, parent, false);
            TextView dateTimeHome = (TextView) rowView.findViewById(R.id.time_c_home);
            TextView c_home = (TextView) rowView.findViewById(R.id.c_u_home);
            TextView c_home_m = (TextView) rowView.findViewById(R.id.c_u_home_m);
            dateTimeHome.setText(dates[position]);
            c_home.setText(user);
            c_home_m.setText(msgs[position]);


        }else
        {
            rowView = inflater.inflate(R.layout.chat_con, parent, false);
            TextView dateTimeAway = (TextView) rowView.findViewById(R.id.time_c_away);
            TextView c_away = (TextView) rowView.findViewById(R.id.c_u_away);
            TextView c_away_m = (TextView) rowView.findViewById(R.id.c_u_away_m);
            dateTimeAway.setText(dates[position]);
            c_away.setText(namefrm[position]);
            c_away_m.setText(msgs[position]);

        }

        return rowView;
    }

Any idea sir? please help. =(

Thanks in advance.

4 Answers4

1

Never update your listview from a non UI thread instead consider using handler.

nikhil.thakkar
  • 1,093
  • 7
  • 12
1

you can update your listview,

First of all, it's depend on you in which event you want to update your list view.

you can use onscroll listener in listview to update listview.

now question is how to update data in custom list view,

when data need to updated then you have call this method,

public void updateDate(String user, String[] name,String[] namefrm, String[] msgs,String[] dates,String To) {
    super(context, R.layout.chat_con,name);

    this.user = user;
    this.context = context;
    this.msgs = msgs;
    this.name = name;
    this.namefrm = namefrm;
    this.dates = dates;
    this.To = To;
}

this method to call in with ur previos adapter object and then call

adapterObject.notifyDataSetChanged();

your listview are update.

Krunal Indrodiya
  • 782
  • 2
  • 7
  • 19
0

I have the better solution. You can bind listView and your database and Android will automatically update your ListView if database refresh new data, so your work will be just receive message from server and put in the database.

To do that you need to implement ContentProvider -- it is a wrapper on SQLite database. After that you implement CursorAdapter -- it has litle difference from ArrayAdapter. The last step is call ContentProvider via ContentResolver which returns a cursor and also will notify your adapter about changes in table. For more details please see http://www.vogella.com/articles/AndroidSQLite/article.html#sqliteoverview_listviews

0

To update UI related components use AsyncTask to do that.
Its really easy and its best practice.
Here is the doc
From your provided code, use the same code you have done in run() method of your thread to
AsynTask's doInBackgrond() method.
EDIT
Since you are new to android you might want to look at the example here.

johntheripp3r
  • 989
  • 6
  • 15
  • I agree that the best would be to use AsyncTask but generally speaking the rule is to update views from UI thread so if not AsyncTask then runOnUiThread(Runnable) method or Handler. http://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread – fgeorgiew Nov 10 '13 at 11:02
  • Thank you for response sir but how can I call AsyncTask to execute it? Sorry I am new in Android. =) – Kent Sabanal Nov 10 '13 at 12:08