کلیدستان

نسخه‌ی کامل: بسته شدن برنامه هنگام استفاده از حلقه در custom ListView (برنامه نویسی اندروید)
شما در حال مشاهده نسخه آرشیو هستید. برای مشاهده نسخه کامل کلیک کنید.
با سلام خدمت دوستان
بنده یک هفته هست که با این مشکل برخورد کردم و هرکاری کردم به نتیجه نرسیدم به دادم برسید
من داخل حافظه گوشی یه پوشه درست کردم با نام 01mypicture و تعدادی عکس درون این پوشه دخیره کردم و تعداد این عکسها ممکن است زیادتر بشه یا کمتر بشه

حالا میخوام این عکسها به همراه توضیحاتی در یک لیست ویو نمایش داده شوند که مسلما باید به روش Custom ListView
هرچه آموزش و تکه کد داخل تو اینترنت هست را بررسی کردم و همه برای حالتی که عکسها داخل پوشه Drawable میباشد
در صورتیکه من عکسهام داخل پوشه ای در حافظه هست که برای همین هم تکه کد هایی از اینترنت پیدا کردم

مشکل من این هست که فرض کنید داخل پوشه یک عکس دارم حالا میخوام این عکس را 3 بار پشت سر هم نمایش بدم و من اومدم یه حلقه for نوشتم که با این حلقه for داخل شبیه ساز اندروید (YouWave) درست نمایش میده ولی وقتی فایل apk برنامه را روی گوشی میریزم با یه پیغام توقف برنامه روبرو میشم و از برنامه در میاد
حلقه for در کد زیر چه ایرادی داره؟
اصلا آیا راه حلی هست که عکسهای درون پوشه حافظه را به همراه توضیحات مربوطه در یک لیست ویو نمایش بدم؟ اگه واسه این کدی داشته باشید ممنون میشم

کد:
import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.widget.ListView;
import android.widget.Toast;

public class Recive_Activity8 extends Activity {

    
    String str_path11;
    Bitmap bitmap;
    Drawable d;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recive_activity8);

        ListView lista = (ListView) findViewById(R.id.listView1_recive_activity8);
        ArrayList<Directivo> arraydir = new ArrayList<Directivo>();
        Directivo directivo;

        // Introduzco los datos
        

        
        str_path11 = Environment.getExternalStorageDirectory().getPath()+"/01mypicture/e.jpg";

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        bitmap = BitmapFactory.decodeFile(str_path11, options);
        d = new BitmapDrawable(getResources(), bitmap);

        
        
        for (int i=0;i<3;i++){

        directivo = new Directivo(d, "text1", "text2");
        arraydir.add(directivo);
        }

        
        
        
        directivo = new Directivo(getResources().getDrawable(R.drawable.ariannahuffington), "Arianna Huffington", "Presidenta");
        arraydir.add(directivo);
        directivo = new Directivo(getResources().getDrawable(R.drawable.corinna), "Princesa Corinna", "CEO");
        arraydir.add(directivo);
        directivo = new Directivo(getResources().getDrawable(R.drawable.hillaryclinton), "Hillary Clinton", "Tesorera");
        arraydir.add(directivo);
        directivo = new Directivo(getResources().getDrawable(R.drawable.bono), "Bono el de U2", "Amenizador");
        arraydir.add(directivo);
        directivo = new Directivo(getResources().getDrawable(R.drawable.carmenmairena), "Carmen de Mairena", "Directora RRHH");
        arraydir.add(directivo);

        // Creo el adapter personalizado
        AdapterDirectivos adapter = new AdapterDirectivos(this, arraydir);

        // Lo aplico
        lista.setAdapter(adapter);


    }

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

}



کد آداپتر

