点击列表视图打开Android活动需要很长时间

时间:2015-02-04 17:13:38

标签: android performance listview android-listview

我试图理解为什么来自activity1的listview项目的点击需要一个记录时间(大约1秒)才能打开第二个活动。

我的代码似乎有实现或性能问题。

  • 第一个活动(主要)显示了一个列表视图。
  • 第二个活动(Detail_annonce)显示了listview项目的详细信息。

以下是我在listview项目上绑定点击的第一个活动(Main)的代码摘录:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            Annonce currentAnnonce = (Annonce) list.getAdapter().getItem(position);
                            String titre = currentAnnonce.getTitle();
                            String cat = currentAnnonce.getCategorie();
                            String desc = currentAnnonce.getDescription();
                            String etat = currentAnnonce.getEtat();
                            String img = currentAnnonce.getImage();
                            String prix = currentAnnonce.getPrix();
                            String villeObj = currentAnnonce.getVilleObjet();
                            String codePostal = currentAnnonce.getCode_postal();
                            String departement = currentAnnonce.getDepartement();
                            String avatarUser = currentAnnonce.getImageUser();
                            String pseudoUser = currentAnnonce.getPseudoUser();
                            String dateDebut = currentAnnonce.getDate_debut();
                            String idAnnonce = currentAnnonce.getId();
                            String emailUser = currentAnnonce.getEmailUser();
                            String partel = currentAnnonce.getPartel();
                            String parmail = currentAnnonce.getParmail();

                            Intent myIntent = new Intent(Main_All_Annonces.this, Detail_annonce.class);
                            myIntent.putExtra("titre", titre);
                            myIntent.putExtra("cat", cat);
                            myIntent.putExtra("desc", desc);
                            myIntent.putExtra("etat", etat);
                            myIntent.putExtra("img", img);
                            myIntent.putExtra("prix", prix);
                            myIntent.putExtra("villeObj", villeObj);
                            myIntent.putExtra("codePostal", codePostal);
                            myIntent.putExtra("departement", departement);
                            myIntent.putExtra("avatarUser", avatarUser);
                            myIntent.putExtra("pseudoUser", pseudoUser);
                            myIntent.putExtra("dateDebut", dateDebut);
                            myIntent.putExtra("idAnnonce", idAnnonce);
                            myIntent.putExtra("emailUser", emailUser);
                            myIntent.putExtra("partel", partel);
                            myIntent.putExtra("parmail", parmail);

                            myIntent.putExtra("parentAct", "AllAnnonces");

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                // get the common element for the transition in this activity
                                final View image_view = findViewById(R.id.allannonces_image);

                                //String transitionName = (String) view.getTag(R.id.allannonces_image);
                                ActivityOptionsCompat options =
                                        ActivityOptionsCompat.makeSceneTransitionAnimation(
                                                Main_All_Annonces.this,
                                                view,           // The view which starts the transition
                                                "transitionImg"  // The transitionName of the view we’re transitioning to
                                        );

                                // put more extras in the intent if you want, like the object clicked
                                myIntent.putExtra("EXTRA_IMAGE_TRANSITION_NAME", "transitionImg");
                                ActivityCompat.startActivity(Main_All_Annonces.this, myIntent, options.toBundle());
                            }
                            else {
                                // Code to run on older devices
                                startActivity(myIntent);
                                overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
                            }

                        }
                    });

以下是我的Detail_annonce活动的代码:

public class Detail_annonce extends Activity {

    HttpPost httppost;
    StringBuffer buffer;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;
    DisplayImageOptions options;
    LinearLayout btn_mail, btn_tel, btn_share;
    View bar1, bar2;
    String partel, parmail;
    TextView nbAnnonceActionBar ;


