2016-12-31 3 views
0

EDIT Frohes neues Jahr! Um genau zu sein, habe ich eine einfache Musik-App in Android Studio erstellt, die MP3-Dateien aus meinem internen Speicher liest. Alles gut, bis ich beschließe, ein zufälliges Bild auf jeden einzelnen Track auf der Liste zu setzen. (Vor dem Namen des Songs möchte ich ein Bild anzeigen.) Wenn ich ein einzelnes Bild in 'src' unter ImageView anwähle, funktioniert es und erscheint allen Songs. Ich werde einen Teil meiner Code Atach unter: Hauptaktivität:Meine App gestoppt jedes Mal, wenn ich es laden

package com.alg.amzar.spectrum; 

import android.content.ContentResolver; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.ImageView; 
import android.widget.ListView; 

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.Random; 


public class MainActivity extends AppCompatActivity { 

static { 
    System.loadLibrary("native-lib"); 
} 
private ArrayList<Song> songList; 
private ListView songView; 


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

    schimbare(); 

    songView = (ListView)findViewById(R.id.song_list); 
    songList = new ArrayList<Song>(); 

    getSongList(); 

    Collections.sort(songList, new Comparator<Song>(){ 
     public int compare(Song a, Song b){ 
      return a.getTitle().compareTo(b.getTitle()); 
     } 
    }); 

    SongAdapter songAdt = new SongAdapter(this, songList); 
    songView.setAdapter(songAdt); 


} 

public void schimbare() { 
    int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2}; 

    ImageView image = (ImageView) findViewById(R.id.imagine); 

    Random ran=new Random(); 
    int i=ran.nextInt(photos.length); 
    image.setImageResource(photos[i]); 
} 

public void getSongList() { 
    ContentResolver musicResolver = getContentResolver(); 
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null); 

    if(musicCursor!=null && musicCursor.moveToFirst()){ 
     //get columns 
     int titleColumn = musicCursor.getColumnIndex 
       (android.provider.MediaStore.Audio.Media.TITLE); 
     int idColumn = musicCursor.getColumnIndex 
       (android.provider.MediaStore.Audio.Media._ID); 
     //add songs to list 
     do { 
      long thisId = musicCursor.getLong(idColumn); 
      String thisTitle = musicCursor.getString(titleColumn); 
      songList.add(new Song(thisId, thisTitle)); 
     } 
     while (musicCursor.moveToNext()); 
    } 
} 

public native String stringFromJNI(); 
} 

Aktivität Haupt .xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:background="#FF330000" 
tools:context=".MainActivity" > 

<ListView 
    android:id="@+id/song_list" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
</ListView> 

</LinearLayout> 

Song.xml:

<LinearLayout 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="fill_parent" 
android:layout_height="wrap_content" 
android:onClick="songPicked" 
android:orientation="vertical" 
android:padding="5dp" > 

<ImageView 
    android:layout_width="70dp" 
    android:id="@+id/imagine" 
    android:layout_height="50dp" /> 

<TextView 
    android:id="@+id/song_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textColor="#FFFFFF99" 
    android:textSize="15sp" 
    android:textStyle="bold" 
    android:layout_marginBottom="20dp" 
    android:layout_marginLeft="75dp" 
    android:layout_marginTop="-42dp"/> 


</LinearLayout> 

Neben diesem, ich habe 2 mehr Java-Klassen. Ich denke, das Problem hier ist, aber idk, was falsch ist:

public void schimbare() { 
    int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2}; 

    ImageView image = (ImageView) findViewById(R.id.imagine); 

    Random ran=new Random(); 
    int i=ran.nextInt(photos.length); 
    image.setImageResource(photos[i]); 
} 

Eine andere fragen, von mir ist, was ‚veraltet‘ ist, wenn I .getDrawable verwenden. Vielen Dank im Voraus!

Logcat:

