Search code examples
javaandroidandroid-studioandroid-listview

How can convert ListActivity to AppCompatActivity


I want to change my activity parent from ListActivity to AppCompatActivity, because I need to use check permission Granted and it's need AppCompat, but my activity is ListView. I try this action, but not received a good result :(

This is my source code (Ever has ... is for no added code):

public class RingtoneSelectActivity extends ListActivity {
...
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
            mShowAll = false;

            String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
                showFinalAlert(getResources().getText(R.string.err_sdcard_readonly));
                return;
            }
            if (status.equals(Environment.MEDIA_SHARED)) {
                showFinalAlert(getResources().getText(R.string.err_sdcard_shared));
                return;
            }
            if (!status.equals(Environment.MEDIA_MOUNTED)) {
                showFinalAlert(getResources().getText(R.string.err_no_sdcard));
                return;
            }

            Intent intent = getIntent();
            mWasGetContentIntent = intent.getAction().equals(
                    Intent.ACTION_GET_CONTENT);

            // Inflate our UI from its XML layout description.
            setContentView(R.layout.media_select);


            SplashHandler mHandler = new SplashHandler();


            Message msg = new Message();
            //Assign a unique code to the message.
            //Later, this code will be used to identify the message in Handler class.
            msg.what = 0;
            // Send the message with a delay of 3 seconds(3000 = 3 sec).
            mHandler.sendMessageDelayed(msg, 10000);

            try {
                mAdapter = new SimpleCursorAdapter(
                        this,
                        // Use a template that displays a text view
                        R.layout.media_select_row,
                        // Give the cursor to the list adatper
                        createCursor(""),
                        // Map from database columns...
                        new String[]{
                                MediaStore.Audio.Media.ARTIST,
                                MediaStore.Audio.Media.ALBUM,
                                MediaStore.Audio.Media.TITLE,
                                MediaStore.Audio.Media._ID,
                                MediaStore.Audio.Media._ID},
                        // To widget ids in the row layout...
                        new int[]{
                                R.id.row_artist,
                                R.id.row_album,
                                R.id.row_title,
                                R.id.row_icon,
                                R.id.row_options_button});

                setListAdapter(mAdapter);

                getListView().setItemsCanFocus(true);

                // Normal click - open the editor
                getListView().setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView parent,
                                            View view,
                                            int position,
                                            long id) {
                        startRingdroidEditor();
                    }
                });

            } catch (SecurityException e) {
                // No permission to retrieve audio?
                Log.e("Ringtone", e.toString());

                // todo error 1
            } catch (IllegalArgumentException e) {
                // No permission to retrieve audio?
                Log.e("Ringtone", e.toString());

                // todo error 2
            }

            mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                public boolean setViewValue(View view,
                                            Cursor cursor,
                                            int columnIndex) {
                    if (view.getId() == R.id.row_options_button) {
                        // Get the arrow image view and set the onClickListener to open the context menu.
                        ImageView iv = (ImageView) view;
                        iv.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                openContextMenu(v);
                            }
                        });
                        return true;
                    } else if (view.getId() == R.id.row_icon) {
                        setSoundIconFromCursor((ImageView) view, cursor);
                        return true;
                    }

                    return false;
                }
            });

            // Long-press opens a context menu
            registerForContextMenu(getListView());

        }
    }
...
}

I changed to this:

public class RingtoneSelectActivity extends AppCompatActivity {

But I received some errors in this lines:

...
                setListAdapter(mAdapter);

                getListView().setItemsCanFocus(true);

                getListView().setOnItemClickListener(new OnItemClickListener() { ... });
...
            registerForContextMenu(getListView());

My errors:

  • Cannot resolve method 'setListAdapter(android.widget.SimpleCursorAdapter)
  • Cannot resolve method 'getListView()'

How can I fix that errors?

[Edit]

My LogCat:

E/ACRA: ACRA caught a NullPointerException for ir.ari.mp3cutter
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SimpleCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
        at ir.ari.mp3cutter.RingtoneSelectActivity.refreshListView(RingtoneSelectActivity.java:621)
        at ir.ari.mp3cutter.RingtoneSelectActivity.onOptionsItemSelected(RingtoneSelectActivity.java:314)
        at android.app.Activity.onMenuItemSelected(Activity.java:2908)
        at com.android.internal.policy.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1151)
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
        at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
        at com.android.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:200)
        at android.widget.AdapterView.performItemClick(AdapterView.java:310)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
        at android.widget.AbsListView$3.run(AbsListView.java:3879)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        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)

Line 304 to 319:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_about:
            RingtoneEditActivity.onAbout(this);
            return true;
        case R.id.action_record:
            onRecord();
            return true;
        case R.id.action_show_all_audio:
            mShowAll = true;
            refreshListView();
            return true;
        default:
            return false;
        }
    }

And line 619 to 622:

    private void refreshListView() {
        String filterStr = mFilter.getQuery().toString();
        mAdapter.changeCursor(createCursor(filterStr));
    }

[notice: I'm sorry for my bad talking, because I not learned English as good :)


Solution

  • So don't change super class, Just check for ungranted permissions with ContextCompat.checkSelfPermission() and then request Permission by ActivityCompat.requestPermissions() and get the result in:

    @Override
    public void onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
        ) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }