Android - Select max in contentProvider

前端 未结 3 1846
滥情空心
滥情空心 2021-01-13 13:58

I try to run this query on my custom contentprovider.

cursor = activity.getContentResolver().query(
                GoalDescriptor.CONTENT_URI,
                     


        
相关标签:
3条回答
  • 2021-01-13 14:08

    Unfortunately nEx's answer (using "AS" to provide an alias for the column) only works with providers who don't set the strictProjectionMap flag in their SQLiteQueryBuilder. E.g. the contacts provider sets this flag, so if you try the AS approach you'll still get the "Invalid column" error.

    And if someone can tell me how specifying an aggregate function like MAX in the selection is supposed to work I'd be very grateful. If I try it I just get a "misuse of aggregate function" exception, which is exactly what I'd expect from trying to put an aggregate function in a WHERE clause. I know you can put a subquery in the WHERE clause, but that assumes that you know the actual table structure, and that it will never change on any given device or OS level, which I wouldn't want to bet on (after all, that's why are using the provider interface in the first place, to abstract from the underlying data store).

    So...I don't know of any way to do this for providers who set the strictProjectionMap flag other than to sort DESC by the desired field, and preferably LIMIT to 1 row if the provider supports it (or if you're willing to take a chance on breaking something by including the LIMIT in the sort string). I would be very happy if someone knows other approaches for these cases!

    0 讨论(0)
  • 2021-01-13 14:20

    In my case the answer of nEx actually worked, but I forgot to also add "max_"+COLUMN_NAME within the getColumnIndexByName() method of the cursor.

    After I figured out this had also to be changed, it finally worked!

    0 讨论(0)
  • 2021-01-13 14:29

    You are sending the max(priority) as the projection, send it in as the selection and it should work.

    See this question: Android: Get highest value in column

    Edit:

    It appears this should work:

    cursor = activity.getContentResolver().query(
             GoalDescriptor.CONTENT_URI,
              new String[] {"MAX(priority) AS max_priority"}, null,
             null, null);
    
    0 讨论(0)
提交回复
热议问题