ime: FATAL EXCEPTION: main 
                    Process: com.alg.amzar.spectrum, PID: 28677 
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alg.amzar.spectrum/com.alg.amzar.spectrum.MainActivity}: java.lang.NullPointerException 
                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2381) 
                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2433) 
                     at android.app.ActivityThread.access$800(ActivityThread.java:155) 
                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346) 
                     at android.os.Handler.dispatchMessage(Handler.java:110) 
                     at android.os.Looper.loop(Looper.java:193) 
                     at android.app.ActivityThread.main(ActivityThread.java:5341) 
                     at java.lang.reflect.Method.invokeNative(Native Method) 
                     at java.lang.reflect.Method.invoke(Method.java:515) 
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:830) 
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:646) 
                     at dalvik.system.NativeStart.main(Native Method) 
                    Caused by: java.lang.NullPointerException 
                     at com.alg.amzar.spectrum.MainActivity.schimbare(MainActivity.java:57) 
                     at com.alg.amzar.spectrum.MainActivity.onCreate(MainActivity.java:31) 
                     at android.app.Activity.performCreate(Activity.java:5343) 
                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088) 
                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335) 
                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2433)  
                     at android.app.ActivityThread.access$800(ActivityThread.java:155)  
                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)  
                     at android.os.Handler.dispatchMessage(Handler.java:110)  
                     at android.os.Looper.loop(Looper.java:193)  
                     at android.app.ActivityThread.main(ActivityThread.java:5341)  
                     at java.lang.reflect.Method.invokeNative(Native Method)  
                     at java.lang.reflect.Method.invoke(Method.java:515)  
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:830)  
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:646)  
                     at dalvik.system.NativeStart.main(Native Method)  

Mein Handy Android-Version: 4.4.2 (API 19) Ziel SDK Version: "19" MinSDK Version: "14"

SongAdapter.java:

package com.alg.amzar.spectrum; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

import java.util.ArrayList; 



