IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

NullPointerException inexplicable sur un setImage


Sujet :

Android

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    47
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 47
    Points : 40
    Points
    40
    Par défaut NullPointerException inexplicable sur un setImage
    Bonjour,

    Je me retrouve face à un problème dont je ne comprend même pas l'origine dans mon application Android.
    Je veux récupérer une image sur internet et l'afficher dans une imageView. Rien de très compliqué. Mon xml est ainsi :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <ImageView
            android:id="@+id/player"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
     
    </LinearLayout>
    Et j'essaye donc avec l'image de faire le code suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		//view = new View(this);
    		setContentView(R.layout.xml_au_dessus);
                    String file_landscape = null;
    ImageView imView = (ImageView) findViewById(R.id.player);
    ...
    }
    Plus loin dans le code lors de l'utilisation de imView

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
                                     * Chargement image landscape.
                                     */
    				if (file_landscape!=null){
    					if (!file_landscape.isEmpty()){
    						try {
    							URL newUrl2 = new URL(file_landscape);
    							Log.e(TAG, "file-landscape URL : "+file_landscape);
    							InputStream inputStream = (InputStream)newUrl2.getContent();
    							Drawable drawable = Drawable.createFromStream(inputStream, null);
    							imView.setImageDrawable(drawable);
    						} catch (MalformedURLException e1) {
    							// TODO Auto-generated catch block
    							e1.printStackTrace();
    						} catch (IOException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    				}
    Le problème est que cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    imView.setImageDrawable(drawable);
    me retourne ceci au niveau du log

    06-14 13:59:33.414: W/dalvikvm(1048): threadid=15: thread exiting with uncaught exception (group=0x40a71930)
    06-14 13:59:33.434: E/AndroidRuntime(1048): FATAL EXCEPTION: Thread-105
    06-14 13:59:33.434: E/AndroidRuntime(1048): java.lang.NullPointerException
    06-14 13:59:33.434: E/AndroidRuntime(1048): at com.myappli.ui.MyActivity$2.run(MyActivity.java:136)

    J'ai beau parcourir des pages et des pages depuis Google, testé plusieurs méthodes de téléchargement de fichier, j'ai essayé avec une Bitmap ou une Drawable, je ne comprend pas pourquoi cette méthode me retourne cette erreur alors que normalement sur la doc Android:
    public void setImageDrawable (Drawable drawable)
    Voilà merci encore de votre aide par avance, je suis en train de voir d'autres pistes de résolution.

    PS : mon Url n'est pas nulle j'ai vérifié.

  2. #2
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Peut etre que l'input-stream est null ?

    On pourrait avoir le code complet ? en particulier le runnable ?
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    47
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 47
    Points : 40
    Points
    40
    Par défaut
    Voilà le code complet de ma classe:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    public class InterstitielActivity extends MyAppliActivity {
    	private JacksController jController;
    	private String format;
    	private String file;
    	private String file_landscape;
    	private String click_stat1;
    	private String click_stat2;
    	private String click_url;
    	private String open_type;
    	private String duree;
    	private String pixel_url;
    	private View view;
    	private ImageView imView;
    	private static final String TAG = LogUtils.getLogTag(InterstitielActivity.class);
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		//view = new View(this);
    		setContentView(R.layout.interstitiel);
    		jController =  new JacksController();
    		format = null;
    		file = null;
    		file_landscape = null;
    		click_stat1 = null;
    		click_stat2 = null;
    		click_url = null;
    		open_type = null;
    		duree = null;
    		pixel_url = null;
    		ImageView imView = (ImageView) findViewById(R.id.my_image);
    		gettingJson();
    		imView.setOnClickListener(new OnClickListener() {
    			public void onClick(View v)
    			{
    				if (click_stat2!=null){
    					if (!click_stat2.isEmpty()){
    						try {
    							URL newUrl5 = new URL(click_stat2);
    							new CallURL().execute(newUrl5);
    						} catch (MalformedURLException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    				}
     
    				if (click_url!=null){
    					if (!click_url.isEmpty()){
    						Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(click_url));
    						startActivity(browserIntent);
    					}
    				}
    			}
     
    		});
     
    	}
     
    	private void gettingJson() {
    		 Thread checkUpdate = new Thread() {
    			public void run() {
    				JacksController.init();
    				if (JacksController.findAll()!=null){
    					Map<String,Map<String,String>> j = JacksController.findAll();
    						format = j.get("pub").get("format");
    						file = j.get("pub").get("file");
    						file_landscape = j.get("pub").get("file-landscape");
    						click_stat1 = j.get("pub").get("click-stat1");
    						click_stat2 = j.get("pub").get("click-stat2");
    						click_url = j.get("pub").get("click-url");
    						open_type = j.get("pub").get("open-type");
    						duree = j.get("pub").get("duree");
    						pixel_url = j.get("pub").get("pixel-url");
     
    				}
     
    				/**
                                     * click_stat1 call URL
                                     */
    				if (click_stat1!=null){
    					if (!click_stat1.isEmpty()){
    						try {
    							URL newUrl = new URL(click_stat1);
    							new CallURL().execute(newUrl);
    						} catch (MalformedURLException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
     
    				}
     
    				/**
                                     * Chargement image landscape.
                                     */
    				if (file_landscape!=null){
    					if (!file_landscape.isEmpty()){
    						try {
    							URL newUrl2 = new URL(file_landscape);
    							Log.e(TAG, "file-landscape URL : "+file_landscape);
    							InputStream inputStream = (InputStream)newUrl2.getContent();
    							Drawable drawable = Drawable.createFromStream(inputStream, null);
    							imView.setImageDrawable(drawable);
    						} catch (MalformedURLException e1) {
    							// TODO Auto-generated catch block
    							e1.printStackTrace();
    						} catch (IOException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    				}
     
    				/**
                                     * pixel_url call URL
                                     */
    				if (pixel_url!=null){
    					if (!pixel_url.isEmpty()){
    						try {
    							URL newUrl3 = new URL(pixel_url);
    							new CallURL().execute(newUrl3);
    						} catch (MalformedURLException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    				}
     
    				runOnUiThread(new Runnable() {
    					@Override
    					public void run() {
    						//displayJson.setText(str.toString());
    						if (duree != null){
    						int temps = Integer.parseInt(duree)*1000;
    						try {
    							Thread.sleep(temps);
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    						}
     
    						finish();
    					}
    				});
     
    			}
    		};
    		checkUpdate.start();
    	}
     
    	private class CallURL extends AsyncTask<URL, Integer, Long> {
    		protected Long doInBackground(URL... urls) {
    			int count = urls.length;
    			long totalSize = 0;
    			for (int i = 0; i < count; i++) {
    				try {
    					InputStream input =	urls[i].openStream();
    					input.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
     
    				// Escape early if cancel() is called
    				if (isCancelled()) break;
    			}
    			return totalSize;
    		}
     
    		protected void onProgressUpdate(Integer... progress) {
    		}
     
    		protected void onPostExecute(Long result) {
    		}
    	}
     
    }

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    47
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 47
    Points : 40
    Points
    40
    Par défaut
    Bon j'ai trouvé d'où ça venait, et c'était très très bête de ma part.
    J'explique brièvement pour ceux que ça intéresse.
    Dans ma classe j'ai cette variable :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    private ImageView imView;
    Que normalement j'initialisais avec cette ligne de code (ligne 31):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ImageView imView = (ImageView) findViewById(R.id.my_image);
    Sauf qu'en faisant ainsi, je définissais une variable interne à ma fonction OnCreate() au lieu d'initialiser ma variable de classe qui restait donc à null lors de son utilisation. Il fallait faire ainsi :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    imView = (ImageView) findViewById(R.id.my_image);
    Comme quoi, c'est le genre d'erreur qui arrive très vite qu'on peut ne pas voir de suite ^^'
    Et une nouvelle fois je démontre que 98% du temps la source d'un bug se situe entre la chaise et le clavier.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. POI NullPointerException tomcat sur row.getCell(8).getStringCellValue()
    Par mouss4rs dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 27/01/2012, 11h00
  2. [Tableau] NullPointerException sur les tableaux
    Par zsoh dans le forum Collection et Stream
    Réponses: 6
    Dernier message: 18/01/2010, 17h42
  3. nullPointerException sur un ObjectSet
    Par mouss4rs dans le forum Autres SGBD
    Réponses: 2
    Dernier message: 04/06/2008, 20h48
  4. NullPointerException sur un RTPManager?
    Par innosang dans le forum Multimédia
    Réponses: 2
    Dernier message: 30/04/2007, 14h10
  5. Réponses: 3
    Dernier message: 19/02/2007, 16h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo