Android - IllegalStateException:已消耗内容

时间:2015-07-30 03:15:59

标签: android

我搜索了它,但我不知道在我的代码中多少使用了一个实体。你能告诉我哪些部分需要修复这些错误吗?我尝试从JSONObject传递值,我将从我的php端到下一个活动。

public class UploadToServerActivity extends Activity {

ArrayList<Integer> xPoint, yPoint;
byte[] img;
String imagePath;
String imageData;
Button b1, b2;
ImageView v1;
Bitmap imageDrawOverlay;

int answerId, accuracyNum;
String jsonResult = "";
String srcString = "";

String urlServer = "~~.php";
//HttpURLConnection connection = null;

HttpURLConnection con = null;
String responseFromServer;
private static final String  TAG = UploadToServerActivity.class.getSimpleName();

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

    b1 = (Button)findViewById(R.id.button);
    b2 = (Button)findViewById(R.id.button2);
    v1 = (ImageView)findViewById(R.id.imageView3);

    Intent intent = getIntent();

    xPoint = intent.getIntegerArrayListExtra("xData");
    yPoint = intent.getIntegerArrayListExtra("yData");
    imagePath = intent.getStringExtra("imagePath");

    Bitmap bp = null;
    if(getIntent().hasExtra("imagePath")) {

        File file = new File(getIntent().getStringExtra("imagePath"));

        try {
            bp = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));

        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Error: " + e.toString());
        }
    }
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    img = stream.toByteArray();


    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d(TAG, "hello");
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadToServer();
                }
            });
            t.start();

            Toast.makeText(UploadToServerActivity.this,"Upload Successful", Toast.LENGTH_SHORT).show();
        }
    });

    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(UploadToServerActivity.this, MenuActivity.class);
            startActivity(intent);
        }
    });

    if (getIntent().hasExtra("imagePath")) {
        File file = new File(getIntent().getStringExtra("imagePath"));

        try {
            bp = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));

        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Error: " + e.toString());
        }

        Log.d(TAG, "Width: " + bp.getWidth() + " Height: " + bp.getHeight());

        v1.setImageBitmap(bp);
        imageDrawOverlay = bp;
    }
}

@SuppressWarnings("deprecation")
public boolean uploadToServer() {
    try {
        String responseString = null;
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(urlServer);
        HttpPost httpPostTwo = new HttpPost(urlServerTwo);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        imageData = Base64.encodeToString(img, Base64.DEFAULT);
        String xDat = xPoint.toString();
        String yDat = yPoint.toString();

        nameValuePairs.add(new BasicNameValuePair("imageData", imageData));
        nameValuePairs.add(new BasicNameValuePair("xData", xDat));
        nameValuePairs.add(new BasicNameValuePair("yData", yDat));
        Log.d(TAG, "xp: " + xPoint.toString());
        Log.d(TAG, "yp: " + yPoint.toString());
        Log.d(TAG, "im: " + imageData.length());

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httpPost);

        String responseBody = EntityUtils.toString(response.getEntity());
        Log.d(TAG, responseBody);
        responseFromServer = responseBody;

        HttpEntity result = response.getEntity();
        if (result != null) {
            InputStream input = result.getContent();
            jsonResult = convertStreamToString(input);
            Log.d(TAG, jsonResult);
            Log.d(TAG, "jesonResult works");

            testReceiveData(jsonResult);
            Log.d(TAG, "maybe this one works too");
        } else {
            Log.d(TAG, "broke in repsonse");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

private String convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
        Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
    }
    return total.toString();
}

public void triggerImageUpload() {
    makeHTTPCall();
}

public void makeHTTPCall() {
}

public void testReceiveData(String jsonResult) {
    try {
        srcString = jsonResult;
        Log.d(TAG, "here"+srcString);

        JSONObject jsonObj = new JSONObject(jsonResult);
        answerId = jsonObj.getInt("animal_id");
        accuracyNum = jsonObj.getInt("accuracy");

        Log.d(TAG, "It gets JSONObject");
        Intent intent = new Intent(UploadToServerActivity.this, ResultActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("ansId", String.valueOf(answerId));
        bundle.putString("accNum", String.valueOf(accuracyNum));

        intent.putExtras(bundle);
        startActivity(intent);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
}

和logcat消息如下:

07-29 23:02:34.442    4885-5988/com.example.kange1.bert D/UploadToServerActivity﹕ [ 07-29 23:02:34.442  4885: 5988 W/System.err ]
java.lang.IllegalStateException: Content has been consumed
07-29 23:02:34.443    4885-5988/com.example.kange1.bert W/System.err﹕ at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:89)
07-29 23:02:34.443    4885-5988/com.example.kange1.bert W/System.err﹕ at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:105)
07-29 23:02:34.451    4885-5988/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.UploadToServerActivity.testSecondEntity(UploadToServerActivity.java:284)
07-29 23:02:34.451    4885-5988/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.UploadToServerActivity.uploadToServer(UploadToServerActivity.java:211)
07-29 23:02:34.451    4885-5988/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.UploadToServerActivity$1$1.run(UploadToServerActivity.java:122)
07-29 23:02:34.455    4885-5988/com.example.kange1.bert W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

很抱歉,我问你很多事情,但你能告诉我线程是否可以访问或在下一个活动中运行? (当我点击按钮转到下一个活动时,我会收到这些错误。它不会转到下一个活动,只是保持当前活动。)

我添加了HttpResponse responseTwo = response;

一些错误发生了变化

07-29 23:26:07.073  16242-17021/com.example.kange1.bert D/UploadToServerActivity﹕ [ 07-29 23:26:07.073 16242:17021 W/System.err ]
java.lang.IllegalStateException: Content has been consumed
07-29 23:26:07.073  16242-17021/com.example.kange1.bert W/System.err﹕ at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:89)
07-29 23:26:07.073  16242-17021/com.example.kange1.bert W/System.err﹕ at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:105)
07-29 23:26:07.073  16242-17021/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.UploadToServerActivity.uploadToServer(UploadToServerActivity.java:200)
07-29 23:26:07.073  16242-17021/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.UploadToServerActivity$1$1.run(UploadToServerActivity.java:122)
07-29 23:26:07.073  16242-17021/com.example.kange1.bert W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:0)

为了简单快速的结果,我建议Android Asynchronous Http Client

例如:添加此依赖项

dependencies {
  compile 'com.loopj.android:android-async-http:1.4.8'
}

并且

public void uploadToServer(){
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams();
        imageData = Base64.encodeToString(img, Base64.DEFAULT);
        String xDat = xPoint.toString();
        String yDat = yPoint.toString();
        requestParams.put("imageData" , imageData);
        requestParams.put("xData" , xDat);
        requestParams.put("yData" , yDat);
        asyncHttpClient.post(urlServer , requestParams , new JsonHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                //Call back  if your response is JSONObject
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                //Failure callback
            }


            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                //Call back if your response is JSONArray
            }
        });
    }