-3

I'm new in Android Studio programming and I coded my first (bigger) app. The app works fine when I start it in the debugger. But when I connect my tablet and try to start my app there I immediately get the error

08-04 14:40:27.752 30433-30433/com.applications.ars.mynotizenundactivityapp E/AndroidRuntime: FATAL EXCEPTION: main                                                           Process: com.applications.ars.mynotizenundactivityapp, PID: 30433
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.applications.ars.mynotizenundactivityapp/com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity}: java.lang.NullPointerException: Attempt to get length of null array                                                                   
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity.onCreate(DateiAuswahlActivity.java:96)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 

I googled the error and it seens that there is perhaps a problem with my .xml at my layout.

This is my .xml-File:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity">
    <ListView
        android:id="@+id/lv_myListView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:entries="@color/colorAccent"
        android:visibility="visible" />
</android.support.constraint.ConstraintLayout>

And this is my java-File:

package com.applications.ars.mynotizenundactivityapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;


public class DateiAuswahlActivity<T> extends AppCompatActivity {

    String my_projektverzeichnis;
    String my_projektordnername = "ars_MyOrdner";
    ArrayList my_karteikastenListe = new ArrayList();
    ArrayList my_URLKarteikastenListe = new ArrayList();
    String my_URLKarteikaesten_longString;
    String [] URLKarteikastenArray;
    ListAdapter adapter;

    ListView lv;
    int stopper = 1;
    GetURLFolderContent my_getURLFolderContent = new GetURLFolderContent();

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_dateiauswahl, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_URL_Download) {
            Toast.makeText(DateiAuswahlActivity.this, "Karteikästen werden heruntergeladen", Toast.LENGTH_LONG).show();
            try {
                my_URLKarteikaesten_longString = my_getURLFolderContent.execute("http://www.meuchelmord.net/andy/Android/listFiles.php").get();
                stopper =1;
            } catch (InterruptedException e) {
                Toast.makeText(DateiAuswahlActivity.this, "Sorry, keine Internetverbindung", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (ExecutionException e) {
                Toast.makeText(DateiAuswahlActivity.this, "Sorry, keine Internetverbindung", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            URLKarteikastenArray = my_URLKarteikaesten_longString.split("<br />");
            for (int i=0;i<URLKarteikastenArray.length-1;i++){
                my_URLKarteikastenListe.add(URLKarteikastenArray[i]);
            }


            for (int i=0;i<my_URLKarteikastenListe.size();i++){
                String my_tempurl = "http://www.meuchelmord.net/andy/Android/".concat(my_URLKarteikastenListe.get(i).toString());
                GetURLFile my_URLFile = new GetURLFile();
                my_URLFile.execute(my_tempurl,my_URLKarteikastenListe.get(i).toString());
                my_URLFile = null;
            }
            my_karteikastenListe = my_URLKarteikastenListe;
            for (int i=0;i<my_karteikastenListe.size();i++){
                my_karteikastenListe.set(i,my_karteikastenListe.get(i).toString().replace(".kartei",""));
            }
            adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
            //lv = (ListView)findViewById(R.id.lv_myListView);
            lv.setAdapter(adapter);

            stopper =1;
            return true;
        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datei_auswahl);

        my_projektverzeichnis = Environment.getExternalStorageDirectory() + "/" + my_projektordnername;
        File my_dateien_alle = new File(my_projektverzeichnis);
        File[] my_dateien_alle_Array = my_dateien_alle.listFiles();


        for(int i = 0; i<my_dateien_alle_Array.length;i++){
            if (my_dateien_alle_Array[i].getName().endsWith(".kartei") ){

                String my_tempname = my_dateien_alle_Array[i].toString().replace(".kartei","");
                String[] my_temparray = my_tempname.split("/");
                my_tempname = my_temparray[my_temparray.length-1];
                my_karteikastenListe.add(my_tempname);
            }
        }

        //List valueList = new ArrayList<String>();
        //for (int i = 0; i < 10; i++)
        //{
        //    valueList.add("value"+i);
        //}
        //ListAdapter adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
        adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
        lv = (ListView)findViewById(R.id.lv_myListView);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {


            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
                Intent intent = new Intent();
                intent.setClassName(getPackageName(), getPackageName()+".MainActivity");
                intent.putExtra("Karteikasten", lv.getAdapter().getItem(arg2).toString());
                startActivity(intent);
            }
            });
        stopper = 1;
    }
}

About my Tablet: Samsung Galaxy TAB A Android Version 7.0 Kernel-Version: 3.18.14-11316739

The configuration of my emulator where there is no problem: Android 7.0 (Google APIs) API 24

Is there anyone who can give me a tip where I can search for the problem? I have no idea...

In hope of a reply, Andy

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Andy
  • 13
  • 4
  • you are calling `.length` method on null array, try to check null before calling `.length` method – akhilesh0707 Aug 04 '17 at 13:28
  • `File my_dateien_alle = new File(my_projektverzeichnis);` I'm guessing the directory isn't created so the next line `File[] my_dateien_alle_Array = my_dateien_alle.listFiles();` is returning null – RobVoisey Aug 04 '17 at 13:28
  • You are getting null at `my_dateien_alle.listFiles()` This happens if there is an I/O error which has 2 possibilities. Either the name of the directory that you mentioned doesn't axist or you don't have access to it. Can you check if you have added below permission in Manifest Also you can modify your code as File dir = new File(Environment.getExternalStorageDirectory() + "/dirname"); if (!dir.exists()) { folder.mkdir(); } – Kapil G Aug 04 '17 at 13:33

3 Answers3

1

java.lang.NullPointerException: Attempt to get length of null array

in your for you try to use my_dateien_alle_Array.length but this ArrayList has no length because it is NULL.

rbcvl
  • 406
  • 3
  • 13
0

Looks like my_dateien_alle.listFiles() is returning null:

File[] my_dateien_alle_Array = my_dateien_alle.listFiles();

And when you are trying to get the length of the null array you hit NPE:

for (int i=0;i<my_URLKarteikastenListe.size();i++){
codaddict
  • 445,704
  • 82
  • 492
  • 529
0

File my_dateien_alle = new File(my_projektverzeichnis); I'm guessing the directory isn't created so the next line File[] my_dateien_alle_Array = my_dateien_alle.listFiles(); is returning null

You may want something like this to create your directory if it does not exist:

File dir = new File(Environment.getExternalStorageDirectory() + "/dirname");
if (!dir.exists()) {
    folder.mkdir();
}
RobVoisey
  • 1,083
  • 15
  • 24