public class SongAdapter extends BaseAdapter { 

private ArrayList<Song> songs; 
private LayoutInflater songInf; 

public SongAdapter(Context c, ArrayList<Song> theSongs) { 
    songs = theSongs; 
    songInf = LayoutInflater.from(c); 
} 

@Override 
public int getCount() { 
    return songs.size(); 
} 

@Override 
public Object getItem(int arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public long getItemId(int arg0) { 
    // TODO Auto-generated method stub 
    return 0; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    //map to song layout 
    LinearLayout songLay = (LinearLayout)songInf.inflate 
      (R.layout.song, parent, false); 
    //get title and artist views 
    TextView songView = (TextView)songLay.findViewById(R.id.song_title); 
    //get song using position 
    Song currSong = songs.get(position); 
    //get title and artist strings 
    songView.setText(currSong.getTitle()); 
    //set position as tag 
    songLay.setTag(position); 
    return songLay; 
} 

} 
+0

Bitte beachten Sie auch Android-Version Ihres Telefons geben Sie mit und gezielte Version Ihrer Anwendung –

+0

sind Testen Sie sollten Ihre Anwendung debuggen, gehen Zeile für Zeile und sehen, wo Problem. – avinesh

Antwort

2

In Ihrem Fall gibt findViewById(R.id.imagine) NULL zurück, weil es nicht im Layout 'activity_main' existiert, das Sie in setContentView() angegeben haben. findViewById() gibt NULL zurück, wenn die Ansicht im aktuellen Layout nicht vorhanden ist. R.id.imagine existiert im Layout song.xml.

Ich denke, Sie versuchen, die ListView mit Layout "Song" aufzublasen. Erst nach dem Aufblasen können Sie findViewById und setImageResource anrufen. Sie können es in der Klasse SongAdapter für jedes Element in ListView nach dem Aufblasen tun.

Ein anderer Vorschlag, anstatt zufällige Bilder zu verwenden, können Sie Album Art eines Liedes von der MediaMetadataRetriever Klasse erhalten. Sie können die Android-Dokumentation dafür verweisen.Aber Sie müssen diese Ausnahme vorher lösen.

Kommentieren/Löschen Funktion schimbare() in onCreate und bearbeiten SongAdapter wie folgt.

package com.alg.amzar.spectrum; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

import java.util.ArrayList; 



public class SongAdapter extends BaseAdapter { 

private ArrayList<Song> songs; 
private LayoutInflater songInf; 

int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2}; 
Random ran=new Random(); 
// CHECK THIS: 
public SongAdapter(Context c, ArrayList<Song> theSongs) { 
    songs = theSongs; 
    // CHECK THIS: 
    songInf = (LayoutInflater)c. 
       getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { 
    return songs.size(); 
} 

@Override 
public Object getItem(int arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public long getItemId(int arg0) { 
    // TODO Auto-generated method stub 
    return 0; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    //map to song layout 
    LinearLayout songLay = (LinearLayout)songInf.inflate 
      (R.layout.song, null); 
    //get title and artist views 
    TextView songView = (TextView)songLay.findViewById(R.id.song_title); 
    // CHECK THIS: 
    ImageView img = (ImageView)songLay.findViewById(R.id.imagine); 
    //get song using position 
    Song currSong = songs.get(position); 
    //get title and artist strings 
    songView.setText(currSong.getTitle()); 
    // CHECK THIS: 
    int i=ran.nextInt(photos.length); 
    img.setImageResource(photos[i]); 
    //set position as tag 
    songLay.setTag(position); 
    return songLay; 
} 

} 
+0

Ich kann nicht richtig verstehen, was in diesem Fall zu tun ist. Zuerst wollte ich mit MediaMetadatRetriever arbeiten, aber das scheint mir etwas kompliziert zu sein. –

+0

Sie müssen 'setImageResourse' in der SongAdapter-Klasse aufrufen. Ich werde Ihnen einen Link zur Verfügung stellen: [link] (https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html). Bitte versuchen Sie es. – 123rgt

+0

Sie müssen die aktuelle Ausnahme beheben, bevor Sie MediaMetadataRetriever ausprobieren. Es ist keine Lösung für die aktuelle Ausnahme. – 123rgt

0

Veraltet bedeuten, dass Google diese Methode nicht mehr unterstützt, sie sagen Ihnen, es gibt neue Methode, die Sie verwenden sollten. Die veraltete Methode funktioniert jetzt gut. Aber eines Tages (vielleicht morgen, vielleicht 3 Jahre später) wird es nicht mehr funktionieren.

über den Fehler, laden Sie bitte das Protokoll hoch.

Der Fehler ist in Zeile 57:

                 at com.alg.amzar.spectrum.MainActivity.schimbare(MainActivity.java:57)

Ich bin nicht sicher, wo die Leitung 57 ist, aber Sie können es in Ihrem Code überprüfen, wenn Sie kann immer noch nicht die Ursache dann finden aktualisieren uns, welche Linie 57

public void schimbare() { 
 
    int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2}; 
 

 
    ImageView image = (ImageView) findViewById(R.id.imagine); 
 

 
    Random ran=new Random(); 
 

 
    // CHANGE photos.length to photos.length-1 
 
    int i=ran.nextInt(photos.length); 
 

 
    //ADD this 2 line of code below, then you can check in your Log if the problem is with the view (the view is null), or if the photos position is null. 
 

 
    Log.d("bug_tag",String.valueOf(photos[i])); 
 
    Log.d("bug_tag",String.valueOf(image.getId())); 
 

 

 
    image.setImageResource(photos[i]); 
 
}

+0

Ich habe das Protokoll hinzugefügt –

+0

Ich kann es immer noch nicht herausfinden. Das Problem ist, wo ich zunächst dachte. Zeile 57: image.setImageResource (Fotos [i]); –

+0

Überprüfen Sie die Kommentare in dem Code, den ich hinzugefügt habe. –

Verwandte Themen