2013-04-06 2 views
1

여기 데이터베이스에서 그림 경로가 저장됩니다. 그래서 나는 경로의 도움으로 gridview에있는 이미지를 보여주고 있습니다. 그러나 아래 코드에서 볼 수 있듯이 을 asynctask에로드하고 있습니다. 문제는 처음으로 모든 이미지가로드 될 때까지 시간이 걸리는 것이 좋습니다.simplecursoradapter에 대한 지연로드 구현

그러나 사용자가 데이터베이스에 또 하나의 그림을 추가하는 경우, 다시 나는 또한 추가 된 사진을 볼 수 있도록 onResume()asynctask을 유지 모든 이미지를로드하는 데 많은 시간이 걸립니다. 사용자가 각 사진을 추가 할 때도 마찬가지입니다. 누군가가 다시 모든 사진을로드하지 않고도 gridview에서 마지막으로 추가 한 그림을 볼 수있는 간단한 방법을 제안 할 수 있습니까? 아니면 적어도 가능하다면 현재 cursoradapter에 게으른 어댑터를 구현하는 데 도움이 될 수 있습니까?

public class ImagesScreen extends Activity { 
    public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.images_screen); 
        gridView = (GridView)findViewById(R.id.gridView1); 
      String[] from = new String[] { Reminders.MOM_PATHS }; 
      int[] to = new int[] {}; 
      dbCon = new SQLiteConnectClass(ImagesScreen.this); 

      imageCursorAdapter = new ImageCursorAdapter(ImagesScreen.this, R.layout.griditem, null, from, to); 
      gridView.setAdapter(imageCursorAdapter); 

     } 

      protected void onResume() { 
      super.onResume(); 
      new GetImages().execute((Object[]) null); 
     } 

     private class GetImages extends AsyncTask<Object, Object, Cursor> { 

      @Override 
      protected Cursor doInBackground(Object... params) { 
       return dbCon.getAllImages(); 
      } 

      @Override 
      protected void onPostExecute(Cursor result) { 
       imageAdapter.changeCursor(result); 
      } 

public void addpictures(View view){ 
    // code for adding picture paths to the database by transferring to another activity. 
} 


     } 

CustomAdapter 클래스 :

public class ImageCursorAdapter extends SimpleCursorAdapter{ 

     private int layout; 
     private LayoutInflater mLayoutInflater; 
     private Context mContext; 

     public ImageAdapter(Context context, int layout, Cursor c,String[] from, int[] to) { 
      super(context, layout, c, from, to,0); 
      this.layout = layout; 
      mLayoutInflater=LayoutInflater.from(context); 
      mContext = context; 
     } 

     public View newView(Context context, Cursor cursor, ViewGroup parent) {  
      View v = mLayoutInflater.inflate(layout, parent, false); 
      return v; 
     } 

     public void bindView(final View v, final Context context, Cursor c) { 
      final int id = c.getInt(c.getColumnIndex("id")); 
      final String imagepath = c.getString(c.getColumnIndex("paths")); 


      ImageView imageview = (ImageView)v.findViewById(R.id.imageView1); 

      File imgFile = new File(imagepath); 
      if(imgFile.exists()){ 

       Bitmap imageBitmap = decodeFile(imgFile); 
       imageview.setImageBitmap(imageBitmap); 
      } 

     } 
} 
+0

이 예제를보십시오 http://stackoverflow.com/a/3068012/964741 –

+0

왜 커서 어댑터 대신 기본 어댑터를 사용할 수 없습니다. – Senthil

+0

@RajaReddyPolamReddy 간단한 어댑터가 아닌 내 cursror adpater에서 구현하는 방법에 대한 도움을받을 수 있습니까? – Apparatus

답변

0

사용 Android-Universal-Image-Loader

ImageView imageview = (ImageView)v.findViewById(R.id.imageView1); 

    File imgFile = new File(imagepath); 
     if(imgFile.exists()){ 
       imageLoader.displayImage(imageUri(ur file path), imageView); 
       } 
+0

감사합니다. 이 메소드 displayimage()를 사용하기 위해 해당 라이브러리에서 사용해야하는 코드 부분을 알려주시겠습니까? 많이 있으니? – Apparatus

4

사용이 코드를 설정

