0

I am trying to make a custom list to show data from an arraylist but it gave me a NullPointerException in this line:

tvtitle.setText(all.get(position).getTitle());

all is arraylist that have objects contain field Title

Here is the activity that has the custom list class as an inner class

package com.heshamkadry.social.app;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.heshamkadry.social.Api.OnTaskCompleteTodo;
import com.heshamkadry.social.Api.TodoAPI;
import com.heshamkadry.social.R;
import com.heshamkadry.social.Users.ToDo;

import java.util.ArrayList;

public class TodoView extends AppCompatActivity implements OnTaskCompleteTodo {
TodoAPI todoAPI;
ListView lsview;
ArrayList<ToDo> all;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_todo_view);
    ProgressDialog progressDialog = new ProgressDialog(this);
    lsview = (ListView) findViewById(R.id.ActivityTodoView_ListView_Todo);
    todoAPI = new TodoAPI(this , progressDialog);
    id = getIntent().getStringExtra("id");
    todoAPI.execute("?userId="+id);
}

@Override
public void OnCompleteListner() {
    try
    {
        all=todoAPI.get();
        CustomAdapter myarrayadapter = new CustomAdapter(this , android.R.layout.simple_list_item_1 , all);
        lsview.setAdapter(myarrayadapter);
    }catch (Exception x){
        x.printStackTrace();
    }

}

public class CustomAdapter extends ArrayAdapter
{
    public LayoutInflater inflator;

    CustomAdapter(Context context , int resourses , ArrayList objects){
        super(context,resourses,objects);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(inflator == null){
            inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }if(convertView == null){
            convertView = inflator.inflate(R.layout.listt_item ,null);
        }

        TextView tvtitle = (TextView) convertView.findViewById(R.id.ListItem_TextView_title);
        TextView tvcoler = (TextView) convertView.findViewById(R.id.ListItem_TextView_coloer);

        tvtitle.setText(all.get(position).getTitle());

        if(all.get(position).isCompleted()){
            tvcoler.setBackgroundColor(0xFF00CC00);
        }else{
            tvcoler.setBackgroundColor(0xFF00CCCC);
        }
        return convertView;
    }
}
}

Here is the custom list xml

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="match_parent"
  android:layout_height="match_parent">

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_marginStart="15dp"
    android:layout_marginTop="19dp"
    android:id="@+id/ListItem_TextView_title" />

<TextView
    android:text="TextView"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_alignBottom="@+id/ListItem_TextView_title"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="14dp"
    android:id="@+id/ListItem_TextView_coloer"
    android:background="@color/colorAccent" />
</RelativeLayout>

Here is the exception

02-11 12:06:59.356 30758-30758/com.heshamkadry.social E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        java.lang.NullPointerException
                                                                            at com.heshamkadry.social.app.TodoView$CustomAdapter.getView(TodoView.java:72)
                                                                            at android.widget.AbsListView.obtainView(AbsListView.java:2181)
                                                                            at android.widget.ListView.makeAndAddView(ListView.java:1880)
                                                                            at android.widget.ListView.fillDown(ListView.java:687)
                                                                            at android.widget.ListView.fillDown(ListView.java:666)
                                                                            at android.widget.ListView.fillFromTop(ListView.java:758)
                                                                            at android.widget.ListView.layoutChildren(ListView.java:1695)
                                                                            at android.widget.AbsListView.onLayout(AbsListView.java:2016)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.widget.FrameLayout.onLayout(FrameLayout.java:452)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.widget.FrameLayout.onLayout(FrameLayout.java:452)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
                                                                            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
                                                                            at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.widget.FrameLayout.onLayout(FrameLayout.java:452)
                                                                            at android.view.View.layout(View.java:14471)
                                                                            at android.view.ViewGroup.layout(ViewGroup.java:4562)
                                                                            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1986)
                                                                            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
                                                                            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009)
                                                                            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508)
                                                                            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
                                                                            at android.view.Choreographer.doCallbacks(Choreographer.java:562)
                                                                            at android.view.Choreographer.doFrame(Choreographer.java:532)
                                                                            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
                                                                            at android.os.Handler.handleCallback(Handler.java:730)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                            at android.os.Looper.loop(Looper.java:213)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5225)
                                                                            at java.lang.reflect.Method.invokeNative(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:525)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
                                                                            at dalvik.system.NativeStart.main(Native Method)

