0

当我滚动 GridView 时,图像会在其中消失。在日志猫它也显示内存不足我不知道我在这里做错了什么。!显示图像也需要很长时间。提前致谢。

BaseActivity.java

public class BaseActivity extends Activity{


private Context context = this;
boolean server_connection = false;

static final Comparator<HashMap<String, String>> byDate = new Comparator<HashMap<String, String>>() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
        Date d1 = null;
        Date d2 = null;

        try {
            if(ord1.get("datetime")!=null){
                d1 = sdf.parse(ord1.get("datetime"));
            }
            else{
                d1 = sdf.parse("1970-01-01 00:00:00");
            }
            if(ord2.get("datetime")!=null){
                d2 = sdf.parse(ord2.get("datetime"));
            }
            else{
                d2 = sdf.parse("1970-01-01 00:00:00");
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //Log.d("Date", ""+d1+"..........."+d2);
        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
        //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

static final Comparator<HashMap<String, String>> byCount = new Comparator<HashMap<String, String>>() {

    public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {

        int c1,c2;
        if(ord1.get("download_count")!=null && !ord1.get("download_count").equals("null")){
            c1=Integer.parseInt(ord1.get("download_count"));
        }
        else{c1=0;}
        if(ord2.get("download_count")!=null && !ord2.get("download_count").equals("null")){
            c2=Integer.parseInt(ord2.get("download_count"));
        }
        else{c2=0;}

        return (c1>c2 ? -1 : 1);     //descending
    }
};

public boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public String prepareWebserviceRequest(String methodname, String[] keys, String[] values) throws JSONException{
    String retStr = null;
    String strParams = null;
    JSONObject json = new JSONObject();
    for(int i=0;i<keys.length;i++){
        json.put(keys[i],values[i]);
    }

    JSONObject fJson = new JSONObject();
    fJson.put("method_name", methodname);
    fJson.put("body", json);
    retStr = fJson.toString();
    return retStr;
}

public String prepareWebserviceRequestOnlyMethod(String methodname) throws JSONException{
    String retStr = null;
    String strParams = null;
    JSONObject json = new JSONObject();


    JSONObject fJson = new JSONObject();
    fJson.put("method_name", methodname);
    //  fJson.put("body", json);
    retStr = fJson.toString();
    return retStr;
}

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);
    // RECREATE THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

class Download extends AsyncTask<String, Void, Bitmap>{

    @Override
    protected Bitmap doInBackground(String... params) {
        // TODO Auto-generated method stub
        Bitmap bmp=null;
        bmp = getBitmapFromURL(params[0]);
        return bmp;
    }

}

public void WriteFile(String path,String filename,String data) {
    try{
        File direct = new File(path);

        if(!direct.exists())
        {
            direct.mkdir();//directory is created;
        }
        String fpath= path +filename;
        File txtfile=new File(fpath);

        txtfile.createNewFile();
        FileOutputStream fout=new FileOutputStream(txtfile);
        OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
        myoutwriter.write(data);
        myoutwriter.close();
        fout.close();

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

public String ReadFile(String path,String filename)
{   File myFile = new File(path + filename);
if(!myFile.exists())
{
    return null;
}
FileInputStream fIn = null;
try {
    fIn = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(
        new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
try {
    while ((aDataRow = myReader.readLine()) != null) {
        aBuffer += aDataRow + "\n";
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return aBuffer;
}
public boolean FileExist(String filename)
{
    String PATH2 = Environment.getExternalStorageDirectory() + "/"+Constant.Alert_Name+filename;
    Log.v("log_tag initial path", "PATH: " + PATH2);
    File file2 = new File(PATH2);
    if(file2.exists()==true)
    {
        return true;
    }
    return false;
}

public String callAPI(String strRequest) {
    String result = null;
    String new_params;
    int ResponseCode;

    // TODO Auto-generated method stub
    try {
        JSONObject json = new JSONObject();

        HttpParams httpParams = new BasicHttpParams();


        httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
        //httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
        httpParams.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        HttpClient client = new DefaultHttpClient(cm,httpParams);

        String url = Constant.WebService_URL;
        //String url = "http://192.168.1.3/messages_app/main.php";
        URL url1 = new URL(Constant.WebService_URL);
        // URL url1 = new URL("http://192.168.1.3/messages_app/main.php");


        HttpPost request = new HttpPost(url);
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");

        new_params =strRequest;
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        //nameValuePairs.add(new BasicNameValuePair("json","{\"method_name\":\"get_all_category\"}"));
        nameValuePairs.add(new BasicNameValuePair("json",new_params));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //      request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
        request.setHeader("json", json.toString());

        HttpResponse response = client.execute(request);

        ResponseCode = response.getStatusLine().getStatusCode();
        //Log.d("ResponseCode", ""+ResponseCode);
        if(ResponseCode==200){
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            if (entity != null) {
                InputStream instream = entity.getContent();

                result = RestClient.convertStreamToString(instream);
                //  Log.i("Read from server", result);
            }
        }

        else if(ResponseCode!=200){
            return "Server down";
        }



    } catch (Throwable t) {
        return null;
    }
    return result;
}


}

LazyAdapter.java

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader; 
DisplayImageOptions options;
ArrayList<HashMap<String, String>> list;

public LazyAdapter(Activity a,ArrayList<HashMap<String, String>> list) {
    this.list=list;
    activity = a;
    inflater = (LayoutInflater)LayoutInflater.from(a);
    File cacheDir = StorageUtils.getOwnCacheDirectory(a, "Download");


    // Get singletone instance of ImageLoader
    imageLoader = ImageLoader.getInstance();
    // Create configuration for ImageLoader (all options are optional)
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
    // You can pass your own memory cache implementation
    .memoryCacheExtraOptions(480,800)
    .denyCacheImageMultipleSizesInMemory()
    .discCacheExtraOptions(480, 480, CompressFormat.PNG, 100)
    .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache       
    .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
    .enableLogging()
    .build();
    // Initialize ImageLoader with created configuration. Do it once.
    imageLoader.init(config);
    //imageLoader.init(ImageLoaderConfiguration.createDefault(a));
    // imageLoader=new ImageLoader(activity.getApplicationContext());
    options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.stub_image)

    .cacheInMemory()
  //        .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(20))
    .build();
}



public int getCount() {
    return list.size();
}

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

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

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder vh;
    if(convertView==null)
    {
        vh = new ViewHolder();
        convertView= inflater.inflate(R.layout.other, parent,false);   
        vh.iv=(ImageView)convertView.findViewById(R.id.picture); 
        vh.pb= (ProgressBar)convertView.findViewById(R.id.pb); 
        vh.tv = (TextView)convertView.findViewById(R.id.text);
        convertView.setTag(vh); 
    } else { 
        vh = (ViewHolder) convertView.getTag(); 
    } 
 //     vh.tv.setText("Image in postion ="+position);
    if(Global.getCurrent_tab()==1){
        vh.tv.setText(""+list.get(position).get("download_count"));
    }
    display(vh.iv, Constant.img_URL+list.get(position).get("photo_name"), vh.pb);

    return convertView;
}

public void display(ImageView img, String url, final ProgressBar pb)
{
    imageLoader.displayImage(url, img, options, new ImageLoadingListener() {


        @Override
        public void onLoadingCancelled() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingComplete(Bitmap arg0) {
            // TODO Auto-generated method stub
            pb.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingFailed(FailReason arg0) {
            // TODO Auto-generated method stub
            pb.setVisibility(View.GONE);

        }

        @Override
        public void onLoadingStarted() {
            // TODO Auto-generated method stub
            pb.setVisibility(View.VISIBLE);



        }

    });
}
static class ViewHolder
{
    ImageView iv;
    TextView tv;
    ProgressBar pb;

}
 }

DefaultGridView.java

public class DefaultGridView  extends Activity {

GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.latestphotos);
        gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setAdapter(new LazyAdapter(DefaultGridView.this,Global.getPhotos_list()));
        gridView.setOnItemClickListener(new OnItemClickListener()
        {

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

                String url =Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name");
                Intent i = new Intent(DefaultGridView.this, FullImageActivity.class);
                i.putExtra("idkey", url); // pass the id
                startActivity(i);
            }

        });

    }

}

FullImageActivity.java

public class FullImageActivity extends Activity {



Button download, setaswallpaper, reportissue;
String url1;
Bitmap myBitmap;
ImageDownloader mDownloader;
FileOutputStream fos;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_image);
    setaswallpaper = (Button) findViewById(R.id.setaswallpaper);
    download = (Button)findViewById(R.id.download);
    reportissue = (Button)findViewById(R.id.reportissue);


    final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    url1 = getIntent().getStringExtra("idkey"); //get id
    Log.i(".............",""+url1);
    //imageView.setImageResource(id);
    new Thread( new Runnable()
    {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try
            {
            URL url = new URL(url1.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            myBitmap = BitmapFactory.decodeStream(input);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            runOnUiThread( new Runnable()
            {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    imageView.setImageBitmap(myBitmap);
                }

            });
        }

    }).start();
    setaswallpaper.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             WallpaperManager myWallpaperManager
             = WallpaperManager.getInstance(getApplicationContext());
            try {
                myWallpaperManager.setBitmap(myBitmap);

                Toast.makeText(getApplicationContext(), "Wallpaper has been set...!!", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }

        }
    });


    download.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    saveImageToSD();
     //                         Toast.makeText(getApplicationContext(), "Wallpaper has been Downloaded...!!",     Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                }

            }
        });

    reportissue.setOnClickListener(new OnClickListener() {


        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Report Issue");
            intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
            intent.setData(Uri.parse("mailto:reportissue@gmail.com")); // or just "mailto:" for blank
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
            startActivity(intent);

        }
    });

}


private void saveImageToSD() {

    /*--- this method will save your downloaded image to SD card ---*/

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    /*--- you can select your preferred CompressFormat and quality. 
     * I'm going to use JPEG and 100% quality ---*/
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    /*--- create a new file on SD card ---*/
    long current = System.currentTimeMillis();
    File file = new File(Environment.getExternalStorageDirectory()
            + File.separator +  (current / 1000) + "wallpaper.jpg");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*--- create a new FileOutputStream and write bytes to file ---*/
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fos.write(bytes.toByteArray());
        fos.close();
        Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }

}



 }
4

0 回答 0