public class Imagegallery extends Activity implements OnItemClickListener, 
    OnScrollListener, OnTouchListener { 
Button btn; 

SQLiteDatabase sampleDB = null; 
String SAMPLE_DB_NAME = "hic"; 

int size = 0; 
TextView headertext; 
Button cartbtn; 

ImageView footer1, footer2, footer3, footer4, footer5; 

GridView gridView; 

boolean larg = false; 
String products; 
int j = 1; 
int ii = 0; 
String imagepath[]; 
String productname[]; 
int productid[] = new int[1000]; 

String productids[] = new String[1000]; 
int integerprodids[] = new int[1000]; 
final Context context = this; 
String filename2[]; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.currentspecial); 

    File root = new File(Environment.getExternalStorageDirectory() 
      + File.separator + "aiwhic/product" + File.separator); 
    File[] fileName = root.listFiles(); 
    filename2 = new String[fileName.length]; 
    for (int j = 0; j < fileName.length; j++) { 
     Uri uri = Uri.fromFile(fileName[j]); 
     filename2[j] = fileName[j].getAbsolutePath(); 

     Log.e("file", filename2[j]); 
    } 

    gridView = (GridView) findViewById(R.id.gridView1); 

    gridView.setAdapter(new ImageAdapter(this, filename2, filename2)); 

    gridView.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View v, 
       int position, long id) { 

      int isf = filename2[position].lastIndexOf("/"); 
      int laf = filename2[position].lastIndexOf("."); 
      String filename = filename2[position].substring(isf + 1, laf); 
      int pos = Integer.parseInt(filename); 
      Intent go = new Intent(Imagegallery.this, ItemsPage.class); 
      Bundle bundle = new Bundle(); 

      bundle.putInt("position", pos); 
      bundle.putString("whichclass", "imagegallery"); 
      bundle.putInt("catid", 2); 
      go.putExtras(bundle); 
      startActivity(go); 

     } 
    }); 

} 

public class ImageAdapter extends BaseAdapter { 
    private Context context; 
    private final String[] mobileValues; 
    private final String[] mobileimages; 

    public ImageAdapter(Context context, String[] mobileValues, String[] mo) { 
     this.context = context; 
     this.mobileValues = mobileValues; 
     this.mobileimages = mo; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 

     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View gridView; 

     if (convertView == null) { 

      gridView = new View(context); 

      gridView = inflater.inflate(R.layout.currentspeciallist, null); 

      TextView textView = (TextView) gridView 
        .findViewById(R.id.textView1); 
      textView.setText(mobileValues[position]); 
      textView.setVisibility(View.INVISIBLE); 
      ImageView imageView = (ImageView) gridView 
        .findViewById(R.id.imageView1); 

      imageView.setTag(mobileimages[position]); 
      new Loadimage().execute(imageView); 
      // imageView.setImageBitmap(BitmapFactory 
      // .decodeFile(mobileimages[position])); 

     } else { 
      gridView = (View) convertView; 
     } 

     return gridView; 
    } 

    public int getCount() { 
     return mobileimages.length; 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

} 

class Loadimage extends AsyncTask<Object, Void, Bitmap> { 

    private ImageView imv; 
    private String path; 

    @Override 
    protected Bitmap doInBackground(Object... params) { 

     imv = (ImageView) params[0]; 

     path = imv.getTag().toString(); 

     // Bitmap thumb = BitmapFactory.decodeFile(path); 
     BitmapFactory.Options opts = new BitmapFactory.Options(); 

     opts.inSampleSize = 2; // for 1/2 the image to be loaded 
     Bitmap thumb = Bitmap.createScaledBitmap(
       BitmapFactory.decodeFile(path, opts), 120, 120, false); 

     return thumb; 

    } 

    @Override 
    protected void onPostExecute(Bitmap bitmap) { 
     if (!imv.getTag().toString().equals(path)) { 
      /* 
      * The path is not same. This means that this image view is 
      * handled by some other async task. We don't do anything and 
      * return. 
      */ 
      return; 
     } 

     if (bitmap != null && imv != null) { 
      imv.setVisibility(View.VISIBLE); 
      imv.setImageBitmap(bitmap); 
     } else { 
      imv.setVisibility(View.GONE); 
     } 
    } 

} 

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 

} 

다음 xml을 만듭니다.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/RelativeLayout1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="5dp" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:src="@drawable/ic_launcher" > 
    </ImageView> 
</RelativeLayout> 

파일 경로를 직접 가져 오는 중입니다. 그냥 sqlite에서 이름을 얻고 배열 문자열을 전달

+0

+1 귀하의 노력에 감사드립니다. 하지만 당신의 코드는 아무런 차이가없는 광산처럼 asynctask를 사용합니다. 모든 이미지의 다운로드가 완료되지 않으면 이미지를 가져 오지 않습니다. – Apparatus

+0

도움을 주셔서 감사합니다. –