0

我制作了一个基于标签的应用程序。有三个选项卡。选项卡之一用于相机。因此,当我按下相机选项卡时,它会打开相机活动,以便我可以拍照。直到这里它工作正常。当我拍照时,那张照片会显示在 ImageView 中。从这里开始,当我按下任何其他选项卡然后按下相机选项卡时,相机活动不会启动。它不断向我展示 ImageView 上的前一张图像。我想要的是每当用户点击相机选项卡时,它应该打开相机活动。我怎样才能达到这个效果?

这是我的代码。下面是相机活动中的 os oncreate 方法。因此,当按下相机选项卡时,它会打开此活动。

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera);

    userFunctions = new UserFunctions();
    globalUID = getIntent().getExtras().getString("globalUID");
    Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
    ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
    bUpload = (Button)findViewById(R.id.bUpload);
    openCamera();
}

private void openCamera() {
    i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, CameraResult);
}

更新

我这样做了,但仍然是同样的问题

boolean flag = true;
@Override
protected void onResume() {
    super.onResume();
    //flag = true;
    if(flag) {
        openCamera();
        flag = false;
    }
}

编辑

在遵循伊姆兰的回答之后,我的代码现在看起来像这样。我还添加了额外的代码。但是这段代码仍然不起作用。

public class Camera extends Activity {
    ImageView ivUserImage;
    Button bUpload;
    Intent i;
    int CameraResult = 0;
    Bitmap bmp;
    public String globalUID;
    UserFunctions userFunctions;
    String photoName;
    InputStream is;
    String largeImagePath;
    int serverResponseCode = 0;
    public static boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

        userFunctions = new UserFunctions();
        globalUID = getIntent().getExtras().getString("globalUID");
        //flag = getIntent().getExtras().getBoolean("flag");
        Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
        ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
        bUpload = (Button)findViewById(R.id.bUpload);
        //openCamera();
        if(flag ==true)
            openCamera();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(flag==true)
            openCamera();
    }

    private void openCamera() {
        i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, CameraResult);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        flag = false;
        if(resultCode == RESULT_OK) {

            //set image taken from camera on ImageView
            Bundle extras = data.getExtras();
            bmp = (Bitmap) extras.get("data");
            ivUserImage.setImageBitmap(bmp);

            //Create new Cursor to obtain the file Path for the large image
            String[] largeFileProjection = {
                MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATA
            };

            String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
            Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);

            try {
                myCursor.moveToFirst();
                //This will actually give you the file path location of the image.
                largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));

                File f = new File("" + largeImagePath);

                photoName = f.getName();

                bUpload.setOnClickListener(new View.OnClickListener() {   
                    public void onClick(View v) {
                        new Upload().execute(largeImagePath, globalUID, photoName);
                    }

                });

            } finally {
                myCursor.close();
            }
        }
    }
}

这是我的标签活动代码

public class DashboardActivity extends TabActivity {
    UserFunctions userFunctions;
    public String globalUID;
    DatabaseHandler db;
    boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);

        db = new DatabaseHandler(getApplicationContext());
        // Check login status in database
        userFunctions = new UserFunctions();

        if(userFunctions.isUserLoggedIn(getApplicationContext())){
            //globalUID = getIntent().getExtras().getString("globalUID");
            HashMap<String, String> data = db.getUserDetails();
            globalUID = data.get("uid");
            Resources res = getResources(); // Resource object to get Drawables
            TabHost tabHost = getTabHost();  // The activity TabHost
            TabHost.TabSpec spec;  // Resusable TabSpec for each tab
            Intent intent;  // Reusable Intent for each tab

            //Home
            intent = new Intent(this, Home.class);
            intent.putExtra("globalUID", globalUID);
            spec = tabHost.newTabSpec("home").setIndicator("", res.getDrawable(R.drawable.home_icon)).setContent(intent);
            tabHost.addTab(spec);

            //Camera
            intent = new Intent(this, Camera.class);
            intent.putExtra("globalUID", globalUID);
            //intent.putExtra("flag", flag);
            spec = tabHost.newTabSpec("camera").setIndicator("", res.getDrawable(R.drawable.camera_icon)).setContent(intent);
            tabHost.addTab(spec);

            //Albums
            intent = new Intent(this, Albums.class);
            intent.putExtra("globalUID", globalUID);
            spec = tabHost.newTabSpec("albums").setIndicator("", res.getDrawable(R.drawable.albums_icon)).setContent(intent);
            tabHost.addTab(spec);

            //tabHost.setCurrentTab(1);
        } else {
            // user is not logged in show login screen
            Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            // Closing dashboard screen
            finish();
        }
    }   
}

这是我的整个相机活动

public class Camera extends Activity {
    ImageView ivUserImage;
    Button bUpload;
    Intent i;
    int CameraResult = 0;
    Bitmap bmp;
    public String globalUID;
    UserFunctions userFunctions;
    String photoName;
    InputStream is;
    String largeImagePath;
    int serverResponseCode = 0;
    public static boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

