0

I have a table having two columns - name and symbol. all i want is to get the symbol corresponding to the name. I use this method. It's kind of returning nothing. Please check this out.

public String getSymbol(String name) {
    String Symbol = "";
    String[] columns = new String[] { "name", "symbol" };
    Cursor c = getReadableDatabase().query(DATABASE_TABLE_NAME, columns, null,
            null, null, null, null);

    int iName = c.getColumnIndex("name");
    int iSymbol = c.getColumnIndex("symbol");

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        if (c.getString(iName) == name) {
            Symbol = Symbol + c.getString(iSymbol);
        }

    }
    return Symbol;

}

2 Answers 2

1

Try this function.

public String getSymbol(String name)
    {
        try
        {
          String Symbol = "";
          Cursor c = db.query(DATABASE_TABLE_NAME, columns, "name = ?" , new String[] {name}, null, null, null);
          if(c.getCount != 0)
          {
               c.moveToFirst();
               Symbol = String.valueOf(c.getString(c.getColumnIndex("symbol"))); 
               c.close();
               return Symbol;
          }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! the code works fine except for this line Symbol = String.valueOf(c.getColumnIndex("symbol")); Actually it should be Symbol = String.valueOf(c.getString(c.getColumnIndex("symbol"))); otherwise it will return the index "1".
Could you please explain what went wrong in my code. Just to figure out things.
You are trying to get all the data and then compare with all data. Its not good idea
0

Instead of using c.getString(iName) == name while comparing, use c.getString(iName).equalsIgnoreCase(name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.