当我按下列表项时,我也得到了ArrayListIndexOutofBound。当我知道android时我已经正确编写了Parcelable代码。但我认为我的问题是回收器视图设置。我很困惑两个我的适配器的声明。帮助我
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
@Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
@Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
@Override
public Information[] newArray(int size) {
return new Information[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat错误
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
现在我在多年后得到它。我会简单地使用它。 FLAG_ACTIVITY_CLEAR_TOP - 如果已设置,并且正在启动的活动已在当前任务中运行,则不会启动该活动的新实例,而是将关闭其上的所有其他活动,并将此Intent传递给(现在在顶部)旧活动作为一个新的意图。