2016-02-25 113 views
0

我想做一个有2个按钮的应用程序。使用OPEN CAMERA,我们使用相机意图拍照,并将其转换为base64编码并存储在服务器上。 使用GET PICTURE,我们尝试从服务器获取图片并使用universalimageloader将其显示在imageview中。 第一部分,即存储图片工作正常,但我无法下载图像并将其显示在图像视图中。使用通用图像加载器,但图像获取只加载一次

package backbenchersbeta.task; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 

import android.preference.PreferenceActivity; 
import android.util.Base64; 
import android.app.Activity; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Environment; 
import android.provider.MediaStore; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.Toast; 
import com.loopj.android.http.AsyncHttpClient; 
import com.loopj.android.http.AsyncHttpResponseHandler; 
import com.loopj.android.http.RequestParams; 
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; 
import com.nostra13.universalimageloader.core.ImageLoader; 
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; 
import com.nostra13.universalimageloader.core.assist.QueueProcessingType; 
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; 
import com.nostra13.universalimageloader.core.DisplayImageOptions; 
import com.nostra13.universalimageloader.core.assist.ImageScaleType; 
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; 
import com.nostra13.universalimageloader.core.imageaware.ImageAware; 
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware; 


import cz.msebera.android.httpclient.Header; 

public class MainActivity extends Activity { 

    static int TAKE_PIC =1; 
    Uri outPutfileUri; 
    RequestParams params = new RequestParams(); 
    ProgressDialog prgDialog; 



