如何获取并显示数组的长度?

时间:2016-06-29 17:21:36

标签: java android arrays android-asynctask

我想为我的应用创建一个文件夹。为此,需要在运行时检查权限。因此,当用户接受请求时,我正在创建文件夹并使用目录中的文件数初始化listFile数组。

我还有一个asyncTask来获取事件。所以我在asyncTask的onPostExecute方法中创建主列表。

在这个主列表中,我想显示listFile数组的长度。但是它因空指针异常而崩溃。

MainActivity:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,GetEventsAsyncTask.GetEvents {

    private RecyclerView recyclerView;
    private MainListAdapter mAdapter;
    private List<MainList> mainLists = new ArrayList<>();


    String folder_main = "MeaVita";
    File dir = new File(Environment.getExternalStorageDirectory(),folder_main);

    File[] listFile;
    public int REQUEST_CODE_ASK_PERMISSIONS = 11;
    public boolean permissionsAccepted;
    private String userUsername;

    public int PERMISSIONS_WRITE_EXTERNAL_STORAGE =10;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        sharedpreferences = getSharedPreferences("username",Context.MODE_PRIVATE);

        userUsername = sharedpreferences.getString("UserUsername","No name defined");

        GetEventsAsyncTask getEventsAsyncTask = new GetEventsAsyncTask(this,MainActivity.this,eventArrayList);
        getEventsAsyncTask.execute(userUsername);

        parent = (AppBarLayout) findViewById(R.id.view3);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        eventArrayList = new ArrayList<>();

        checkFilePermissions();

        recyclerView.setAdapter(new MainListAdapter(mainLists, new MainListAdapter.OnItemClickListener() {
            @Override public void onItemClick(MainList item) {

                if(item.getTitle().equals("Plan Event")) {
                    startActivity(new Intent(MainActivity.this, PlanEventActivity.class));
                }
                if(item.getTitle().equals("Events")) {
                    startActivity(new Intent(MainActivity.this, EventsListActivity.class));
                }
                if(item.getTitle().equals("Photos")) {
                  //  checkFilePermissions();

                    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

                    permissionsAccepted = sharedpreferences.getBoolean("permission",false);

                    if(dir.exists()) {

                        if (permissionsAccepted) {


                            if (listFile.length == 0) {


                                showAlert("No Images");

                            } else {

                                new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
                            }

                      }
                    }
                    else {

                        showAlert("No Folder");
                    }

                }
                if(item.getTitle().equals("Reminders")) {
                    startActivity(new Intent(MainActivity.this, RemindersActivity.class));
                }
                if(item.getTitle().equals("Chat")) {

                }
                if(item.getTitle().equals("Notes")) {
                    startActivity(new Intent(MainActivity.this, NotesActivity.class));
                }
                if(item.getTitle().equals("Notifications")) {
                    startActivity(new Intent(MainActivity.this, NotificationsActivity.class));
                }
                if(item.getTitle().equals("Profile")) {
                    startActivity(new Intent(MainActivity.this, ProfileActivity.class));
                }
            }
        }));

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());


    }

    public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {

        private MediaScannerConnection mMs;
        private File mFile;

        public SingleMediaScanner(Context context, File f) {
            mFile = f;
            mMs = new MediaScannerConnection(context, this);
            mMs.connect();
        }

        public void onMediaScannerConnected() {
            mMs.scanFile(mFile.getAbsolutePath(), null);
        }

        public void onScanCompleted(String path, Uri uri) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(uri);
            startActivity(intent);
            mMs.disconnect();
        }

    }

    private void checkFilePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteExternalStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (REQUEST_CODE_ASK_PERMISSIONS == 11) {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                    if (!dir.exists()) {
                        dir.mkdirs();
                        permissionsAccepted = true;
                    }

                   listFile = dir.listFiles();


                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putBoolean("permission",permissionsAccepted);
                    editor.apply();


                    if (listFile.length == 0) {
                        Toast.makeText(MainActivity.this, "The folder is empty.", Toast.LENGTH_SHORT).show();
                    }

                    else {

                        new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this, "Request Denied", Toast.LENGTH_SHORT).show();

                }


            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private void prepareData() {



        MainList mainList = new MainList("Plan Event","", R.drawable.plan);
        mainLists.add(mainList);

        mainList = new MainList("Events",String.valueOf(eventArrayList.size()), R.drawable.events);
        mainLists.add(mainList);

        mainList = new MainList("Photos",String.valueOf(listFile.length), R.drawable.phone);
        mainLists.add(mainList);

        mainList = new MainList("Reminders","20", R.drawable.remind);
        mainLists.add(mainList);

        mainList = new MainList("Chat","2", R.drawable.chat);
        mainLists.add(mainList);

        mainList = new MainList("Notes","2", R.drawable.notes);
        mainLists.add(mainList);

        mainList = new MainList("Notifications","20", R.drawable.remind);
        mainLists.add(mainList);

        mainList = new MainList("Profile","50%", R.drawable.user);
        mainLists.add(mainList);

    }
    public void showAlert(String alert) {

        Snackbar snackbar = Snackbar.make(parent, alert, Snackbar.LENGTH_LONG);
        snackbar.show();
    }
    @Override
    public void doPostExecute(ArrayList<Event> response) {

        eventArrayList = response;
        listFile = dir.listFiles();
        prepareData();

    }
}