کد:
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AdapterDirectivos extends BaseAdapter{
    
    protected Activity activity;
    protected ArrayList<Directivo> items;

    public AdapterDirectivos(Activity activity, ArrayList<Directivo> items) {
        this.activity = activity;
        this.items = items;
      }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int arg0) {
        return items.get(arg0);
    }
    
    @Override
    public long getItemId(int position) {
        return items.get(position).getId();
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        
        // Generamos una convertView por motivos de eficiencia
        View v = convertView;
        
        //Asociamos el layout de la lista que hemos creado
        if(convertView == null){
            LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inf.inflate(R.layout.custom_list1, null);
        }
        
        // Creamos un objeto directivo
        Directivo dir = items.get(position);
        //Rellenamos la fotografأ­a
        ImageView foto = (ImageView) v.findViewById(R.id.foto);
        foto.setImageDrawable(dir.getFoto());
        //Rellenamos el nombre
        TextView nombre = (TextView) v.findViewById(R.id.nombre);
        nombre.setText(dir.getNombre());
        //Rellenamos el cargo
        TextView cargo = (TextView) v.findViewById(R.id.cargo);
        cargo.setText(dir.getCargo());
        
        // Retornamos la vista
        return v;
    }
}



کد کلاس کمکی مربوط به آداپتر

کد:
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

public class Directivo {
    protected Drawable foto;
    
    protected Bitmap foto_bitmap;
    
    
    protected String nombre;
    protected String cargo;
    protected long id;
    
    public Directivo(Drawable foto, String nombre, String cargo) {
        super();
        this.foto = foto;
        this.nombre = nombre;
        this.cargo = cargo;
    }

    public Directivo(Drawable foto, String nombre, String cargo, long id) {
        super();
        this.foto = foto;
        this.nombre = nombre;
        this.cargo = cargo;
        this.id = id;
    }
    
    public void Directivo_Bitmap(Bitmap foto_bitmap, String nombre, String cargo) {

        this.foto_bitmap = foto_bitmap;
        this.nombre = nombre;
        this.cargo = cargo;

    }

    public Drawable getFoto() {
        return foto;
    }
    
    public Bitmap getFoto_bitmap() {
        return foto_bitmap;
    }

