我有一個簡單的要求我有一個字符串數組,我在類級別聲明,以便我可以在類中的任何地方使用它。如何訪問從另一個方法初始化一個方法的字符串數組?
String image_url[];//Declared outside of any methods
//Initailzed image_url[] to img_url[]
public void showJSON(String json)
{
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
image_url= ParseJSON.img_url;
Toast.makeText(DisplayMagazine.this, "Image loc"+image_url[1], Toast.LENGTH_SHORT).show();
}
我想用IMAGE_URL數組中的下列方法: -
private ArrayList prepareData() {
ArrayList android_version = new ArrayList<>();
for (int i = 0; i < magazine_version_names.length; i++) {
MagazineVersion magazineVersion = new MagazineVersion();
magazineVersion.setMagazine_version_name(magazine_version_names[i]);
magazineVersion.setMagazine_image_url(image_url[i]);
android_version.add(magazineVersion);
}
return android_version;
}
當我運行這段代碼的應用程序崩潰與在這一行一個空指針異常: -
magazineVersion.setMagazine_image_url(image_url[i]);
這是ParseJSON代碼: -
public class ParseJSON
{
public static String[] magversion;
public static String[] img_url;
public static String[] download_url;
public static String[] sample_url;
public static String[] status_dl;
public static String[] status_sm;
public static String[] device_id;
public static final String JSON_ARRAY = "result";
public static final String KEY_MAGVER = "magversion";
public static final String KEY_IMGURL = "img_url";
public static final String KEY_DOWNLOADURL = "download_url";
public static final String KEY_SAMPLEURL = "sample_url";
public static final String KEY_STATUS_DL ="status_dl";
public static final String KEY_DEVICE_ID ="device_id";
private JSONArray magazines = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
magazines = jsonObject.getJSONArray(JSON_ARRAY);
magversion = new String[magazines.length()];
img_url = new String[magazines.length()];
download_url = new String[magazines.length()];
sample_url= new String[magazines.length()];
status_dl= new String[magazines.length()];
device_id= new String[magazines.length()];
for(int i=0;i<magazines.length();i++){
JSONObject jo = magazines.getJSONObject(i);
magversion[i] = jo.getString(KEY_MAGVER);
img_url[i] = jo.getString(KEY_IMGURL);
download_url[i] = jo.getString(KEY_DOWNLOADURL);
sample_url[i] = jo.getString(KEY_SAMPLEURL);
status_dl[i] = jo.getString(KEY_STATUS_DL);
device_id[i] = jo.getString(KEY_DEVICE_ID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我是新手編程,所以任何幫助或建議表示讚賞。謝謝。
可以顯示'ParseJSON(String)'構造函數嗎? –
[什麼是NullPointerException,以及如何解決它?]可能重複(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –
提示:理解字段是什麼,以及它們與你的類的關係是**絕對必要的基本**東西。如果你不知道這些事情,最好讓你的手指遠離android編程。目前。重點是:不要試圖學習java做android編程。首先學習java基礎知識,然後轉向Android。其他任何事情都會導致(可能很短)一系列非常令人沮喪的「爲什麼這不起作用」的體驗。總之,因爲你很快就會失去動力。 – GhostCat