我正在使用swiperefreshlayout
刷新列表视图。刷新时,当我尝试向上滚动或向下滚动列表视图时,应用程序崩溃了。有人可以给我解决我的问题。
logcat的
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at latestcardview.CustomBaseAdapter.getView(CustomBaseAdapter.java:206)
at android.widget.AbsListView.obtainView(AbsListView.java:2467)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5424)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3569)
at android.widget.AbsListView.onTouchMove(AbsListView.java:3950)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3788)
at android.view.View.dispatchTouchEvent(View.java:8444)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2158)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2436)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2178)at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2386)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1727)
at android.app.Activity.dispatchTouchEvent(Activity.java:2764)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2335)
at android.view.View.dispatchPointerEvent(View.java:8655)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4238)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4094)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3694)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3660)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3773)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3668)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3830)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3640)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3694)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3660)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3668)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3640)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5940)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5908)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5872)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6030)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:211)
at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method )
at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:197)
at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:6001)
at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:6062)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:792)
at android.view.Choreographer.doCallbacks(Choreographer.java:596)
at android.view.Choreographer.doFrame(Choreographer.java:555)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:778)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:102 9)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
代码
public class CustomBaseAdapter extends BaseAdapter {
private int ConvertPixelsToDp(float pixelValue)
{
int dp = (int) ((pixelValue)/ Resources.getSystem().getDisplayMetrics().density);
return dp;
}
private static LayoutInflater inflater = null;
ArrayList<String> userName,
jokeLike, jok_id,jok_desc,jok_img,jok_is_active,jok_nsfw,jok_total_comments,jok_total_flags,
jok_total_shares,jok_created_on,jok_modified_on, jok_userimg,likeCount,dislikeCount,popularJoke,languagename;
TextView tv_share,tv_comment,tv_smile,tv_frown;
Bitmap bmp;
String image_url,path;
Context context;
String joke_status;
String joke_id, status, user_id, time_pass,user_type_id,desc;
private ProgressDialog pDialog;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
int width;
String time,userLikeString, userDislikeString,popularstatus;
String big_url;
String jokeingid;
String option;
String like_response;
public CustomBaseAdapter(FragmentActivity mainActivity,
ArrayList<String> UserName,
ArrayList<String> JokeLike,
ArrayList<String> Jok_id,
ArrayList<String> Jok_desc,
ArrayList<String> Jok_img,
ArrayList<String> Jok_is_active,
ArrayList<String> Jok_nsfw,
ArrayList<String> Jok_total_comments,
ArrayList<String> Jok_total_flags,
ArrayList<String> Jok_total_shares,
ArrayList<String> Jok_created_on,
ArrayList<String> Jok_modified_on,
ArrayList<String> Jok_userimg,
ArrayList<String> LikeCount,
ArrayList<String> DislikeCount,
ArrayList<String> JokePopular,
ArrayList<String>languageName) {
// TODO Auto-generated constructor stub
/*
set parameter to the variable
*/
userName = UserName;
jokeLike = JokeLike;
jok_id = Jok_id;
jok_desc = Jok_desc;
jok_img = Jok_img;
jok_is_active = Jok_is_active;
jok_nsfw = Jok_nsfw;
jok_total_comments = Jok_total_comments;
jok_total_flags = Jok_total_flags;
jok_total_shares = Jok_total_shares;
jok_created_on = Jok_created_on;
jok_modified_on = Jok_modified_on;
jok_userimg = Jok_userimg;
likeCount = LikeCount;
dislikeCount = DislikeCount;
popularJoke = JokePopular;
languagename = languageName;
context = mainActivity;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return userName.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.cardview_backend_latest, null);
pref = context.getSharedPreferences("MyPref", 0);
editor = pref.edit();
user_id = pref.getString("userId", null); // getting String
user_type_id = pref.getString("typeId", null);
holder.UserNameTxt = (TextView) rowView.findViewById(R.id.jokes_username); // set textView to xml id
holder.up = (ImageView) rowView.findViewById(R.id.up);
holder.down = (ImageView) rowView.findViewById(R.id.down);
holder.user_profile = (ImageView) rowView.findViewById(R.id.jokes_user_profile);
holder.jokeId = (TextView) rowView.findViewById(R.id.jokesId);
holder.username = (TextView) rowView.findViewById(R.id.jokes_username);
holder.description = (TextView) rowView.findViewById(R.id.jokes_description);
holder.smiles = (TextView) rowView.findViewById(R.id.jokes_smiles);
holder.frowns = (TextView) rowView.findViewById(R.id.jokes_frowns);
holder.comments = (TextView) rowView.findViewById(R.id.jokes_comments);
holder.share = (TextView) rowView.findViewById(R.id.jokes_share);
holder.time = (TextView) rowView.findViewById(R.id.time);
holder.languagename = (TextView) rowView.findViewById(R.id.lang);
holder.list_image = (ImageView) rowView.findViewById(R.id.jokes_list_image);
holder.extend = (LinearLayout) rowView.findViewById(R.id.extend);
holder.share_icon = (LinearLayout)rowView.findViewById(R.id.share_icon);
holder.flag_icon = (LinearLayout)rowView.findViewById(R.id.flag_icon);
holder.comment_icon = (ImageView) rowView.findViewById(R.id.comment_icon);
holder.markPopular = (CheckBox) rowView.findViewById(R.id.mark_popular);
tv_share = (TextView)rowView.findViewById(R.id.tv_share);
tv_comment = (TextView)rowView.findViewById(R.id.tv_comments);
tv_smile = (TextView)rowView.findViewById(R.id.tv_smiles);
tv_frown = (TextView)rowView.findViewById(R.id.tv_frowns);
if(user_type_id.equals("1")){
holder.markPopular.setVisibility(View.VISIBLE);
}
holder.UserNameTxt.setText(userName.get(position).toString());// set the value to textView
holder.smiles.setText(likeCount.get(position).toString());
holder.frowns.setText(dislikeCount.get(position).toString());
holder.comments.setText(jok_total_comments.get(position));
holder.share.setText(jok_total_shares.get(position));
holder.description.setText(jok_desc.get(position).toString());
if(languagename.get(position).toString().equals("")) {
holder.languagename.setText("Not Mentioned");
} else {
holder.languagename.setText(languagename.get(position).toString());
}
Log.e("Languagename",languagename.get(position).toString());
time = jok_created_on.get(position).toString().substring(0, 19);
String userjokeposttime = jok_created_on.get(position).toString();
Log.e("userjokeposttime", userjokeposttime);
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTime jodatime = dtf.parseDateTime(time);
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd/MM/yyyy");
System.out.println(dtfOut.print(jodatime));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
width = context.getResources().getDisplayMetrics().widthPixels;
DisplayMetrics display = this.context.getResources().getDisplayMetrics();
int widthInDp = ConvertPixelsToDp(display.widthPixels);
return rowView;
}
public class Holder {
TextView UserNameTxt, jokeId, username, description, smiles, frowns, comments, share, time,languagename; //Initialize TextView variable
ImageView up, down, user_profile, list_image, comment_icon;
LinearLayout extend,share_icon,flag_icon;
CheckBox markPopular;
}
public class LikeTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Global_Url.like_url);
try {
// Add your data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("jid",joke_id));
nameValuePair.add(new BasicNameValuePair("uid", user_id));
nameValuePair.add(new BasicNameValuePair("status", status));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
Log.e("jokegdg",joke_id+user_id+status);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
@Override
protected void onPostExecute(String result) {
try {
JSONObject jsono = new JSONObject(result);
String jarray = jsono.getString("status");
if(jarray.equals("0")){
Toast.makeText(context, "you didnt like", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, like_response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Response", result.toString());
}
}
}
protected void onPostExecute(final Bitmap result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, "Title", null);
Uri bmpUri = Uri.parse(path);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, desc);
sendIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
sendIntent.setType("image/*");
context.startActivity(sendIntent);
}
}
}
}
}
public class Latest_Jokes extends Fragment {
View inflatedView = null;
private ProgressDialog pDialog;
ArrayList<GetSetJokes> jokesList = new ArrayList<GetSetJokes>();
ArrayList<String> userName = new ArrayList<String>();
ArrayList<String> jokeLike = new ArrayList<String>();
ArrayList<String> jok_id = new ArrayList<String>();
ArrayList<String> jok_desc = new ArrayList<String>();
ArrayList<String> jok_img = new ArrayList<String>();
ArrayList<String> jok_is_active = new ArrayList<String>();
ArrayList<String> jok_nsfw = new ArrayList<String>();
ArrayList<String> jok_total_comments = new ArrayList<String>();
ArrayList<String> jok_total_flags = new ArrayList<String>();
ArrayList<String> jok_total_shares = new ArrayList<String>();
ArrayList<String> jok_created_on = new ArrayList<String>();
ArrayList<String> jok_modified_on = new ArrayList<String>();
ArrayList<String> jok_username = new ArrayList<String>();
ArrayList<String> jok_userimg = new ArrayList<String>();
ArrayList<String> like_status = new ArrayList<String>();
ArrayList<String> likeCount = new ArrayList<String>();
ArrayList<String> dislikeCount = new ArrayList<String>();
ArrayList<String> popularJoke = new ArrayList<String>();
ArrayList<String> languagename = new ArrayList<String>();
private SwipeRefreshLayout mSwipeRefreshLayout = null;
private Context mContext;
int width;
String nsfwcode, jsonStr, userId;
JSONArray jarray;
ListView listview;
ImageView extend;
private String new_url = Global_Url.jokes_url;
int current_page = 1;
String con_url = new_url.concat("?page" + String.valueOf(2));
private SharedPreferences.Editor editor;
private SharedPreferences pref;
private int SCROLL_TO_POSITION = 0;
private int mPreLast;
int iTest = 0;
public Latest_Jokes() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.latest_jokes, container, false);
mSwipeRefreshLayout = (SwipeRefreshLayout) inflatedView.findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setColorSchemeResources(R.color.yelow);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
SCROLL_TO_POSITION = 0;
iTest = 0;
current_page = 1;
int mPreLast;
jok_id.clear();
jok_desc.clear();
jok_img.clear();
jok_is_active.clear();
jok_nsfw.clear();
jok_total_comments.clear();
jok_total_flags.clear();
jok_total_shares.clear();
jok_created_on.clear();
jok_modified_on.clear();
userName.clear();
jokeLike.clear();
jok_userimg.clear();
likeCount.clear();
dislikeCount.clear();
popularJoke.clear();
languagename.clear();
new LatestTask().execute();
}
});
pref = getActivity().getSharedPreferences("MyPref", 0);
editor = pref.edit();
width = getActivity().getResources().getDisplayMetrics().widthPixels;
extend = (ImageView) inflatedView.findViewById(R.id.extend);
listview = (ListView) inflatedView.findViewById(R.id.list_jokes);
userId = pref.getString("userId", null);
nsfwcode = pref.getString("nswKey",null);// getting String
new LatestTask().execute(nsfwcode,userId);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (mPreLast != lastItem) {
mPreLast = lastItem;
if (SCROLL_TO_POSITION >= 10) {
new LatestTask().execute();
iTest = 1;
}
}
}
}
});
return inflatedView;
}
private class LatestTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mSwipeRefreshLayout.setRefreshing(true);
}
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Global_Url.jokes_url);
try {
userId = pref.getString("userId", null);
nsfwcode = pref.getString("nswKey",null);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("page", String.valueOf(current_page)));
nameValuePair.add(new BasicNameValuePair("uid", userId));
nameValuePair.add(new BasicNameValuePair("nsfw", nsfwcode));
Log.e("userId",userId+nsfwcode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
@Override
protected void onPostExecute(String result) {
jsonStr = result;
if (jsonStr != null) {
JSONObject jsono = null;
try {
jsono = new JSONObject(jsonStr);
jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
jok_id.add(object.getString("jok_id"));
jok_desc.add(object.getString("jok_desc"));
jok_img.add(object.getString("jok_img"));
jok_is_active.add(object.getString("jok_is_active"));
jok_nsfw.add(object.getString("jok_nsfw"));
jok_total_comments.add(object.getString("jok_total_comments"));
jok_total_flags.add(object.getString("jok_total_flags"));
jok_total_shares.add(object.getString("jok_total_shares"));
jok_created_on.add(object.getString("jok_created_on"));
jok_modified_on.add(object.getString("jok_modified_on"));
userName.add(object.getString("jok_username"));
jokeLike.add(object.getString("likeStatus"));
jok_userimg.add(object.getString("jok_userimg"));
likeCount.add(object.getString("likeCount"));
dislikeCount.add(object.getString("dislikeCount"));
popularJoke.add(object.getString("jok_is_popular"));
languagename.add(object.getString("language"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listview.setAdapter(new CustomBaseAdapter(getActivity(), userName, jokeLike, jok_id, jok_desc, jok_img, jok_is_active, jok_nsfw,
jok_total_comments, jok_total_flags, jok_total_shares, jok_created_on
, jok_modified_on, jok_userimg, likeCount, dislikeCount, popularJoke,languagename));
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
if (iTest == 1) {
listview.setSelection(SCROLL_TO_POSITION-2);
}
if (jsonStr != null) {
try {
SCROLL_TO_POSITION = current_page * 10;
current_page++;
} catch (Exception e) {
}
}
}
}
}