    public void setFoto(Drawable foto) {
        this.foto = foto;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}
دوست عزیز شما بهتر زمانی که برنامه متوقف میشه ،لوگ کت نگاه کنید و پیغامهای اون رو اینجا قرار بدید تا دوستان بتونند بفهمند مشکل چیه.
اینکه میگید روی شبیه ساز انجام شده .ولی روی گوشی نه.مطمئن شید که در آدرس مربوطه عکسی وجود داره در گوشی؟
در کل باید لوگ کت قرار بدید.وگرنه کار به جایی نمیبرید.
ممنون از توجهتون
هر مشکلی هست مربوط به تکه کد زیر هست

کد:
       for (int i=0;i<3;i++){

       directivo = new Directivo(d, "text1", "text2");
       arraydir.add(directivo);
       }

اینجور که خودم متوجه شدم اگر کد زیر را از داخل حلقه بیارم بیرون خطا نمیده

کد:
 directivo = new Directivo(d, "text1", "text2");
پس از کلی سعی و خطا و تو اینترنت گشتن
مشکل از اینجا بوده که حافظه رم گوشی جوابگوی عکس با سایز بزرگ نبوده و باید عکسها را قبل از اینکه در لیست ویو نمایش داده بشن تغییر سایز داد

لطفا دوستان بگن راه اصولی این موضوع یعنی نمایش عکسهای که در یک فولدر خاصی هستند در یک لیست ویو چی هست؟
سلام
اگر اندازه و سایز عکس براتون مهم  باید از فشرده سازی عکس استفاده کنید و کیفیت عکسها رو کم کنید 

Bitmap.Compress

اگر کیفیت تصاویر برای شما مهم هستش ، پس باید اندازه و سایز تصاویر رو کم کنید
مباحث scaling تصاویر در 
Bitmap.options
کد مربوط به تغییر اندازه و سایز تصویر

کد:
Bitmap bitmapImage = BitmapFactory.decodeFile("Your path");
int nh = (int) ( bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
your_imageview.setImageBitmap(scaled);

کد مربوط به کم کردن حجم عکس یا فشرده سازی بدون افت کیفیت

کد:
public String compressImage(String imageUri) {

      String filePath = getRealPathFromURI(imageUri);
      Bitmap scaledBitmap = null;

      BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
      options.inJustDecodeBounds = true;
      Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

      int actualHeight = options.outHeight;
      int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

      float maxHeight = 816.0f;
      float maxWidth = 612.0f;
      float imgRatio = actualWidth / actualHeight;
      float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

      if (actualHeight > maxHeight || actualWidth > maxWidth) {
          if (imgRatio < maxRatio) {
              imgRatio = maxHeight / actualHeight;
              actualWidth = (int) (imgRatio * actualWidth);
              actualHeight = (int) maxHeight;
          } else if (imgRatio > maxRatio) {
              imgRatio = maxWidth / actualWidth;
              actualHeight = (int) (imgRatio * actualHeight);
              actualWidth = (int) maxWidth;
          } else {
              actualHeight = (int) maxHeight;
              actualWidth = (int) maxWidth;

          }
      }

//      setting inSampleSize value allows to load a scaled down version of the original image

      options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
      options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
      options.inPurgeable = true;
      options.inInputShareable = true;
      options.inTempStorage = new byte[16 * 1024];

      try {
//          load the bitmap from its path
          bmp = BitmapFactory.decodeFile(filePath, options);
      } catch (OutOfMemoryError exception) {
          exception.printStackTrace();

      }
      try {
          scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
      } catch (OutOfMemoryError exception) {
          exception.printStackTrace();
      }

      float ratioX = actualWidth / (float) options.outWidth;
      float ratioY = actualHeight / (float) options.outHeight;
      float middleX = actualWidth / 2.0f;
      float middleY = actualHeight / 2.0f;

      Matrix scaleMatrix = new Matrix();
      scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

      Canvas canvas = new Canvas(scaledBitmap);
      canvas.setMatrix(scaleMatrix);
      canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
      ExifInterface exif;
      try {
          exif = new ExifInterface(filePath);

          int orientation = exif.getAttributeInt(
                  ExifInterface.TAG_ORIENTATION, 0);
          Log.d("EXIF", "Exif: " + orientation);
          Matrix matrix = new Matrix();
          if (orientation == 6) {
              matrix.postRotate(90);
              Log.d("EXIF", "Exif: " + orientation);
          } else if (orientation == 3) {
              matrix.postRotate(180);
              Log.d("EXIF", "Exif: " + orientation);
          } else if (orientation == 8) {
              matrix.postRotate(270);
              Log.d("EXIF", "Exif: " + orientation);
          }
          scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                  scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                  true);
      } catch (IOException e) {
          e.printStackTrace();
      }

      FileOutputStream out = null;
      String filename = getFilename();
      try {
          out = new FileOutputStream(filename);

//          write the compressed bitmap at the destination specified by filename.
          scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }

      return filename;

  }

  public String getFilename() {
      File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
      if (!file.exists()) {
          file.mkdirs();
      }
      String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
      return uriSting;

  }

  private String getRealPathFromURI(String contentURI) {
      Uri contentUri = Uri.parse(contentURI);
      Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
      if (cursor == null) {
          return contentUri.getPath();
      } else {
          cursor.moveToFirst();
          int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
          return cursor.getString(index);
      }
  }

  public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;

      if (height > reqHeight || width > reqWidth) {
          final int heightRatio = Math.round((float) height / (float) reqHeight);
          final int widthRatio = Math.round((float) width / (float) reqWidth);
          inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
      }
      final float totalPixels = width * height;
      final float totalReqPixelsCap = reqWidth * reqHeight * 2;
      while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
          inSampleSize++;
      }

      return inSampleSize;
  }