So I was trying to retrieve all the posts from the REST API I made to be outputted to a textview in my Posts
activity. I can successfully retrieve the JSON Objects and store them in their corresponding ArrayLists. However, whenever I call my ListPosts
function from my Posts
activity within the AsyncTask's onPostExecute
, its saying that my postsSect
textview is null.
I am thinking that for some reason the R.id
is not getting contacted, even though I declared it in onCreate
of my Posts
. Because of this I'm getting this error message in my 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();
}
}
}
First of all restructure your code. And for setting text make those fields static which you want to use and then set their values in the onPostExecute of AsyncTask or else you can return the jsonstring as it is to your activity and then parse it there and set values for better readability.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.