-3

I am new to android development, i am learning working with SQLite databases, when i create a database and retrieve data from it this error show up. Kindly do let me know if any other code u needed to see.

Here is my mainActivity:

public static final String LOGTAG = "EMPLOYEES";

public static final String Name = "name";
public static final String Pic = "pic";
public static final String Position = "position";
public static final String Qualification = "qualification";
public static final String Expertise = "expertise";
public static final String Contact = "contact";


public static final int DETAIL_REQUEST_CODE = 1001;
protected List<TeamDetails> data;

private SharedPreferences settings;
private SharedPreferences.OnSharedPreferenceChangeListener listener;

EmployeeDataSource datasource;

private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    datasource = new EmployeeDataSource(this);
    datasource.open();

    List<TeamDetails> teamDetails = datasource.findAll();
    if (teamDetails.size() == 0) {
        createData();
        teamDetails = datasource.findAll();
    }


    ArrayAdapter<TeamDetails> courseArrayAdapter =
            new nameArrayAdapter(this, 0, data);
    ListView listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(courseArrayAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TeamDetails teamDetails = data.get(position);
            displayDetail(teamDetails);
        }
    });

    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

@Override
protected void onResume() {
    super.onResume();
    datasource.open();
}

@Override
protected void onPause() {
    super.onPause();
    datasource.close();
}

private void createData() {

    TeamDetails teamDetails = new TeamDetails();
    teamDetails.setName("M Jaleed");
    teamDetails.setPosition("Team Lead");
    teamDetails.setQualities("Masters");
    teamDetails.setExpertise("Android Development");
    teamDetails.setContact(03331234567);
    teamDetails.setImage("");
    teamDetails = datasource.create(teamDetails);
    Log.i(LOGTAG, "Details has been added" + teamDetails.getId());

    teamDetails = new TeamDetails();
    teamDetails.setName("Sajawal Nawaz");
    teamDetails.setPosition("Internee");
    teamDetails.setQualities("Bachelors");
    teamDetails.setExpertise("Android Development");
    teamDetails.setContact(03331234567);
    teamDetails.setImage("");
    teamDetails = datasource.create(teamDetails);
    Log.i(LOGTAG, "Details has been added" + teamDetails.getId());

    teamDetails = new TeamDetails();
    teamDetails.setName("Waqas Khan");
    teamDetails.setPosition("Internee");
    teamDetails.setQualities("Bachelors");
    teamDetails.setExpertise("Android Development");
    teamDetails.setContact(03331234567);
    teamDetails.setImage("");
    teamDetails = datasource.create(teamDetails);
    Log.i(LOGTAG, "Details has been added" + teamDetails.getId());

    teamDetails = new TeamDetails();
    teamDetails.setName("Waqas Khan Swat");
    teamDetails.setPosition("Internee");
    teamDetails.setQualities("Bachelors");
    teamDetails.setExpertise("Android Development");
    teamDetails.setContact(03331234567);
    teamDetails.setImage("");
    teamDetails = datasource.create(teamDetails);
    Log.i(LOGTAG, "Details has been added" + teamDetails.getId());

    teamDetails = new TeamDetails();
    teamDetails.setName("Arslan Shah");
    teamDetails.setPosition("Internee");
    teamDetails.setQualities("Bachelors");
    teamDetails.setExpertise("Android Development");
    teamDetails.setContact(03331234567);
    teamDetails.setImage("");
    teamDetails = datasource.create(teamDetails);
    Log.i(LOGTAG, "Details has been added" + teamDetails.getId());


}


private void displayDetail(TeamDetails teamDetails) {
    Intent intent = new Intent(this, DetailActivity.class);
    intent.putExtra(Name, teamDetails.getName());
    intent.putExtra(Pic, teamDetails.getImage());
    intent.putExtra(Position, teamDetails.getPosition());
    intent.putExtra(Qualification, teamDetails.getQualities());
    intent.putExtra(Expertise, teamDetails.getExpertise());
    intent.putExtra(Contact, teamDetails.getContact());
    startActivityForResult(intent, DETAIL_REQUEST_CODE);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onStart() {
    super.onStart();

    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW,
            "Main Page", 
            Uri.parse("http://host/path"),

            Uri.parse("android-app://com.example.sj.dgapps3/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public void onStop() {
    super.onStop();

    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, 
            "Main Page", 
    Uri.parse("http://host/path"),

            Uri.parse("android-app://com.example.sj.dgapps3/http/host/path")
    );
    AppIndex.AppIndexApi.end(client, viewAction);
    client.disconnect();
}


class nameArrayAdapter extends ArrayAdapter<TeamDetails> {

    Context context;
    List<TeamDetails> objects;

    public nameArrayAdapter(Context context, int resource, List<TeamDetails> objects) {
        super(context, resource, objects);

        this.context = context;
        this.objects = objects;
    }

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

        TeamDetails teamDetails = objects.get(position);

        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.list, null);

        TextView tv = (TextView) view.findViewById(R.id.name);
        tv.setText(teamDetails.getName());

        ImageView iv = (ImageView) view.findViewById(R.id.empPic);
        int res = context.getResources().getIdentifier(teamDetails.getImage(), "drawable", context.getPackageName()
        );
        iv.setImageResource(res);

        return view;
    }

}