        userFunctions = new UserFunctions();
        globalUID = getIntent().getExtras().getString("globalUID");
        //flag = getIntent().getExtras().getBoolean("flag");
        Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
        ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
        bUpload = (Button)findViewById(R.id.bUpload);
        //openCamera();
        //if(flag ==true)
            openCamera();
    }
    /*
    @Override
    protected void onResume() {
        super.onResume();
        if(flag==true)
            openCamera();
    }*/

    private void openCamera() {
        i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, CameraResult);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        flag = false;
        if(resultCode == RESULT_OK) {

            //set image taken from camera on ImageView
            Bundle extras = data.getExtras();
            bmp = (Bitmap) extras.get("data");
            ivUserImage.setImageBitmap(bmp);

            //Create new Cursor to obtain the file Path for the large image
             String[] largeFileProjection = {
                     MediaStore.Images.ImageColumns._ID,
                     MediaStore.Images.ImageColumns.DATA
             };

             String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
             Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);

             try {
                 myCursor.moveToFirst();
                 //This will actually give you the file path location of the image.
                 largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));

                 File f = new File("" + largeImagePath);

                 photoName = f.getName();

                 bUpload.setOnClickListener(new View.OnClickListener() {   
                     public void onClick(View v) {
                         new Upload().execute(largeImagePath, globalUID, photoName);
                     }

                 });

             } finally {
                 myCursor.close();
             }
        }
    }

    public class Upload extends AsyncTask<String, Integer, String> {

        ProgressDialog dialog;

        protected void onPreExecute() {
            dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            String success = "false";
            Bitmap bitmapOrg = setImageToImageView(largeImagePath);//BitmapFactory.decodeFile(largeImagePath);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

            byte [] ba = bao.toByteArray();
            String ba1=Base64.encodeToString(ba, 0);

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("imageName", photoName));
            nameValuePairs.add(new BasicNameValuePair("uid", globalUID));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.example.info/android/fileupload.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                if(response != null) {
                    success = "true";
                }
                is = entity.getContent();
            } catch(Exception e) {
                Log.e("log_tag", "Error in http connection "+e.toString());
            }
            dialog.dismiss();
            return success;
        }

        protected void onProgressUpdate(Integer...progress) {

        }

        protected void onPostExecute(String f) {
            Toast.makeText(getApplicationContext(), "File uploaded", Toast.LENGTH_LONG).show();
        }

    }

    public Bitmap setImageToImageView(String filePath) { 
        // Decode image size 
        BitmapFactory.Options o = new BitmapFactory.Options(); 
        o.inJustDecodeBounds = true; 
        BitmapFactory.decodeFile(filePath, o); 

        // The new size we want to scale to 
        final int REQUIRED_SIZE = 1024; 

        // Find the correct scale value. It should be the power of 2. 
        int width_tmp = o.outWidth, height_tmp = o.outHeight; 
        int scale = 1; 
        while (true) { 
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) 
            break; 
            width_tmp /= 2; 
            height_tmp /= 2; 
            scale *= 2;
        } 

        // Decode with inSampleSize 
        BitmapFactory.Options o2 = new BitmapFactory.Options(); 
        o2.inSampleSize = scale; 
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2); 
        return bitmap;

    }

    public boolean fileData(String guid, String photoName) {
        Toast.makeText(getApplicationContext(), photoName, Toast.LENGTH_LONG).show();

        JSONObject json = userFunctions.uploadFileData(guid, photoName);

        try {
            if(Integer.parseInt(json.getString("success")) != 1) {
                Toast.makeText(getApplicationContext(), json.getInt("error_msg"), Toast.LENGTH_LONG).show();
                //register_error.setText(json.getString("error_msg"));
                return false;
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }
}
4

3 回答 3

0

这是因为当您在选项卡之间切换时,您的活动不会再次调用 onCreate。

尝试将呼叫转移到 openCamera(); 进入 onResume 方法,应该没问题。

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera);

    userFunctions = new UserFunctions();
    globalUID = getIntent().getExtras().getString("globalUID");
    Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
    ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
    bUpload = (Button)findViewById(R.id.bUpload);

}



protectd void onResume(){
      super.onResume();
      openCamera();
}

private void openCamera() {
    i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, CameraResult);
}
于 2012-06-23T13:58:36.427 回答
0

出于效率的原因,每个Activity人只TabHost调用一次。onCreate()这就是为什么openCamera()不会一次又一次地调用它的原因。

为了处理这个问题,您可以在父级Activity中实现并注册一个OnTabChangeListener,您可以在其中捕获单击了哪个选项卡并执行任何所需的操作。

希望这可以帮助!

于 2012-06-23T13:58:47.880 回答
0

添加onResume()您的活动并调用 openCamera(); 从 onResume() 也可以:

public static boolean flag = true;

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera);

    userFunctions = new UserFunctions();
    globalUID = getIntent().getExtras().getString("globalUID");
    Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
    ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
    bUpload = (Button)findViewById(R.id.bUpload);
if(flag ==true)
    openCamera();
}


       @Override
        protected void onResume() {
            super.onResume();
if(flag==true)
            openCamera();
        }

并在onActivityResut()

flag =false;

或在 tabclick

YourflagActivity.flag=true;
于 2012-06-23T14:00:38.250 回答