打开一个 android activity on click in listview 需要很长时间

Open an android activity on click in listview takes a long time

我想了解为什么单击 activity1 中的列表视图项目需要很长时间(大约 1 秒)才能打开第二个 activity。

看来我的代码有实现或性能问题..

这是我的第一个 activity(主要)代码的摘录,用于绑定点击列表视图项目:

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 activity 上的代码:

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

}

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

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

通常我所做的(作为专业 Android 开发人员)只是获取我在 onCreateView() 中作为 class 变量保留的视图,然后将我所有的填充代码放入onStart()。如果您的 Activity 在切换 Activity 后显示数据需要一些时间,您可以在前面放置一个 ProgressSpinner 视图,以便您的用户知道数据仍在处理中。

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

旁注: 我同意评论者关于将您的对象作为额外传输的观点。为此,您必须将对象标记为 SerializableSee this SO question. 查看投票最多的答案,而不是 "accepted" 那个。

模块化你的代码!将其中一些内容分离到辅助方法中,然后在 onCreateView()onStart() 方法中调用这些方法。这将使移动代码变得更加容易。

您应该考虑使用单个 Actvitity,并只对所有单独的屏幕(不包括弹出窗口)使用 Fragment。片段有助于使您的代码更加面向对象,并避免重复过多的代码。 Google 似乎也在大力推动 Fragment-Decorator 设计模式。然而,这最终归结为个人喜好。

编辑:More info about Activity lifecycle methods here. 注意 onCreate() 在 之前是如何被调用的 ,图表表明 Activity 是 "created"。