TCP套接字连接,在列表视图中接收和显示数据。

时间:2013-07-03 08:45:37

标签: android sockets tcp indexoutofboundsexception

我正在做一个TCP套接字连接的项目。 从服务器接收json数据并将其显示在列表视图中。 服务器每1秒连续发送数据 我收到索引超出绑定异常的错误无效的索引4大小是4。 我的代码如下。 我认为问题在于用户u = list.get(position);和runonUIthread。

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity{

String str;

ArrayList<User> list = new ArrayList<User>();;

ArrayAdapter<User> adb;
ListView lv;

SQLiteAdapter sqladapter = new SQLiteAdapter(MainActivity.this);;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    lv = (ListView) findViewById(R.id.listView1);
    new Thread(new Client()).start();
     Timer tm = new Timer(); 
}

public class Client implements Runnable{

    @Override
    public void run() {
        try {
            Socket s = new Socket("My IP",My Port);
           while(s.isConnected()){
            BufferedReader in =  new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            int nRead;
            char[] data = new char[1024+512];
            String decoded= "";
            Date date = new Date();
            long time = date.getTime();
            while ((nRead = in.read(data, 0, data.length)) != -1) {

              decoded += new String(data,0,nRead);
              if(decoded.contains("{") && decoded.contains("}")){
               str = decoded.substring(decoded.indexOf('{'),decoded.indexOf('}')+1);
              decoded = decoded.substring(decoded.indexOf('}')+1);
              if(!decoded.contains("{"))
                  decoded = "";
            try {           
                JSONArray results = new JSONArray("["+str+"]");
                for (int i = 0; i < results.length(); i++) {
                    JSONObject jsonObject;
                    jsonObject = results.getJSONObject(i);              
                    String symbol = jsonObject.getString("Symbol");
                    double high = Double.parseDouble(jsonObject.getString("High"));
                    double low = Double.parseDouble(jsonObject.getString("Low"));
                    sqladapter = sqladapter.opentowrite();
                    boolean insertOrUpdate = sqladapter.checkDB(symbol);                                
                    if(insertOrUpdate== false){                         
                        User user = new User(jsonObject.getString("Symbol"),
                        jsonObject.getString("AskPrice"),
                        jsonObject.getString("BidPrice"),
                        jsonObject.getString("Open"),
                        jsonObject.getString("High"),
                        jsonObject.getString("Low"),
                        jsonObject.getString("Close"),
                        jsonObject.getString("PerChange"),
                        jsonObject.getString("NetChange"),
                        jsonObject.getString("Volume"));
                        sqladapter.insert(user);
                        list.add(user); 
                    }
                    else{
                        int j;
                        for(j = 0; j<list.size();j++){
                            User obj = list.get(j);
                            if(obj.getSymbol().equalsIgnoreCase(symbol)){
                                list.remove(obj);
                                System.out.println("REMOVIED "+obj.getSymbol());
                                break;
                            }
                        }
                        User user2 = new User(jsonObject.getString("Symbol"),
                                jsonObject.getString("AskPrice"),
                                jsonObject.getString("BidPrice"),
                                jsonObject.getString("Open"),
                                high+"",low+"",
                                jsonObject.getString("Close"),
                                jsonObject.getString("PerChange"),
                                jsonObject.getString("NetChange"),
                                jsonObject.getString("Volume"));
                                list.add(j,user2);
                                System.out.println("ADDED :"+j);                            
                            }
                            updateList();
                            runOnUiThread(new Runnable() {  
                                @Override
                                public void run() {
                                lv.setAdapter(adb);

                                adb.notifyDataSetChanged();
lv.invalidateViews();
lv.getCount();      
                            }
                        });                 
                    }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
              }
              System.out.println(date.getTime()- time);
            }
           }
            s.close();


    } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
    }
}


public void updateList() {
    adb = new ArrayAdapter<User>(MainActivity.this, R.layout.rssitemview,list){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view=convertView;
            if(null == view) {
                    LayoutInflater vi = (LayoutInflater)MainActivity.this.
                            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    view = vi.inflate(R.layout.rssitemview, null);
            }  
            User u = list.get(position);             

            if(null != u)
            {
                TextView title = (TextView)view.findViewById(R.id.symbol);
                TextView persend = (TextView)view.findViewById(R.id.persent);
                TextView ltp = (TextView)view.findViewById(R.id.ltp);
                TextView open = (TextView)view.findViewById(R.id.open);
                TextView high = (TextView)view.findViewById(R.id.high);
                TextView low = (TextView)view.findViewById(R.id.low);
                TextView close = (TextView)view.findViewById(R.id.close);
                title.setText(u.getSymbol().substring(0, 5));
                ltp.setText(u.getPerChange().substring(0, 4));
                persend.setText(u.getVolume().substring(0, 4));
                open.setText(u.getOpen().substring(0, 4));
                high.setText(u.getHigh().substring(0, 4));
                low.setText(u.getLow().substring(0, 4));
                close.setText(u.getClose().substring(0, 4));

            }

            return view;

        }

    };

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

请帮助..

0 个答案:

没有答案