通过服务器更新列表视图并显示更新的列表视图而不连接

时间:2016-11-09 11:03:59

标签: java android listview indexoutofboundsexception

大家好我已经面临这个问题已经很多天了,但是在google上找不到正确的解决方案。我想创建一个与我的服务器同步的聊天应用程序我已经实现了一种技术,每隔8秒从服务器获取数据,并在列表视图中显示更新的一个并清除前一个。我遇到的问题是,当我滚动我的列表视图时,它会崩溃应用程序并显示我在logcat中发布的错误。

logcat的:

java.lang.IndexOutOfBoundsException: Invalid index 13, size is 0

MainActivity.java

import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;  
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends ListActivity
{
Handler h;int delay;
private static final String REGISTER_URL =  "http://friends.ueuo.com/chat.php";
public static final String RECEVIE_URL = "http://friends.ueuo.com/rec.php";
String message,Sender_name;
public static final String KEY_SEND = "send";
public static final String KEY_RECEIVE = "receive";
public static final String KEY_MESSAGE = "Message";

ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayAdapter<String> adapter,adapter1;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Receive();

     h = new Handler();
    delay = 15000; //milliseconds

    h.postDelayed(new Runnable()
    {
        public void run()
        {
            list.clear();
            Receive();
            h.postDelayed(this, delay);

        }
    }, delay);






    Button btn = (Button) findViewById(R.id.addItem);
    adapter = new ArrayAdapter<String>(this,R.layout.my_custom_layout,  list);

    OnClickListener listener = new OnClickListener()
    {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            EditText edit = (EditText) findViewById(R.id.text);
            message = edit.getText().toString();
            String sender = "Sender"+System.lineSeparator()+"";
            list.add(sender+edit.getText().toString());
            setListAdapter(adapter);
            adapter.notifyDataSetChanged();
            registerUser();
        }
    };


    btn.setOnClickListener(listener);


}





private void registerUser()
{


    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_SEND, "ad@gmail.com");
            params.put(KEY_RECEIVE, "bv@gmail.com");
            params.put(KEY_MESSAGE, message);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}




private void Receive()
{


    StringRequest stringRequest = new StringRequest(RECEVIE_URL, new Response.Listener<String>()
    {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onResponse(String response)
        {

            showJSON(response);
        }
    },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                     Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG ).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void showJSON(String response)
{
    JSONObject jsonObject=null;
    JSONArray users = null;
    try
    {
        jsonObject = new JSONObject(response);
        users = jsonObject.getJSONArray("result");

        // JSONObject jsonObject = new JSONObject(response);
        //JSONArray result = jsonObject.getJSONArray("result");
        // JSONObject collegeData = result.getJSONObject(2);
        // name = collegeData.getString("message");
        for(int i=0;i<users.length();i++)
        {

            JSONObject jo = users.getJSONObject(i);
            message=jo.getString("message");
            Sender_name=jo.getString("sendby");
            if (Sender_name.equals("ad@gmail.com"))

            {


                String sender="Wajid Usman"+System.lineSeparator()+"";
                list.add(sender+message);
                setListAdapter(adapter);
                adapter.notifyDataSetChanged();



            }
            else

            {

                String receiver="Salman"+System.lineSeparator()+System.lineSeparator();
                list.add(receiver+message);
                setListAdapter(adapter);
                adapter.notifyDataSetChanged();
            }



        }


    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }

}

}

1 个答案:

答案 0 :(得分:0)

这意味着你有ArrayList,它有0个元素,你可以得到每个元素,如0,1,2,ecc位置。并且您正在尝试读取ArrayList中不存在的第12个元素。