    @SuppressWarnings("unused")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.detail_layout);

        Typeface robotolight = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/Roboto/Roboto-Light.ttf");
        Typeface robotoBold = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/Roboto/Roboto-Bold.ttf");
        Typeface robotoRegular = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/Roboto/Roboto-Regular.ttf");

        bar1 = (View) findViewById(R.id.detail_view1);
        bar2 = (View) findViewById(R.id.detail_view2);

        options = new DisplayImageOptions.Builder()
                .displayer(new RoundedBitmapDisplayer(2000))
                .cacheOnDisc(true)
                .build();

        Intent previous = getIntent();
        Bundle extras = previous.getExtras();
        final String titre = extras.getString("titre");
        String cat = extras.getString("cat");
        String desc = extras.getString("desc");
        String img = extras.getString("img");
        final String prix = extras.getString("prix");
        final String villeObj = extras.getString("villeObj");
        final String codePostal = extras.getString("codePostal");
        String avatarUser = extras.getString("avatarUser");
        final String pseudoUser = extras.getString("pseudoUser");
        String dateDebut = extras.getString("dateDebut");
        final String idAnnonce = extras.getString("idAnnonce");
        final String emailUser = extras.getString("emailUser");
        partel = extras.getString("partel");
        parmail = extras.getString("parmail");
        String parentAct = extras.getString("parentAct");

        ImageView image_txt = (ImageView) findViewById(R.id.detail_annonce_image);
        TextView titre_txt = (TextView) findViewById(R.id.detail_annonce_titre);
        TextView prix_txt = (TextView) findViewById(R.id.detail_annonce_prix);
        TextView dateDebut_txt = (TextView) findViewById(R.id.detail_annonce_date_debut);
        TextView villeAndCodePostal = (TextView) findViewById(R.id.detail_annonce_ville_and_codePos);

        ImageLoader imageLoader = ImageLoader.getInstance();

        Double latitude = null, longitude = null;
        Geocoder geo = new Geocoder(getBaseContext(), Locale.getDefault());
        try {
            List<Address> addresses = geo.getFromLocationName(villeObj, 10);
            Address currentFound = addresses.get(0);
            if (currentFound.hasLatitude() && currentFound.hasLongitude()) {
                latitude = currentFound.getLatitude();
                longitude = currentFound.getLongitude();
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        ViewCompat.setTransitionName(image_txt, getIntent().getStringExtra("EXTRA_IMAGE_TRANSITION_NAME"));
        imageLoader.displayImage(img, image_txt);

        titre_txt.setText(titre);
        titre_txt.setTypeface(robotoRegular);

        prix_txt.setText("€" + prix + ",00 EUR");
        prix_txt.setTypeface(robotolight);

        villeAndCodePostal.setText("Disponible à " +villeObj);
        villeAndCodePostal.setTypeface(robotolight);

        ////////////////
        /// DATE
        ////////////////
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date pDate;
        try {
            pDate = df.parse(dateDebut);
            dateDebut = DateUtils.getDateDifference(pDate);
            dateDebut = dateDebut.replace("-", "");
        } catch (ParseException e) {
            Log.e("DATE PARSING", "Error parsing date..");
        }

        dateDebut_txt.setText("Posté il y a " + dateDebut + "dans la catégorie " +cat);
        dateDebut_txt.setTypeface(robotolight);

        if (latitude != null && longitude != null ) {
            // Get a handle to the Map Fragment
            GoogleMap map = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)).getMap();

            LatLng ville = new LatLng(latitude, longitude);

            map.setMyLocationEnabled(true);
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(ville, 9));

            map.addMarker(new MarkerOptions()
                    .title(villeObj)
                    .visible(true)
                    .snippet("La vente se fait à cet adresse.")
                    .position(ville));
        }

}

2 个答案:

答案 0 :(得分:2)

当Android启动您的新活动时,它会在显示任何内容之前执行onCreate() 中的所有代码。

通常我所做的(作为专业的Android开发人员)只抓取我在onCreateView()中保留为类变量的视图,然后将所有填充代码放在onStart()中。如果您的活动在切换活动后显示数据需要一段时间,您可以将ProgressSpinner视图放在前面,这样您的用户就知道数据仍在处理中。

在您的情况下,绝对可以使用onCreate()中的所有Google地图代码。 Google地图非常受欢迎,有时服务器需要一段时间才能满足您的要求。

附注:    我同意评论者关于将您的对象作为额外内容进行传输。为此,您必须将对象标记为SerializableSee this SO question. 查看投票率最高的答案,而不是“已接受”的答案。

模块化您的代码!将一些内容分成辅助方法,然后在onCreateView()onStart()方法中调用它们。它将使代码移动更容易。

您应该考虑使用单个Actvitity并仅使用片段来处理所有单独的屏幕(弹出窗口除外)。片段可以帮助您的代码更加面向对象,并避免重复这么多代码。 Google似乎也在努力推动Fragment-Decorator的设计模式。然而,这最终归结为个人偏好。

修改:More info about Activity lifecycle methods here.注意{<1}}在之前如何调用,表示活动已“创建”。

答案 1 :(得分:-1)

使用GSON库。这对你有好处。