0

我在 Android 中工作,但遇到了一大段代码问题:

public static void main(String[] args) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
    String text = null;
    try {
          HttpResponse response = httpClient.execute(httpGet, localContext);
          HttpEntity entity = response.getEntity();
          text = getASCIIContentFromEntity(entity);
    } catch (Exception e) {
    }
    System.out.println(text);
}

这段代码可以在 Java 中的另一个项目上正确运行。问题是,当我尝试在 Android 中使用这段代码时,它会出错。

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3633)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.view.View$1.onClick(View.java:3628)
... 11 more
Caused by: java.lang.NullPointerException
at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
at com.example.mgen.MgenActivity.renew(MgenActivity.java:61)
at com.example.mgen.MgenActivity.refresh(MgenActivity.java:44)
... 14 more

我在两个项目上都有相同的进口。有没有人见过这样的问题或这样的异常?我似乎在任何地方都找不到类似的东西。

此外,我有一个连接到本地 9. 网络的 VPN,我可以从 android vm 互联网浏览器和我的本地笔记本电脑访问它。

我也排查过 安卓版本上的问题 在线

HttpResponse response = httpClient.execute(httpGet, localContext);

更完整的代码:

package com.example.mgen;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MgenActivity extends Activity {
ArrayList<mgenObject> listItems = new ArrayList<mgenObject>();

ArrayAdapter<mgenObject> adapter;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    adapter = new ArrayAdapter<mgenObject>(this,
            android.R.layout.simple_list_item_1, listItems);
    ListView lv = (ListView) findViewById(R.id.list);
    lv.setAdapter(adapter);
    renew();
}

// METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void refresh(View v) {

    listItems = renew();
    adapter.notifyDataSetChanged();

    System.out.println("refresh worked");
}

public ArrayList<mgenObject> renewTest() {
    mgenObject object = new mgenObject("test", "test", "test");
    ArrayList<mgenObject> list = new ArrayList<mgenObject>();
    list.add(object);
    return list;

}

public ArrayList<mgenObject> renew() {
    ArrayList<mgenObject> tempList = new ArrayList<mgenObject>();
    String jsonStr = getMgenJSON();
    System.out.println(jsonStr);

    try {
        JSONArray rows = new JSONArray(jsonStr); // Parse the JSON to a
                                                    // JSONArray
        for (int i = 0; i < rows.length(); i++) { // Loop over each each row
            JSONObject element = rows.getJSONObject(i); // Get row object
            String workflow = element.getString("workflow_state");
            String vgen = element.getString("vgen_state");
            String name = element.getString("title");

            mgenObject tempObject = new mgenObject(name, workflow, vgen);
            tempList.add(tempObject);
        }

    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }

    return tempList;
}

public String getMgenJSON() {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(
            "http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
    String text = null;
    try {
        System.out.println("testing3");
        HttpResponse response = httpClient.execute(new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack"));
        System.out.println("testing3.5");
        HttpEntity entity = response.getEntity();
        System.out.println("testing4");
        text = getASCIIContentFromEntity(entity);
        System.out.println("testing5");
    } catch (Exception e) {
        return e.getLocalizedMessage();
    }
    System.out.println(text);
    return text;
}

protected String getASCIIContentFromEntity(HttpEntity entity)
        throws IllegalStateException, IOException {
    InputStream in = entity.getContent();
    StringBuffer out = new StringBuffer();
    int n = 1;
    while (n > 0) {
        byte[] b = new byte[4096];
        n = in.read(b);
        if (n > 0)
            out.append(new String(b, 0, n));
    }
    return out.toString();
}
}

另外,如果您不知道,我正在尝试在单击按钮时进行此调用。

4

3 回答 3

1

您不能在主线程上进行网络调用。尝试将您的网络调用放在doInBackgroundAsyncTask

public void blah(String[] args) {
   new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute()
        {
            // here is for code you do before the network call. you 
            // leave it empty
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            // here goes your network call
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
            String text = null;
            try {
                  HttpResponse response = httpClient.execute(httpGet, localContext);
                  HttpEntity entity = response.getEntity();
                  text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
            }
            System.out.println(text);
        }

        @Override
        protected void onPostExecute(Void res)
        {
            // here goes your UI code. i.e if you want to hide a button
        }
    }.execute();
}
于 2013-07-30T21:27:49.700 回答
0

使用 Android 时,不允许在主线程上进行网络调用。奇怪的是,这似乎不是这里提出的问题。您是在处理单独的线程还是 AsyncTask?

于 2013-07-30T21:24:51.830 回答
0

可以发一下安卓代码吗?因为这看起来像普通的 Java。Android中也有很多事情可能出错。确保您在清单文件中具有适当的权限。然后,您需要使用后台任务从网络中实际检索某些内容。这可以通过扩展 Asynctask 抽象类来完成。

检查文档:

http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-07-30T21:25:12.010 回答