如何调试此Android Studio应用程序

时间:2014-01-30 16:58:35

标签: android debugging nullpointerexception android-studio

我试图在Android Studio中使用我的第二个Android应用访问网络资源。我在API 15上作为min,target和build。这是我的课。它根本不是MVC,我只是将在线开发你的第一个Android App教程的所有内容都投入到MainActivity类中:

public class MainActivity extends Activity {
    private static final String DEBUG_TAG = "HttpExample";
    private static final String MYURL = "http://www.server.com/app/service.php";
    private TextView textView;

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

        textView = (TextView) findViewById(R.id.hello_world);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        //Check connectivity
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            //fetch data
            new DownloadWebpageTask().execute(MYURL);
            textView.setText("Fetching data");

        } else {
            //show error
            textView.setText("No network connection available.");
        }
    }

    //Method to connect to the internet
    // Uses AsyncTask to create a task away from the main UI thread. This task takes a
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
        }
    }

    //Method to convert url to url object
    // Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    //Convert input stream to string
    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

这是一个巨大的日志文件:

我不会发布它,但我有两个问题:

  • 如何减少log cat中的所有输出。我已经从verbose切换到调试但我仍然有很多东西。在这种特殊情况下,由于应用程序崩溃,我没有时间做另一个SO帖子所说的选择正在运行的进程并点击2绿色箭头按钮,只过滤掉运行进程的输出。在我可以过滤掉日志之前,我是否需要让应用程序不崩溃,这样我才能看到导致崩溃的原因?否则很难对所有日志进行排序。这里的最佳做法是什么。

  • 我确实得到了一份日志; “01-30 10:40:58.665 2047-2072 / com.santiapps.downloadwebdata D / HttpExample:响应是:200”,这是在代码中然后几行我崩溃了:

    01-30 10:40:58.710 2047-2047 / com.santiapps.downloadwebdata E / AndroidRuntime:FATAL EXCEPTION:main java.lang.NullPointerException            at com.santiapps.downloadwebdata.MainActivity $ DownloadWebpageTask.onPostExecute(MainActivity.java:77)            at com.santiapps.downloadwebdata.MainActivity $ DownloadWebpageTask.onPostExecute(MainActivity.java:63)            在android.os.AsyncTask.finish(AsyncTask.java:631)            在android.os.AsyncTask.access $ 600(AsyncTask.java:177)            在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644)            在android.os.Handler.dispatchMessage(Handler.java:99)            在android.os.Looper.loop(Looper.java:137)            在android.app.ActivityThread.main(ActivityThread.java:5071)            at java.lang.reflect.Method.invokeNative(Native Method)            在java.lang.reflect.Method.invoke(Method.java:511)            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:808)            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)            at dalvik.system.NativeStart.main(Native Method)01-30 10:40:58.717 837-2676 /? W / ActivityManager:强制完成活动com.santiapps.downloadwebdata / .MainActivity

我看到它是一个空指针异常。我该怎么做?对不起,我是新来的android。感谢

2 个答案:

答案 0 :(得分:2)

您可以通过单击链接来关注logcat,例如 MainActivity.java:77

您可以通过创建新过滤器来过滤日志(参见图像)

filter configuration

您可以按包名过滤,这样只会看到您应用的日志

答案 1 :(得分:1)

您的TextView为空...

您通常会像这样初始化它:

setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.id_of_your_textview);

至于减少日志量,您应该过滤应用程序包名称上的日志。在Android Studio中,它应该位于Android DDMS面板中Log Level的右侧(它现在可能只读取No Filter,您需要通过单击Edit Filter Configuration来创建一个)。