Поэтому я пытался извлечь все сообщения из REST API, которые я сделал, чтобы вывести их в текстовое представление в моей Posts
активности. Я могу успешно извлечь объекты JSON и сохранить их в соответствующих списках ArrayLists. Однако всякий раз, когда я вызываю свою ListPosts
функцию из моей Posts
активности в onPostExecute
AsyncTask, это говорит о том, что мое postsSect
текстовое представление равно нулю.
Я думаю, что по какой-то причине с R.id
не связываются, хотя я объявил это в onCreate
из моих Posts
. Из-за этого я получаю это сообщение об ошибке в моей logcat:
01-14 21:43:57.022 16588-16588/com.example.android.androidcraftsappprototype E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.androidcraftsappprototype, PID: 16588
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.android.androidcraftsappprototype.WSAdapter$SendPostsRequest.onPostExecute(WSAdapter.java:186)
at com.example.android.androidcraftsappprototype.WSAdapter$SendPostsRequest.onPostExecute(WSAdapter.java:104)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendPostsRequest PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
@Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
//postDetailsHelper.ListPosts();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postsSect = (TextView) findViewById(R.id.PostsSection);
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.callPostDetails("http://192.168.0.18:8000/api/");
//postDetailsHelper.ListPosts();
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter().new SendPostsRequest();
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
this.post_id.add(p_id);
this.post_title.add(p_title);
this.post_content.add(p_content);
}
public ArrayList<Integer> getPostID() {
return this.post_id;
}
public ArrayList<String> getPostTitle() {
return this.post_title;
}
public ArrayList<String> getPostContent() {
return this.post_content;
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
int lastFrJSONArray = getPostID().size() - 1;
postsSect = (TextView) findViewById(R.id.PostsSection);
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + getPostID().get(0) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + getPostTitle().get(i) + "\n");
postsSect.append("content: " + getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + getPostID().get(i) + "\n");
}
}
}
}
}
WSAdapter.java
public class WSAdapter {
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
public class SendPostsRequest extends AsyncTask<String, String, String> {
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
private WeakReference<Activity> mPostReference;
/*public SendPostsRequest(Activity activity){
mPostReference = new WeakReference<Activity>(activity);
}*/
@Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
try {
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
/*finally {
urlConnection.disconnect();
}*/
return result.toString();
}
@Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
postsHelper.ListPosts();
}
}
}