记录:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.siddhi.meavita, PID: 30194
java.lang.NullPointerException: Attempt to get length of null array
    at com.example.siddhi.meavita.Activities.MainActivity.prepareData(MainActivity.java:341)
    at com.example.siddhi.meavita.Activities.MainActivity.doPostExecute(MainActivity.java:370)
    at com.example.siddhi.meavita.AsyncTaskClasses.GetEventsAsyncTask.onPostExecute(GetEventsAsyncTask.java:107)
    at com.example.siddhi.meavita.AsyncTaskClasses.GetEventsAsyncTask.onPostExecute(GetEventsAsyncTask.java:28)
    at android.os.AsyncTask.finish(AsyncTask.java:651)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)

如何以及何时初始化listFile数组以及何时调用prepareData方法?

请帮忙。坚持这个,非常新的。 谢谢。

3 个答案:

答案 0 :(得分:0)

您只是忘记将eventArrayList实现为类变量,当您尝试调用null时,您也试图将其称为eventArrayList.size()异常p>

答案 1 :(得分:0)

您正在使用方法File.listFiles()从目录中获取文件列表。

listFile可以为null

但是,根据Docs,此方法可以返回null

  

public File [] listFiles()   
...
  如果此抽象路径名不表示目录,或者发生I / O错误,则返回null。

dir.listFile()可能会在以下条件中返回null

  1. 如果dir没有反映目录(dir可以指向某个文件,例如..那不是你的情况)
  2. 任何I / O错误(如读取目录内容时的权限或任何其他失败。
  3. 正如您所看到的,您无法确保listFile始终与null不同... ...它可以是偶数的空。因此,在读取其属性/值之前,首先应检查listFile是否为null。

    null保护

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        listFile = dir.listFiles();
        ...
        if (listFile == null || listFile.length == 0) {
            Toast.makeText(MainActivity.this, "The folder is empty.", Toast.LENGTH_SHORT).show();
        } else {
            new MainActivity.SingleMediaScanner(MainActivity.this, listFile[0]);
        }
        ...
    }
    

    private void prepareData() {
        ...
        if(listFile != null && listFile.length >= 0)
            mainList = new MainList("Photos",String.valueOf(listFile.length), R.drawable.phone);
        else
            mainList = new MainList("Photos", "0", R.drawable.phone);
    
        mainLists.add(mainList);
        ...
    }
    

答案 2 :(得分:0)

您试图获取长度而不指定文件大小或初始化listFile对象。您需要指定listFile长度。喜欢

File[] listFile = new File[10];

或者你可以在listFile对象中传递任何你需要的数组。然后得到长度。