【问题标题】:GSON fronJson : throwing error java.lang.NullPointerException: storage == nullGSON fronJson:抛出错误 java.lang.NullPointerException: storage == null
【发布时间】:2014-10-12 16:51:49
【问题描述】:

LogCat 输出:

10-15 21:57:58.557  10666-10666/com.example.bilal.myapp D/OpenGLRenderer﹕ Enabling debug mode 0
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ onDecode : QmageDecodeFrame      20140421 Rev.6376
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ This is decoding
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ decoding stream->hasLength()
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ onDecode : QmageDecParseHeader  call : QM
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ Qmage parsing for decoding ok
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ onDecode :  QmageHeader.NinePatched 0
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ onDecode : QmageHeader Height()     32 Width() : 32 sampleSize : 1
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ Qmage Make Color table
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ SkBitmap::kIndex8_Config ==   config && 1 == sampleSize
10-15 21:57:58.687  10666-10666/com.example.bilal.myapp E/Qmage﹕ onDecode : return true QM
10-15 21:57:59.908  10666-10685/com.example.bilal.myapp I/System.out﹕  [{"username":"bilal","title":"bilaltitle","description":"descrip","discount":"10","image1":"IMG_0477. JPG","image2":"IMG_0530.JPG","image3":"IMG_0490.JPG","image4":"IMG_0528.JPG","expiry_duration":"2014- 10-14","date_posted":"2014-10-12 13:38:34"},{"username":"bilal","title":"offer 2","description":"des  2","discount":"20","image1":"","image2":"IMG_0489.JPG","image3":"","image4":"","expiry_duration":"201 4-10-14","date_posted":"2014-10-12 20:24:01"}]
10-15 21:57:59.938  10666-10685/com.example.bilal.myapp E/OfferFetcher﹕ Failed due to:  java.lang.NullPointerException: storage == null

android 从网络服务器收到我的 JSON

[
 {  
  "username":"bilal",
  "title":"bilaltitle",
  "description":"descrip",
  "discount":"10",
  "image1":"IMG_0477.JPG",
  "image2":"IMG_0530.JPG",
  "image3":"IMG_0490.JPG",
  "image4":"IMG_0528.JPG",
  "expiry_duration":"2014-10-14",
  "date_posted":"2014-10-12 13:38:34"
  }
]

主要活动中的OfferFetcher方法接收JSON并使用GSON

private class OffersFetcher extends AsyncTask<Void, Void, String> {
    private static final  String TAG = "OfferFetcher";
    public static final String SERVER_URL ="http://192.168.0.107/webservice/listoffers.php";

    @Override
    protected String doInBackground(Void... params) {
        try {

            StringBuilder builder = new StringBuilder();
            // create an HTTP client
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);

            // perform the request and check the status code
            HttpResponse  response = client.execute(httpPost);
            StatusLine statusline = response.getStatusLine();

            if(statusline.getStatusCode() == 200) {


                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();

                try {
                    // read the server response and attempt to parse it as JSON
                        BufferedReader b_reader = new BufferedReader(new InputStreamReader(content));
                        Reader reader = new InputStreamReader(content);
                        String line;
                        while((line = b_reader.readLine()) != null) {
                            builder.append(line);
                            System.out.println(line);
                        }


                    GsonBuilder gsonbuilder = new GsonBuilder();
                    Gson gson = gsonbuilder.create();
                    List<Offer> offers;
                    offers = Arrays.asList(gson.fromJson(reader, Offer[].class));
                   } catch (Exception ex) {
                    Log.e(TAG, "Failed due to: " + ex);
                    failedLoadingOffers1();
                }
            } else {
                Log.e(TAG, "Server responded with status code: " + statusline.getStatusCode());
                failedLoadingOffers2();
            }
            return builder.toString();

        } catch (Exception ex) {
            Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
            failedLoadingOffers3();
        }
        return null;
    }
 }
}

我的优惠类(Offer.java)

 public class Offer {

 // @SerializedName("username")
 public String username;
 // @SerializedName("title")
 public String title;
 // @SerializedName("description")
 public String description;
 @SerializedName("discount")
  public String discount;
 //  @SerializedName("image1")
 public String image1;
 //  @SerializedName("image2")
 public String image2;
 //  @SerializedName("image3")
 public String image3;
 // @SerializedName("image4")
 public String image4;
 // @SerializedName("expiry_duration")
 public String expiry_duration;
 // @SerializedName("date_posted")
 public String date_posted;
 }

我的 PHP 代码在这里转发 JSON:

     $j_response["Offer"] = array();
 foreach ($row as $row) {
    $offer = array();
    $offer['username'] = $row['username'];
    $offer['title'] = $row['title'];
    $offer['description'] = $row['description'];
    $offer['discount'] = $row['discount'];
    $offer['image1'] = $row['image1'];
    $offer['image2'] = $row['image2'];
    $offer['image3'] = $row['image3'];
    $offer['image4'] = $row['image4'];
    $offer['expiry_duration'] = $row['expiry_duration'];
    $offer['date_posted'] = $row['date_posted'];

    // update our JSON data
    array_push($j_response["Offer"], $offer);
 }

 $json = json_encode($j_response["Offer"]);
 echo $json;

我的代码抛出错误 E/OfferFetcher:解析 JSON 失败,原因是:java.lang.NullPointerException: storage == null

【问题讨论】:

  • 请编辑您的问题以包含堆栈跟踪。
  • 对不起,我不明白你的问题?如何添加堆栈跟踪? Android Studio 抛出:java.lang.nullpointer 异常:storage == null at "failedLoadingOffers1() methode"

标签: android json nullpointerexception null gson


【解决方案1】:

你的问题出在这一行:

offers = Arrays.asList(gson.fromJson(reader, Offer[].class));

gson.fromJson 将第一个参数作为字符串 您正在向它发送一个阅读器!试试这个:

offers = Arrays.asList(gson.fromJson(builder, Offer[].class));

【讨论】:

  • 请在回答之前检查答案... Aadi droid 建议调试检查实体,但我不知道如何?
【解决方案2】:

尝试这样做

Type listType = new TypeToken<ArrayList<Offer>>() {}.getType();
List<Offer> list = new Gson().fromJson(line, listType);

要逐个访问每个对象,您可以这样做,

for(Offer offer : list) {
    //Do your thing
}

【讨论】:

  • 好的,谢谢伙计..我从来没有使用过“Type”和“TypeToken”...错误消失了,但我现在怎么才能让我的对象变红?
  • 我这样做了:for(Offer offer : list) { System.out.println(offer1.username); } 和 Logcat 抛出错误:Failed due to: java.lang.NullPointerException
  • 能否调试并检查实体是否不为空?
  • 如何检查实体不为空
  • 我用了这个' HttpEntity entity = response.getEntity(); InputStream 内容 = entity.getContent(); System.out.println(response.getEntity().getContentLength()); StringBuilder sb = new StringBuilder();尝试 { BufferedReader reader1 = new BufferedReader(new InputStreamReader(entity.getContent()), 65728);字符串 line1 = null; while ((line1 = reader1.readLine()) != null) { sb.append(line1); System.out.println(line1);'和 LogCat 输出:' ....bilal.myapp I/System.out:459 .... E/OfferFetcher:失败,原因是:java.lang.IllegalStateException:内容已被使用'
【解决方案3】:

谢谢dandoonian

当我使用“builder.toString()”时它起作用了

成功了:

List<Offer> offers;
offers = Arrays.asList(gson.fromJson(builder.toString(), Offer[].class));

for(Offer offer : offers) {
                        System.out.println(offer.getUsername());
                        System.out.println(offer.getTitle());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多