     @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
      DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() 
        .cacheOnDisc(true).cacheInMemory(true) 
        .imageScaleType(ImageScaleType.EXACTLY) 
        .displayer(new FadeInBitmapDisplayer(300)).build(); 

      ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
        getApplicationContext()) 
        .defaultDisplayImageOptions(defaultOptions) 
        .memoryCache(new WeakMemoryCache()) 
        .discCacheSize(100 * 1024 * 1024).build(); 

      ImageLoader.getInstance().init(config); 

      prgDialog = new ProgressDialog(this); 
     // Set Cancelable as False 
     prgDialog.setCancelable(false); 

    } 
    public void CameraClick(View v) { 

     Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     File f= new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); 

     outPutfileUri = Uri.fromFile(f); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri); 
     params.put("filename", "temp.jpg"); 

     Toast.makeText(getApplicationContext(), "Taking pic", 
       Toast.LENGTH_LONG).show(); 
     startActivityForResult(intent, TAKE_PIC); 



    } 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode,Intent data) 
    { 
     if (requestCode == TAKE_PIC && resultCode==RESULT_OK){ 
      File f = new File(Environment.getExternalStorageDirectory().toString()); 
      for (File temp : f.listFiles()) { 
       if (temp.getName().equals("temp.jpg")) { 
        f = temp; 
        break; 
       } 
      } 
      try { 

       Bitmap bitmap; 
       BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 
       Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show(); 
       prgDialog.setMessage("Converting Image to Binary Data"); 
       prgDialog.show(); 
       bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions); 

       Toast.makeText(getApplicationContext(), "Started converting", 
         Toast.LENGTH_LONG).show(); 

      ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao); 
      byte[] ba = bao.toByteArray(); 
      String ba1=Base64.encodeToString(ba,Base64.DEFAULT); 
      prgDialog.setMessage("Calling Upload"); 
      params.put("image", ba1); 

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

     } 
    } 
    public void triggerImageUpload() { 
     makeHTTPCall(); 
    } 

    public void makeHTTPCall() { 
     prgDialog.setMessage("Invoking Php"); 
     AsyncHttpClient client = new AsyncHttpClient(); 
     // Don't forget to change the IP address to your LAN address. Port no as well. 
     client.post("http://192.168.43.145:80/imgupload/upload_image.php", 
       params, new AsyncHttpResponseHandler() { 
        // When the response returned by REST has Http 
        // response code '200' 
        @Override 
        public void onSuccess(int statusCode, Header[] headers, byte[] response) { 
         prgDialog.hide(); 
         Toast.makeText(getApplicationContext(), "Done", 
           Toast.LENGTH_LONG).show(); 
        } 

        // When the response returned by REST has Http 
        // response code other than '200' such as '404', 
        // '500' or '403' etc 
        @Override 
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { 

         prgDialog.hide(); 
         if (statusCode == 404) { 
          Toast.makeText(getApplicationContext(), 
            "Requested resource not found", 
            Toast.LENGTH_LONG).show(); 
         } 
         // When Http response code is '500' 
         else if (statusCode == 500) { 
          Toast.makeText(getApplicationContext(), 
            "Something went wrong at server end", 
            Toast.LENGTH_LONG).show(); 
         } 
         // When Http response code other than 404, 500 
         else { 
          Toast.makeText(
            getApplicationContext(), 
            "Error Occured n Most Common Error: n1. Device not connected to Internetn2. Web App is not deployed in App servern3. App server is not running HTTP Status code : " 
              + statusCode, Toast.LENGTH_LONG) 
            .show(); 
         } 
        } 
       }); 
    } 

    public void GetPicture(View v) { 
     String url="http://192.168.43.145:80/imgupload/uploadedimages/temp.jpg"; 
     Toast.makeText(getApplicationContext(), "Inside getpic", 
       Toast.LENGTH_LONG).show(); 
     ImageLoader imageLoader = ImageLoader.getInstance(); 
     DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true) 
       .cacheOnDisc(true).resetViewBeforeLoading(true) 
       .build(); 
     ImageView img = (ImageView) findViewById(R.id.imageView); 
     ImageAware imageAware = new ImageViewAware(img, false); 

     imageLoader.displayImage(url,img,options); 
     /*Bitmap bitmap = DownloadImage(
      "http://192.168.43.145:80/imgupload/uploadedimages/temp.jpg"); 
     ImageView img = (ImageView) findViewById(R.id.imageView); 
     img.setImageBitmap(bitmap);*/ 
    } 
    private InputStream OpenHttpConnection(String urlString) 
      throws IOException 
    {Toast.makeText(getApplicationContext(), "Inside imputstream", 
      Toast.LENGTH_LONG).show(); 
     InputStream in = null; 
     int response = -1; 

     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 

     if (!(conn instanceof HttpURLConnection)) 
      throw new IOException("Not an HTTP connection"); 

     try{ 
      HttpURLConnection httpConn = (HttpURLConnection) conn; 
      httpConn.setAllowUserInteraction(false); 
      httpConn.setInstanceFollowRedirects(true); 
      Toast.makeText(getApplicationContext(), "Inside tryblock1", 
        Toast.LENGTH_LONG).show(); 
      httpConn.setRequestMethod("GET"); 
      Toast.makeText(getApplicationContext(), "Inside tryblock2", 
        Toast.LENGTH_LONG).show(); 
      httpConn.connect(); 
      Toast.makeText(getApplicationContext(), "Inside tryblock3", 
        Toast.LENGTH_LONG).show(); 

      response = httpConn.getResponseCode(); 
      if (response == HttpURLConnection.HTTP_OK) { 
       in = httpConn.getInputStream(); 
      } 
     } 
     catch (Exception ex) 
     { 
      throw new IOException("Error connecting"); 
     } 
     return in; 
    } 
    public static void initImageLoader(Context context) { 

     // ImageLoaderConfiguration.createDefault(this); 

       ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context); 
      config.threadPriority(Thread.NORM_PRIORITY - 2); 
       config.denyCacheImageMultipleSizesInMemory(); 
       config.diskCacheFileNameGenerator(new Md5FileNameGenerator()); 

       config.tasksProcessingOrder(QueueProcessingType.LIFO); 
       config.writeDebugLogs(); // Remove for release app 


       // Initialize ImageLoader with configuration. 

      ImageLoader.getInstance().init(config.build()); 
      } 

    private Bitmap DownloadImage(String URL) 
    {Toast.makeText(getApplicationContext(), "Inside dowmloadimage", 
      Toast.LENGTH_LONG).show(); 
     Bitmap bitmap = null; 
     InputStream in = null; 
     try { 
      in = OpenHttpConnection(URL); 
      bitmap = BitmapFactory.decodeStream(in); 
      in.close(); 
     } catch (IOException e1) { 
// TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     return bitmap; 
    } 



    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     // Dismiss the progress bar when application is closed 
     if (prgDialog != null) { 
      prgDialog.dismiss(); 
     } 
    } 


} 

布局文件是

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="backbenchersbeta.task.MainActivity"> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:gravity="center" 
     android:layout_gravity="center" 
     android:layout_marginTop="100dp" 
     android:text="Open Camera" 
     android:onClick="CameraClick" 
     android:background="#0054a6" 
     android:padding="15dp" 
     android:textColor="#ffffff"/> 
    <Button 
     android:id="@+id/button2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:layout_gravity="center" 
     android:text="Get Picture" 
     android:onClick="GetPicture" 
     android:background="#0054a6" 
     android:padding="15dp" 
     android:textColor="#ffffff" 
     android:layout_alignTop="@+id/button1" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" /> 

    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageView" 
     android:layout_below="@+id/button1" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="106dp" /> 

</RelativeLayout> 

的问题是,虽然图像是越来越显示一次,但下一张照片后,它没有得到,甚至点击获取图片后改变。

+0

使用IDE调试可以更有效地完成调试,添加断点并检查代码和输出,同时,为什么不尝试使用通用图像加载器,这是一个好的库。 – Yazan

+0

我正在探索图书馆。我还添加了2个新的敬酒,发现httpConn.connect();不能正常工作..请你看看它 – BBenchers

+0

它显示“内部getpic”吗? –

回答

0

在Getpicture中我做了以下修改

DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(false) .cacheOnDisc(false).resetViewBeforeLoading(true).build(); 

因为正在显示缓存中存储图像时出现的问题。

相关问题