简体   繁体   中英

How to debug this Android Studio app

I have tried to access a web resource using my second android app, in Android Studio. Im on API 15 as min, target and build. Here is my class. Its not MVC at all, i just threw in all the stuff from the Developing your first Android App tutorial online into the MainActivity Class:

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;
        }
    }

}

and here is the huge log file:

Well I won't post it, but I have 2 questions:

  • How can I reduce all the output in log cat. I already switched from verbose to debug but I still get lots of stuff. And in this particular case, because the app crashes, I don't have time to do what another SO post said which is select the running process and hit the 2 green arrow button that filters out only output for the running process. Would I need to get the app to NOT crash before I could filter out the log such that i can SEE what is making it crash? Otherwise its difficult to sort through all the logs. What is the best practice here.

  • I do get one of my logs; "01-30 10:40:58.665 2047-2072/com.santiapps.downloadwebdata D/HttpExample﹕ The response is: 200" which is in the code but then a few lines down I get the crash:

    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) at android.os.AsyncTask.finish(AsyncTask.java:631) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5071) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575) at dalvik.system.NativeStart.main(Native Method) 01-30 10:40:58.717 83 7-2676/? W/ActivityManager﹕ Force finishing activity com.santiapps.downloadwebdata/.MainActivity

Its a null pointer exception I see. How do I follow it? Sorry, Im new to android. Thanks

You can follow the logcat by clicking on the links, for example MainActivity.java:77 .

You can filter the log by creating a new filter, (see image)

过滤器配置

There you can filter by Package Name , so only the log of your app will be visible

Your TextView is null ...

You typically initialize it like this :

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

As for reducing the amount of log, you should filter the log on your app's package name. In Android Studio, this should be located on the right of Log Level in the Android DDMS panel (it probably reads No Filter for now, you will need to create one by clicking Edit Filter Configuration).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM