我正在尝试创建一个从我的网站解析代码并将其显示在listActivity上的应用程序。我试过使用几个网站......它们都运行良好。但是后来我的网站显示了这个java.lang.NegativeArraySizeException:-1异常!
package com.example.hamad.jsonparsingverybasic;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "log";
TextView network;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
network = (TextView) findViewById(R.id.networkStatus);
if (isNetworkAvailable()) {
GetBlogPosts getBlogPosts = new GetBlogPosts();
getBlogPosts.execute();
network.setText("Network: Available!");
} else {
network.setText("Network: Not available!");
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean netWorkAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
netWorkAvailable = true;
}
return netWorkAvailable;
}
private class GetBlogPosts extends AsyncTask<Object, Void, String> {
int responseCode = 0;
@Override
protected String doInBackground(Object[] params) {
try {
URL blogURL = new URL("http://trapedzone.com/api/info/");
HttpURLConnection connection = (HttpURLConnection) blogURL.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
Log.v(TAG, responseData);
} catch (Exception e) {
}
} else {
Log.e(TAG, "Bad response code: " + responseCode);
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e);
}
return "Code: " + responseCode;
}
}
}
执行时,它会在我的网站http://trapedzone.com上抛出java.lang.NegativeArraySizeException:-1异常,但在我在其他网站http://trapedhost.com上使用它时效果很好 请帮忙。我的网站是否存在问题,或者我可以在java代码中修复这些问题。
答案 0 :(得分:0)
如果您发布了堆栈跟踪,这将有所帮助。
但是,您发布的代码中只有一行可能会生成该错误: char [] charArray = new char [contentLength];
所以,我猜想connection.getCOntentLength()返回-1。