2015-04-23 20 views
1

我想創建一個if語句,檢查看到「-1,0,1,2,3,4和5」的餐廳的「評級」。我需要用圖像替換評級號碼。我已經試圖做到這一點,但應用程序不斷崩潰,應用程序工作正常,沒有if語句,並顯示10個最近的位置,因爲它應該。這裏是代碼:Android開發如果聲明與圖像

JSONObject jo = (JSONObject) ja.get(i); 
String name = jo.getString("BusinessName"); 
String rating = jo.getString("RatingValue"); 
String address1 = jo.getString("AddressLine1"); 
String address2 = jo.getString("AddressLine2"); 
String postcode = jo.getString("PostCode"); 

ImageSwitcher imageView = null; 
if(rating.equalsIgnoreCase("-1")){ 
    imageView.setImageResource(R.drawable.rating0); 
}else if(rating.equalsIgnoreCase("0")){ 
    imageView.setImageResource(R.drawable.rating0); 
}else if(rating.equalsIgnoreCase("1")){ 
    imageView.setImageResource(R.drawable.rating0); 
}else{ 
    //default case, if above all conditions will become false then this will call 
} 
+0

發佈logcat。 – Bharatesh

+0

顯然它會崩潰,因爲'imageView'爲空。 init查看'findViewById(R.id.viewid);' – Bharatesh

+0

看看Android Studio對你發佈的代碼所說的:方法調用'imageView.setImageResource(R.drawable.rating0)'可能產生'java.lang.NullPointerException' – MiguelHincapieC

回答

0

UPDATE:

除了下面的代碼,你需要建立一個視圖工廠,使您的圖像可以添加到一些東西。

ImageSwitcher imageView = new ImageSwitcher(context); 
imageView.setFactory(new ViewSwitcher.ViewFactory() { 
     @Override 
     public View makeView() { 
      ImageView view = new ImageView(Location_assignment.this); 
      return view; 
     } 
    }); 

然後把你的if語句放在這個代碼下面。


您的圖像切換器爲空。您需要實例化圖像切換器,然後才能將圖像分配給它。

ImageSwitcher imageView = new ImageSwitcher(context); 
+0

哦,好的,所以在(上下文)我需要將其更改爲評分變量?因爲它提出了一個錯誤@Zamereon – abdul

+0

你的上下文將是任何上下文是在這一點上。如果你在一個活動中,只需用'this'替換它,如果你在一個片段中,用'getActivity()'替換它等。 – Zamereon

+0

我在我的main_activity中,當我改變上下文到它時,它來了出現錯誤。錯誤是:ImageSwitcher(ImageSwitcher中的android.content.Context無法應用於(android.location.LocationListener)@Zamereon – abdul

0
ImageSwitcher imageView = null; 

其空。

使其不爲空。

0

你必須檢查兩件事情:

首先需要初始化ImageView的(因爲它是空)。 這就是AS說一下你的代碼:

方法調用 'imageView.setImageResource(R.drawable.rating0)' 可能會產生 '顯示java.lang.NullPointerException'

其次,是個好主意檢查變量「rating」是否爲null,因爲它來自JSON。

+0

我懷疑評級將爲空,在CAS e在'json中找不到'RatingValue',那麼它會拋出JSON異常。 – Bharatesh

+0

是的,但通常你會在拋出JSON異常之前處理這些問題(控制檯日誌,生成味精錯誤......)。 – MiguelHincapieC

+0

RatingValue不爲空。所有來自JSON的結果都很好,只是當我試圖將評分值轉換爲一張因爲它爲空而崩潰的圖像時。 – abdul