alfian vian February 2016

error missing return statement in method

I want to get data based on a fragment of the name , but why the error with a description of the missing return statement ?

public Cursor getName (String nama){
    Cursor c = db.query(Konstanta.NAMA_TABEL, new String[]{
            Konstanta.ID_ARTIS,
            Konstanta.NAMA_ARTIS,
            Konstanta.GENDER_ARTIS_PRIA,
            Konstanta.GENDER_ARTIS_WANITA,
            Konstanta.TGLAHIR}, Konstanta.NAMA_ARTIS + "LIKE '%" + nama + "%'",
            null, null, null, null, null);
    if (c != null){
        c.moveToFirst();
        return c;
    }
}

Answers


Eran February 2016

Your method returns a result only if c is not null. It must return a result in all scenarios, i.e. even if c is null.

You can change

    if (c != null){
        c.moveToFirst();
        return c;
    }

to

    if (c != null){
        c.moveToFirst();
    }
    return c;


Sercan Ozdemir February 2016

Every method which has a return value must return the described bean. You need to return null or throw a custom exception if c is not null.

public Cursor getName (String nama){
        Cursor c = db.query(Konstanta.NAMA_TABEL, new String[]{
                Konstanta.ID_ARTIS,
                Konstanta.NAMA_ARTIS,
                Konstanta.GENDER_ARTIS_PRIA,
                Konstanta.GENDER_ARTIS_WANITA,
                Konstanta.TGLAHIR}, Konstanta.NAMA_ARTIS + "LIKE '%" + nama + "%'",
                null, null, null, null, null);
        if (c != null){
            c.moveToFirst();
            return c;
        }
        throw new IllegalStateException("c is null");
    }


kevz February 2016

add below line -

return null;

in your code block -

public Cursor getName (String nama){
    Cursor c = db.query(Konstanta.NAMA_TABEL, new String[]{
            Konstanta.ID_ARTIS,
            Konstanta.NAMA_ARTIS,
            Konstanta.GENDER_ARTIS_PRIA,
            Konstanta.GENDER_ARTIS_WANITA,
            Konstanta.TGLAHIR}, Konstanta.NAMA_ARTIS + "LIKE '%" + nama + "%'",
            null, null, null, null, null);
    if (c != null){
        c.moveToFirst();
        return c;
    }

return null;
}


Kapil Rajput February 2016

Your method must return Cursor type value but you are returning value only in a if loop

do this way :

 public Cursor getName (String nama){
 Cursor c =null;
 c = db.query(Konstanta.NAMA_TABEL, new String[]{
            Konstanta.ID_ARTIS,
            Konstanta.NAMA_ARTIS,
            Konstanta.GENDER_ARTIS_PRIA,
            Konstanta.GENDER_ARTIS_WANITA,
            Konstanta.TGLAHIR}, Konstanta.NAMA_ARTIS + "LIKE '%" + nama + "%'",
            null, null, null, null, null);
    if (c != null){
        c.moveToFirst();
        return c;
    }
   return c;
   } 

Post Status

Asked in February 2016
Viewed 3,981 times
Voted 12
Answered 4 times

Search




Leave an answer