Here is the error log

    E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sj.dgapps3, PID: 1641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sj.dgapps3/com.example.sj.dgapps3.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
at android.widget.ListView.setAdapter(ListView.java:491)
at com.example.sj.dgapps3.MainActivity.onCreate(MainActivity.java:104)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Here is my Data Source class

    package DgApps3.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.sj.dgapps3.TeamDetails;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SJ on 4/14/2016.
 */
public class EmployeeDataSource {

    public static final String LOGTAG = "EMPLOYEES";

    SQLiteOpenHelper dbhelper;
    SQLiteDatabase database;

    private static final String[] allColumns = {
            DgApps3DBOpenHelper.COLUMN_ID,
            DgApps3DBOpenHelper.COLUMN_NAME,
            DgApps3DBOpenHelper.COLUMN_POSITION,
            DgApps3DBOpenHelper.COLUMN_PIC,
            DgApps3DBOpenHelper.COLUMN_EXPERTISE,
            DgApps3DBOpenHelper.COLUMN_QUALIFICATION,
            DgApps3DBOpenHelper.COLUMN_CONTACT
    };

    public EmployeeDataSource(Context context) {
        dbhelper = new DgApps3DBOpenHelper(context);
        //database = dbhelper.getWritableDatabase();
    }

    public void open() {
        Log.i(LOGTAG, "Database opened");
        database = dbhelper.getWritableDatabase();
    }

    public void close() {
        Log.i(LOGTAG, "Database closed");
        dbhelper.close();
    }

    public TeamDetails create(TeamDetails teamDetails) {
        ContentValues values = new ContentValues();
        values.put(DgApps3DBOpenHelper.COLUMN_NAME, teamDetails.getName());
        values.put(DgApps3DBOpenHelper.COLUMN_POSITION, teamDetails.getPosition());
        values.put(DgApps3DBOpenHelper.COLUMN_PIC, teamDetails.getImage());
        values.put(DgApps3DBOpenHelper.COLUMN_QUALIFICATION, teamDetails.getQualities());
        values.put(DgApps3DBOpenHelper.COLUMN_EXPERTISE, teamDetails.getExpertise());
        values.put(DgApps3DBOpenHelper.COLUMN_CONTACT, teamDetails.getContact());
        long insertid = database.insert(DgApps3DBOpenHelper.TABLE_EMPLOYEES, null, values);
        teamDetails.setId(insertid);
        return teamDetails;
    }

    public List<TeamDetails> findAll() {
        List<TeamDetails> teamDetails = new ArrayList<TeamDetails>();

        Cursor cursor = database.query(DgApps3DBOpenHelper.TABLE_EMPLOYEES, allColumns,
                null, null, null, null, null);

        Log.i(LOGTAG, "Returned" + cursor.getCount() + " rows ");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                TeamDetails teamDetail = new TeamDetails();
                teamDetail.setId(cursor.getLong(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_ID)));
                teamDetail.setName(cursor.getString(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_NAME)));
                teamDetail.setPosition(cursor.getString(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_POSITION)));
                teamDetail.setImage(cursor.getString(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_PIC)));
                teamDetail.setQualities(cursor.getString(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_QUALIFICATION)));
                teamDetail.setExpertise(cursor.getString(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_EXPERTISE)));
                teamDetail.setContact(cursor.getDouble(cursor.getColumnIndex(DgApps3DBOpenHelper.COLUMN_CONTACT)));
                teamDetails.add(teamDetail);
            }

        }
        return teamDetails;
    }
}
SajaWal NaWaz
  • 115
  • 1
  • 3
  • 13

1 Answers1

0

If you read the stacktrace close enough, you'll see the error occurs when calling the size method on a List. You might say, you never call the size method. True, but Android does...

Look at this code

protected List<TeamDetails> data;

Do you ever initialize that list? No, so it's null. So, how do you expect this to work?

ArrayAdapter<TeamDetails> courseArrayAdapter =
        new nameArrayAdapter(this, 0, data);

It won't, thus the error. To fix it, use the proper list in the Adapter, or initialize that one before putting it into and adapter

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I have initialize it already, but the problem is on this line of code listView.setAdapter(courseArrayAdapter); If i comment this, the error is gone so does my list. – SajaWal NaWaz Apr 20 '16 at 07:47
  • Yeah, your problem is on that line because the `data` variable is null inside the adapter. And you won't get an error telling you that until you run that line. If you changed your code, please edit your question and the error to reflect those changes. – OneCricketeer Apr 20 '16 at 08:13
  • It's resolved now, but now the next issue is image can't be passed in the list. – SajaWal NaWaz Apr 20 '16 at 09:42
  • Not sure what you mean by that, but please post a new question for new problems – OneCricketeer Apr 20 '16 at 09:44