编舞:跳过53帧!应用程序可能在其主线程上做了太多工作

时间:2017-05-04 20:09:57

标签: java android performance listview

我不知道为什么,但我经常收到此错误,另一个问题是AsyncTask后listView不可见,我必须再次手动刷新到notifyDataSetChanged。请帮忙!提前致谢! MainActivity.java

public class MainActivity extends AppCompatActivityimplements NavigationView.OnNavigationItemSelectedListener { 

ListView listView;
CustomAdapter customAdapter;
public static Boolean tapped = false;

SwipeRefreshLayout refreshLayout;

public static ArrayList<String> titles;
public static ArrayList<String> newsSources;
public static ArrayList<String> imageUrl;
public static ArrayList<String> urls;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //Main

    ListView listView = (ListView) findViewById(R.id.listView);

    refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh);

    refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            customAdapter.notifyDataSetChanged();
            refreshLayout.setRefreshing(false);
        }
    });

    titles = new ArrayList<>();
    urls = new ArrayList<>();
    newsSources = new ArrayList<>();
    imageUrl = new ArrayList<>();

    customAdapter = new CustomAdapter(MainActivity.this, titles, newsSources, imageUrl);

    DownloadTask task = new DownloadTask();
    try {

        task.execute("https://newsapi.org/v1/articles?source=the-verge&sortBy=top&apiKey=357539b5b6dd401689aa2f400ce1a03d");
        listView.setAdapter(customAdapter);
        customAdapter.notifyDataSetChanged();


    } catch (Exception e) {

        e.printStackTrace();

    }


}

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {

        String result = "";
        URL url;
        HttpsURLConnection urlConnection = null;

        try {

            url = new URL(strings[0]);
            urlConnection = (HttpsURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;
                result += current;
                data = reader.read();

            }

            Log.i("URLContent", result);

            JSONObject jsonObject = new JSONObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("articles");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                String articleTitle = jsonObject1.getString("title");
                String articleURL = jsonObject1.getString("url");
                String articleThumbnail = jsonObject1.getString("urlToImage");
                String articleSource = jsonObject1.getString("author");

                Log.i("Content", articleTitle);

                titles.add(articleTitle);
                imageUrl.add(articleThumbnail);
                newsSources.add(articleSource);
                urls.add(articleURL);

            }


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

        return null;
    }


}



@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

} `

1 个答案:

答案 0 :(得分:1)

不要在主线程中调用线程。当活动完成UI工作时也调用线程。就像在awk < file '{print $2}' | while read -r x ; do somecmd "$x" ; done 中放置AsyncTasks并在onStart()方法中销毁它们一样。