使用onCreateOptionsMenu,Android应用程序变得越来越慢

时间:2017-06-30 09:25:59

标签: java android

我的应用会显示ListView中的所有图片。它很快,但后来我添加了onCreateOptionsMenu。从那时起,应用程序非常慢,只显示一个图像。这与线程有关吗?

这是我MainActivity的代码:

public class MainActivity extends AppCompatActivity {

  static ArrayList<Product> arrayList;
  ListView lv;

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

      arrayList = new ArrayList<>();
      lv = (ListView) findViewById(R.id.listView);

      runOnUiThread(new Runnable() {
         @Override
         public void run() {
            new ReadJSON().execute("http://10.0.3.2:5000/products/id/6");
          }
      });
  }

  class ReadJSON extends AsyncTask<String, Integer, String> {

      @Override
      protected String doInBackground(String... params) {
          return readURL(params[0]);
      }

      @Override
      protected void onPostExecute(String content) {
          try {
              JSONObject jsonObject = new JSONObject(content);
              JSONArray jsonArray =  jsonObject.getJSONArray("products");

              for(int i =0;i<jsonArray.length(); i++){
                  JSONObject productObject = jsonArray.getJSONObject(i);
                  arrayList.add(new Product(
                          productObject.getString("image"),
                          productObject.getString("title"),
                          productObject.getString("price"),
                          productObject.getString("description")
                  ));
              }
          } catch (JSONException e) {
              e.printStackTrace();
          }
          CustomListAdapter adapter = new CustomListAdapter(
                  getApplicationContext(), R.layout.custom_list_layout, arrayList
          );
          lv.setAdapter(adapter);

          lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {  // list item click opens a new detailed activity
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Product product = arrayList.get(position); // getting the model
                  Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                  intent.putExtra("title", product.getName());
                  intent.putExtra("price", product.getPrice());
                  intent.putExtra("img", product.getImage());
                  intent.putExtra("description", product.getDescription());
                  intent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
                  startActivity(intent);
              }
          });
      }
  }

  private static String readURL(String theUrl) {
      StringBuilder content = new StringBuilder();
      try {
          // create a url object
          URL url = new URL(theUrl);
          // create a urlconnection object
          URLConnection urlConnection = url.openConnection();
          // wrap the urlconnection in a bufferedreader
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
          String line;
          // read from the urlconnection via the bufferedreader
          while ((line = bufferedReader.readLine()) != null) {
              content.append(line + "\n");
          }
          bufferedReader.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
      return content.toString();
  }

  public static ArrayList<Product> getProduct(Resources res) {
      return arrayList;
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.menu, menu);

      return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      int id = item.getItemId();
      if(id == R.id.shoppingcart) {
          Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
          startActivity(viewShoppingCartIntent);
          return true;
      }

      return super.onOptionsItemSelected(item);
  }

}

编辑1:菜单资源文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:id="@+id/shoppingcart"
    android:icon="@drawable/shop_1600"
    android:title="Item"
    app:showAsAction="always" />
</menu>

编辑2 :这是出现问题的最小示例。

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);

    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.shoppingcart) {
        Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
        startActivity(viewShoppingCartIntent);
        return true;
    }

    return super.onOptionsItemSelected(item);
  }
}

1 个答案:

答案 0 :(得分:1)

你不会在onCreateOptionsMenu中做任何繁重的工作,所以我不会在那里看到问题。

但在AsyncTask内运行runOnUiThread并不是一个好主意。 AsyncTask本身已经处理了哪个代码在单独的线程上运行并且在UI线程上运行。

onCreate内调用它,就像这样:

new ReadJSON().execute("http://10.0.3.2:5000/products/all");