虽然这个论坛已经多次询问过这个问题。我读过它们但至少没有一个能为我工作。我差不多2天了,但无法弄清楚如何初始化线性布局和逃避NPE。我没有使用任何片段,并且想要在活动中初始化布局管理器。
下面是我的代码的重要部分,其余的代码与适配器和xml相同,所以不要写在这里....但是如果需要它,我也会提供它。
public class MainNews extends AppCompatActivity {
public RecyclerViewAdapter recyclerViewAdapter;
Toolbar toolbar;
private String[] inputStream;
public RecyclerView recyclerView;
//ArrayList<Data> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_news);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
String newsMain = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
new JSONAsync(getApplicationContext()).execute(newsMain);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this, JSONAsync.dataArray);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
@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();
return super.onOptionsItemSelected(item);
}
/////////////////////////////////////////////////////
public static class JSONAsync extends AsyncTask<String, String, Boolean> {
Context context;
public static List<Data> dataArray;
public JSONAsync(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return false;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public boolean downloadUrl(String myurl) throws IOException,JSONException {
InputStream is = null;
int response;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
response = conn.getResponseCode();
is = conn.getInputStream();
if (response == 200) {
String responseBody = convertStreamToString(conn.getInputStream());
JSONArray jArray = new JSONArray(responseBody);
// JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jobj = jArray.getJSONObject(i);
Data data = new Data();
data.setId(jobj.getInt("id"));
data.setHeading(jobj.getString("heading"));
data.setBrief(jobj.getString("brief"));
data.setDate(jobj.getString("date"));
dataArray.add(data);
}
return true;
} else return false;
} finally {
if (is != null) {
is.close();
}
}
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
@Override
protected void onPostExecute(Boolean result) {
if (result == true) {
Toast.makeText(context, "Data Fetched, now do some work with it AH", Toast.LENGTH_LONG).show();
} else
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
这是logcat。
FATAL EXCEPTION: AsyncTask #1
Process: admin.myproject, PID: 11032
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at admin.myproject.MainNews$JSONAsync.downloadUrl(MainNews.java:128)
at admin.myproject.MainNews$JSONAsync.doInBackground(MainNews.java:90)
at admin.myproject.MainNews$JSONAsync.doInBackground(MainNews.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818) enter code here
P.S:我已经使JSONAsync类静态/非静态,其他的东西都被改变但是没有用。
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
dataArray未初始化。将其更改为
public static List<Data> dataArray = new Arraylist();
答案 1 :(得分:1)
您尝试添加的数组列表从未初始化。在添加任何值之前,必须先将其初始化。
试试这个
public static List<Data> dataArray = new Arraylist();
或者你也可以这样做
List<Data> dataArray;
public boolean downloadUrl(String myurl) throws IOException,JSONException {
InputStream is = null;
int response;
dataArray = new List<Data>();
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
response = conn.getResponseCode();
is = conn.getInputStream();
if (response == 200) {
String responseBody = convertStreamToString(conn.getInputStream());
JSONArray jArray = new JSONArray(responseBody);
// JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jobj = jArray.getJSONObject(i);
Data data = new Data();
data.setId(jobj.getInt("id"));
data.setHeading(jobj.getString("heading"));
data.setBrief(jobj.getString("brief"));
data.setDate(jobj.getString("date"));
dataArray.add(data);
}
return true;
} else return false;
} finally {
if (is != null) {
is.close();
}
}