it runs with no problems with the simple list view

EDIT

Here is the todo asynkTask

package com.heshamkadry.social.Api;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Base64;

import com.heshamkadry.social.Users.ToDo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Hesham Kadry on 2/10/2017.
 */

public class TodoAPI extends AsyncTask<String , String ,ArrayList<ToDo>> {
    ProgressDialog progressDialog;
    OnTaskCompleteTodo onTaskCompleteTodo;

    public TodoAPI(OnTaskCompleteTodo onTaskCompleteTodo , ProgressDialog progressDialog){
        this.progressDialog = progressDialog;
        this.onTaskCompleteTodo = onTaskCompleteTodo;
    }

    @Override
    protected void onPreExecute() {
        progressDialog.setMessage("loading......");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected ArrayList<ToDo> doInBackground(String... strings)
    {
        ArrayList<ToDo> alltodo = new ArrayList<ToDo>();

        try
        {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://jsonplaceholder.typicode.com/todos"+strings[0]);
            String authorizationString = "Basic " + Base64.encodeToString(
                    ("tester" + ":" + "tm-sdktest").getBytes(),
                    Base64.NO_WRAP);

            request.setHeader("Authorization", authorizationString);
            HttpResponse response = client.execute(request);

            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity);
            int statuescode = response.getStatusLine().getStatusCode();

            if(statuescode == 200)
            {
                JSONArray jsonArray = new JSONArray(result);

                for (int counter=0 ; counter<jsonArray.length() ; counter++)
                {
                    JSONObject jsonObject = jsonArray.getJSONObject(counter);
                    int userid = jsonObject.getInt("userId");
                    int id = jsonObject.getInt("id");
                    String title = jsonObject.getString("title");
                    boolean completed = jsonObject.getBoolean("completed");

                    ToDo toDo = new ToDo(userid , id , title , completed);

                    alltodo.add(toDo);
                }
            }

        }
        catch (Exception c)
        {
            c.printStackTrace();
        }
        return alltodo;
    }

    @Override
    protected void onPostExecute(ArrayList<ToDo> toDos) {
        progressDialog.dismiss();
        onTaskCompleteTodo.OnCompleteListner();
    }
}
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
  • your getView method returns some null value. – Ankush Bist Feb 10 '17 at 10:18
  • show your getCount(),getItemId() etc of array adapter – Rasel Feb 10 '17 at 10:21
  • Not sure why this issue marked as duplicated, as it is more particular case comparing to one that mentioned in duplicated reason. So far, I'm having the same issue with custom TextView and custom Attribute. Still can't resolve it. – Kostanos Feb 19 '19 at 23:33

2 Answers2

1

Your ArrayList, "all", might not be initialized yet. That's why you get a nullpointerexception. Check where you initialize it and make sure that code is run first and you should be good. If you want to make sure where your code fails, I recommend to run it in debugger with breakpoints and stepping through.

Community
  • 1
  • 1
Jerri Kangasniemi
  • 633
  • 1
  • 9
  • 23
1

Instantiate your arraylist inside onCreate.

all = new Arraylist<>();

This will most likely solve your issue. If not post the new stack trace

Kushan
  • 5,855
  • 3
  • 31
  • 45
  • alright ... anyway this will prevent another NullPointerException – Kushan Feb 10 '17 at 11:33
  • try convertView = LayoutInflater.from(getContext()).inflate(R.layout.listt_item, parent, false); ...... delete your member inflater and use this directly. – Kushan Feb 10 '17 at 11:36