I'm making an app in which I pick image using Camera/Gallery Intent and then set it to ImageView. After that onTouch on the image(in ImageView) I get Hex, RGB and HSL values of the color of the touched pixel of the image.
This works well for the image imported the first time but when I import image second time and touch on that new image it gives me the color of the previous image.
Here is my code:
package com.blogspot.atifsoftwares.colorslab;
import android.Manifest;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
public class PickFromImageActivity extends AppCompatActivity {
ImageView mImageView;
TextView mResultTv;
ImageButton mCopyBtn, mShareBtn;
Bitmap bitmap;
View view;
Uri image_uri;
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;
private static final int PERMISSION_READ_STORAGE_CODE = 1002;
private static final int PERMISSION_WRITE_STORAGE_CODE = 1003;
private static final int PERMISSION_CAMERA_CODE = 1004;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_from_image);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("Color Picker");
actionBar.setSubtitle("Pick color from Image");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mImageView =findViewById(R.id.imageIv);
mResultTv = findViewById(R.id.restultTv);
mCopyBtn = findViewById(R.id.copyBtn);
mShareBtn = findViewById(R.id.shareBtn);
view = findViewById(R.id.colorView);
mImageView.setDrawingCacheEnabled(true);
mImageView.buildDrawingCache(true);
mImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){
bitmap = mImageView.getDrawingCache();
int pixel = bitmap.getPixel((int)event.getX(), (int) event.getY());
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
view.setBackgroundColor(Color.rgb(r,g,b));
mResultTv.setText("HEX: "+ String.format("#%06X", 0xFFFFFF & color)
+"\nRGB: "+ r +", "+ g +", "+ b
+"\nHSL: "+ rgbToHsl(r,g,b));
}
return true;
}
});
mCopyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cb.setText(data);
Toast.makeText(PickFromImageActivity.this, "Copied...!", Toast.LENGTH_SHORT).show();
}
});
mShareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, data);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
}
private String rgbToHsl(int r, int g, int b) {
final float rf = r / 255f;
final float gf = g / 255f;
final float bf = b / 255f;
final float max = Math.max(rf, Math.max(gf, bf));
final float min = Math.min(rf, Math.min(gf, bf));
final float deltaMaxMin = max - min;
float h, s;
float l = (max + min) / 2f;
if (max == min) {
// Monochromatic
h = s = 0f;
} else {
if (max == rf) {
h = ((gf - bf) / deltaMaxMin) % 6f;
} else if (max == gf) {
h = ((bf - rf) / deltaMaxMin) + 2f;
} else {
h = ((rf - gf) / deltaMaxMin) + 4f;
}
s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
}
h = (h * 60f) % 360f;
s = s*100;
l = l*100;
NumberFormat formH = NumberFormat.getNumberInstance();
formH.setMinimumFractionDigits(0);
formH.setMaximumFractionDigits(0);
String formattedH = formH.format(h);
NumberFormat formS = NumberFormat.getNumberInstance();
formS.setMinimumFractionDigits(0);
formS.setMaximumFractionDigits(0);
String formattedS = formS.format(s);
NumberFormat formL = NumberFormat.getNumberInstance();
formL.setMinimumFractionDigits(0);
formL.setMaximumFractionDigits(0);
String formattedL = formL.format(l);
return ""+ formattedH +", "+ formattedS +"%, "+ formattedL +"%";
}
public void pickCamera(){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
public void pickGallery(){
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
menu.findItem(R.id.action_search).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
return true;
} else if (id == R.id.action_rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
}
return true;
} else if (id == R.id.action_more) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
}
return true;
}
else if (id == R.id.action_share) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "\"Colors Lab\" contains important tools such as Popular Colors, Pick Color from color platte, Pick Color from Image, Convert Color from and to Hex, RGB, HSL.:\n https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
else if (id == R.id.action_camera) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_WRITE_STORAGE_CODE);
}
else {
//permission already granted
pickCamera();
}
}
else {
//system os is less then marshmallow
pickCamera();
}
}
else if (id == R.id.action_gallery) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_READ_STORAGE_CODE);
}
else {
//permission already granted
pickGallery();
}
}
else {
//system os is less then marshmallow
pickGallery();
}
}
return super.onOptionsItemSelected(item);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_READ_STORAGE_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickGallery();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
case PERMISSION_CAMERA_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickCamera();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
//set image to image view
mImageView.setImageURI(data.getData());
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
//set image to image view
mImageView.setImageURI(image_uri);
}
}
}
}
Screen shot:
before adding image
write this piece of code
ImgView.setImageBitmap(null);
ImgView.destroyDrawingCache();
In order to get color, first you have to get the pixel which is clicked by user
To get a pixel, you must get the bitmap on a canvas and then read the RGB values of that clicked pixel
Below code will help you do so
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y); // x and y are coordinates
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
// color is red
}
You can use multiple conditions or a logic to create RGB code from above values.
Add before adding the image...
mImageView.setImageBitmap(null);
mImageView.destroyDrawingCache();
Related
I'm trying to make a app where i can take a picture of something and then set that picture to a ImageView and I have succeded with that. the next step is to be able the save the picture in the imageView so that the picture remains the same even when closing and reopening the app. I am using SharedPrefrences for storing some other values but i can't find a way to use it for images. Here is my code:
package com.example.pongrknare;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ImageView imageView1;
private ImageView imageView2;
private ImageView imageView3;
private ImageView imageView4;
private ImageView imageView5;
private ImageView imageView6;
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private Switch undoSwitch;
private int nr = 1;
private int p1 = 0;
private int p2 = 0;
private int p3 = 0;
private int p4 = 0;
private int p5 = 0;
private int p6 = 0;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String P1 = "P1_value";
public static final String P2 = "P2_value";
public static final String P3 = "P3_value";
public static final String P4 = "P4_value";
public static final String P5 = "P5_value";
public static final String P6 = "P6_value";
private static final int REQUEST_IMAGE_CAPTURE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
imageView3 = findViewById(R.id.imageView3);
imageView4 = findViewById(R.id.imageView4);
imageView5 = findViewById(R.id.imageView5);
imageView6 = findViewById(R.id.imageView6);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
textView4 = findViewById(R.id.textView4);
textView5 = findViewById(R.id.textView5);
textView6 = findViewById(R.id.textView6);
undoSwitch = findViewById(R.id.undoSwitch);
loadData();
update_text();
}
public void takePicture1(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 1;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture2(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 2;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture3(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 3;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture4(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 4;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture5(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 5;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture6(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 6;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.reset_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.ja1:
p1 = 0;
p2 = 0;
p3 = 0;
p4 = 0;
p5 = 0;
p6 = 0;
update_text();
return true;
case R.id.ja2:
imageView1.setImageResource(R.color.colorImage);
imageView2.setImageResource(R.color.colorImage);
imageView3.setImageResource(R.color.colorImage);
imageView4.setImageResource(R.color.colorImage);
imageView5.setImageResource(R.color.colorImage);
imageView6.setImageResource(R.color.colorImage);
return true;
}
return super.onOptionsItemSelected(item);
}
private void update_text(){
textView1.setText("" + p1);
textView2.setText("" + p2);
textView3.setText("" + p3);
textView4.setText("" + p4);
textView5.setText("" + p5);
textView6.setText("" + p6);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (nr==1) {
Bundle extras = data.getExtras();
Bitmap imageBitmap1 = (Bitmap) extras.get("data");
imageView1.setImageBitmap(imageBitmap1);
saveData();
} else if(nr == 2){
Bundle extras = data.getExtras();
Bitmap imageBitmap2 = (Bitmap) extras.get("data");
imageView2.setImageBitmap(imageBitmap2);
saveData();
}else if(nr == 3){
Bundle extras = data.getExtras();
Bitmap imageBitmap3 = (Bitmap) extras.get("data");
imageView3.setImageBitmap(imageBitmap3);
saveData();
}else if(nr == 4){
Bundle extras = data.getExtras();
Bitmap imageBitmap4 = (Bitmap) extras.get("data");
imageView4.setImageBitmap(imageBitmap4);
saveData();
}else if(nr == 5){
Bundle extras = data.getExtras();
Bitmap imageBitmap5 = (Bitmap) extras.get("data");
imageView5.setImageBitmap(imageBitmap5);
saveData();
}else if(nr == 6){
Bundle extras = data.getExtras();
Bitmap imageBitmap6 = (Bitmap) extras.get("data");
imageView6.setImageBitmap(imageBitmap6);
saveData();
}else{
return;
}
}
public void count1(View view) {
if (undoSwitch.isChecked()== false) {
p1++;
}else if(p1> 0){
p1--;
}
textView1.setText(""+p1);
saveData();
}
public void count2(View view) {
if (undoSwitch.isChecked()== false) {
p2++;
}else if(p2>0){
p2--;
}
textView2.setText(""+p2);
saveData();
}
public void count3(View view) {
if (undoSwitch.isChecked()== false) {
p3++;
}else if(p3>0){
p3--;
}
textView3.setText(""+p3);
saveData();
}
public void count4(View view) {
if (undoSwitch.isChecked()== false) {
p4++;
}else if(p4>0){
p4--;
}
textView4.setText(""+p4);
saveData();
}
public void count5(View view) {
if (undoSwitch.isChecked()== false) {
p5++;
}else if(p5>0){
p5--;
}
textView5.setText(""+p5);
saveData();
}
public void count6(View view) {
if (undoSwitch.isChecked()== false) {
p6++;
}else if(p6>0){
p6--;
}
textView6.setText(""+p6);
saveData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(P1, p1);
editor.putInt(P2, p2);
editor.putInt(P3, p3);
editor.putInt(P4, p4);
editor.putInt(P5, p5);
editor.putInt(P6, p6);
editor.apply();
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
p1 = sharedPreferences.getInt(P1, 0);
p2 = sharedPreferences.getInt(P2, 0);
p3 = sharedPreferences.getInt(P3, 0);
p4 = sharedPreferences.getInt(P4, 0);
p5 = sharedPreferences.getInt(P5, 0);
p6 = sharedPreferences.getInt(P6, 0);
}
}
You can save the photos to the app pictures directory as follows
1. Generate the image file:
private File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_Hms").format(new Date());
String fileName = "JPEG_" + timestamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoImage = File.createTempFile(fileName, ".jpg", storageDir);
// Store this value in field to use later
picture1Path = photoImage.getAbsolutePath();
return photoImage;
}
Add the image file Uri to the IMAGE_CAPTURE intent:
private void takePicture1() {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), e.getMessage(), e);
}
// Add file Uri to intent
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile(
this,"com.your_app_package.fileprovider", photoFile);
imageTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
Save image Uri to shared preferences if image capture successful:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
setPic();
// Save imageUri
preferences.edit().putString("image1Uri", currentPhotoPath).apply();
}
}
}
private void setPic() {
// load and display pic
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
imageView1.setImageBitmap(bitmap);
}
4. Then set up the FileProvider:
In the app manifest.xml inside the tag:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your_app_package.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Also include the WRITE_EXTERNAL_STORAGE permission.
The create the "file_paths.xml" and add:
<paths>
<external-files-path name="my_images" path="/"/>
</paths>
And then in onCreate load the image file Uri from preferences and display:
currentPhotoPath = preferences.getString("image1Uri", null);
if (currentPhotoPath != null) {
setPic();
}
package com.example.hello;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* This activity displays the gallery image picker.
* It displays the image that was picked.
*
* #author ITCuties
*
*/
public class GalleryActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
#Override
public void onClick(View v) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}
}
this code select image from gallery ..
package com.example.hello;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ColourPickerActivity extends Activity {
TextView touchedXY, invertedXY, imgSize, colorRGB;
ImageView imgSource1, imgSource2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colourpicker);
// touchedXY = (TextView)findViewById(R.id.xy);
// invertedXY = (TextView)findViewById(R.id.invertedxy);
// imgSize = (TextView)findViewById(R.id.size);
colorRGB = (TextView)findViewById(R.id.colorrgb);
// imgSource1 = (ImageView)findViewById(R.id.source1);
imgSource2 = (ImageView)findViewById(R.id.source2);
//imgSource1.setOnTouchListener(imgSourceOnTouchListener);
imgSource2.setOnTouchListener(imgSourceOnTouchListener);
}
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
// touchedXY.setText(
// "touched position: "
// + String.valueOf(eventX) + " / "
// + String.valueOf(eventY));
// invertedXY.setText(
// "touched position: "
// + String.valueOf(x) + " / "
// + String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
// imgSize.setText(
// "drawable size: "
// + String.valueOf(bitmap.getWidth()) + " / "
// + String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
// if(x < 0){
// x = 0;
// }else if(x > bitmap.getWidth()-1){
// x = bitmap.getWidth()-1;
// }
//
// if(y < 0){
// y = 0;
// }else if(y > bitmap.getHeight()-1){
// y = bitmap.getHeight()-1;
// }
int touchedRGB = bitmap.getPixel(x, y);
colorRGB.setText("touched color: " + "#" + Integer.toHexString(touchedRGB));
colorRGB.setTextColor(touchedRGB);
return true;
}};
}
this code tell colour of pixel on touch of image which is in drawable folder .. how can i integrate these two activities .. i want to select image from gallery and apply colour detector on this image which is selected from gallery
Firs you'll need to call the second class from the fist one inside onActivityResult, adding the imagePath to the Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
(previous code)
Intent intent = new Intent(this, ColourPickerActivity.class);
intent.putExtra("IMAGE_PATH", imagePath);
startActivity(intent)
}
}
Then in your ColourPickerActivity you'll need to extract that path and load it into your ImageView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(previous code)
String imagePath = getIntent().getStringExtra("IMAGE_PATH");
//Load image into the ImageView
imgSource2.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
Hope that helps, cheers!
I have made a View Pager in that I want to implement manually slide(OnTOuch) and auto slide(onButton Click)..Both functions are working when use alone.But when i slede from one to another image and start auto Slide,It gives me IllegalStateException..And stops..Please help me to solve it,My code is as below:
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ImagePagerAdapter adapter;
ViewPager viewPager;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
System.out.println(":::::::::::::::current pos::::::::::" + pos);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
Animation anim;
anim = (Animation) getResources().getAnimation(
R.anim.animated_activity_slide_right_in);
viewPager.setAnimation(anim);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
/*
* proImage.setVisibility(View.GONE);
*
* AdapterViewFlipper flipper = (AdapterViewFlipper)
* findViewById(R.id.flipper); flipper.setAutoStart(true);
* flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
* resultArray));
*/
i = 0;
final Handler handler = new Handler();
final Runnable ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
if (i <= adapter.getCount() - 1) {
viewPager.setCurrentItem(i, true);
handler.postDelayed(this, 2000);
i++;
}
}
};
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader.displayImage(resultArray.get(position), imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
Try it and post output or logcat
private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
Log.d("TAG", "mScroller is: " + mScroller + ", "
+ mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is "
+ this + ", " + getClass().getSuperclass().getCanonicalName());
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}
I have this code for compressing pictures , I have two error , I have separated these errors with line in code like this (...........) first is : The left-hand side of an assignment must be a variable .......... and the second is Type mismatch: cannot convert from Object to String ................. how can I fix them ???
package com.example.resizingimages;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
public class GetImageActivity extends Activity
implements MediaScannerConnection.MediaScannerConnectionClient, DialogInterface
{
private static final int CAMERA_REQUEST = 1800;
private static final int GALLERY_KITKAT_INTENT_CALLED = 1500;
private static final int SELECT_PICTURE = 1;
static String filePath;
private TextView Name;
private TextView Size;
MediaScannerConnection conn;
File file;
private String filename;
private int height;
Uri imageUri;
private ImageView img;
private Uri outputFileUri;
Uri outputFileUri1;
String path1;
private String path2;
private Bitmap picture;
private File root;
File sdImageMainDirectory;
private Uri selectedImageUri;
private int width;
private void cameraaa(String paramString, Uri paramUri)
{
while (true)
{
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inSampleSize = 2;
localOptions.inPurgeable = true;
byte[] arrayOfByte = new byte[1024];
localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions.inTempStorage = arrayOfByte;
this.picture = BitmapFactory.decodeStream(localInputStream, null, localOptions);
switch (new ExifInterface(paramString).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str = sizee(paramUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str, 0).show();
System.out.println("Image Path : " + paramString);
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
}
public static String getDataColumn(Context paramContext, Uri paramUri, String paramString, String[] paramArrayOfString)
{
Cursor localCursor = null;
String[] arrayOfString = { "_data" };
try
{
localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, paramString, paramArrayOfString, null);
if ((localCursor != null) && (localCursor.moveToFirst()))
{
String str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
return str;
}
}
finally
{
if (localCursor != null)
localCursor.close();
}
if (localCursor != null)
localCursor.close();
return null;
}
public static String getPathl(Context paramContext, Uri paramUri)
{
int i;
if (Build.VERSION.SDK_INT >= 19)
i = 1;
while ((i != 0) && (DocumentsContract.isDocumentUri(paramContext, paramUri)))
if (isExternalStorageDocument(paramUri))
{
String[] arrayOfString3 = DocumentsContract.getDocumentId(paramUri).split(":");
if (!"primary".equalsIgnoreCase(arrayOfString3[0]))
break label271;
return Environment.getExternalStorageDirectory() + "/" + arrayOfString3[1];
i = 0;
}
else
{
if (isDownloadsDocument(paramUri))
{
String str2 = DocumentsContract.getDocumentId(paramUri);
return getDataColumn(paramContext, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(str2).longValue()), null, null);
}
if (!isMediaDocument(paramUri))
break label271;
String[] arrayOfString1 = DocumentsContract.getDocumentId(paramUri).split(":");
String str1 = arrayOfString1[0];
Uri localUri;
if ("image".equals(str1))
localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
while (true)
{
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = arrayOfString1[1];
return getDataColumn(paramContext, localUri, "_id=?", arrayOfString2);
if ("video".equals(str1))
{
localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else
{
boolean bool = "audio".equals(str1);
localUri = null;
if (bool)
localUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
}
if ("content".equalsIgnoreCase(paramUri.getScheme()))
return getDataColumn(paramContext, paramUri, null, null);
if ("file".equalsIgnoreCase(paramUri.getScheme()))
return paramUri.getPath();
label271: return filePath;
}
public static boolean isDownloadsDocument(Uri paramUri)
{
return "com.android.providers.downloads.documents".equals(paramUri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri paramUri)
{
return "com.android.externalstorage.documents".equals(paramUri.getAuthority());
}
public static boolean isMediaDocument(Uri paramUri)
{
return "com.android.providers.media.documents".equals(paramUri.getAuthority());
}
private void openAddPhoto()
{
String[] arrayOfString = { "Camera", "Gallery" };
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle(getResources().getString(2130968578));
localBuilder.setItems(arrayOfString, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
if (paramAnonymousInt == 0)
{
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", "new-photo-name.jpg");
localContentValues.put("description", "Image capture by camera");
GetImageActivity.this.imageUri = GetImageActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);
Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
localIntent1.putExtra("output", GetImageActivity.this.imageUri);
GetImageActivity.this.startActivityForResult(localIntent1, 1800);
}
if (paramAnonymousInt == 1)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent localIntent2 = new Intent();
localIntent2.setType("image/*");
localIntent2.setAction("android.intent.action.GET_CONTENT");
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent2, "Select Picture"), 1);
}
}
else
return;
Intent localIntent3 = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent3, "Select Picture"), 1500);
}
});
localBuilder.setNeutralButton("cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
private void startScan()
{
if (this.conn != null)
this.conn.disconnect();
this.conn = new MediaScannerConnection(this, this);
this.conn.connect();
}
public void cancel()
{
}
public void dismiss()
{
}
public String getPath(Uri paramUri)
{
Cursor localCursor = managedQuery(paramUri, new String[] { "_data" }, null, null, null);
String str = null;
if (localCursor != null)
{
int i = localCursor.getColumnIndexOrThrow("_data");
localCursor.moveToFirst();
str = localCursor.getString(i);
}
return str;
}
public String name(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
this.filename = filePath.substring(i + 1, paramString.length());
return this.filename;
}
if (paramString.charAt(j) == '/')
i = j;
}
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt2 == -1)
{
if (paramInt1 == 1)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
Toast.makeText(getApplicationContext(), "DATA " + filePath, 0).show();
filePath = getPath(this.selectedImageUri);
InputStream localInputStream2 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
localOptions2.inSampleSize = 2;
localOptions2.inPurgeable = true;
byte[] arrayOfByte2 = new byte[1024];
localOptions2.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions2.inTempStorage = arrayOfByte2;
this.picture = BitmapFactory.decodeStream(localInputStream2, null, localOptions2);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str4 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str4, 0).show();
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException3)
{
Toast.makeText(getApplicationContext(), "Error " + localException3.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
if (paramInt1 == 1500)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
getPathl(getApplicationContext(), this.selectedImageUri);
getContentResolver();
filePath = getPathl(getApplicationContext(), this.selectedImageUri);
InputStream localInputStream1 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
localOptions1.inSampleSize = 2;
localOptions1.inPurgeable = true;
byte[] arrayOfByte1 = new byte[1024];
localOptions1.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions1.inTempStorage = arrayOfByte1;
this.picture = BitmapFactory.decodeStream(localInputStream1, null, localOptions1);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str3 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str3, 0).show();
return;
case 6:
case 3:
}
}
catch (Exception localException2)
{
Toast.makeText(getApplicationContext(), "Error " + localException2.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 90);
continue;
rotateImage(this.picture, 180);
}
if (paramInt1 == 1800)
{
filePath = null;
this.selectedImageUri = this.imageUri;
if (this.selectedImageUri != null)
while (true)
{
String str1;
try
{
str1 = this.selectedImageUri.getPath();
String str2 = getPath(this.selectedImageUri);
if (str2 != null)
{
filePath = str2;
if (filePath == null)
break;
Toast.makeText(getApplicationContext(), " path" + filePath, 1).show();
new Intent(getApplicationContext(), GetImageActivity.class);
cameraaa(filePath, this.selectedImageUri);
return;
}
}
catch (Exception localException1)
{
Toast.makeText(getApplicationContext(), "Internal error", 1).show();
Log.e(localException1.getClass().getName(), localException1.getMessage(), localException1);
return;
}
if (str1 != null)
{
filePath = str1;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path", 1).show();
Log.e("Bitmap", "Unknown path");
}
}
}
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
setContentView(2130903040);
Display localDisplay = getWindowManager().getDefaultDisplay();
this.width = localDisplay.getWidth();
this.height = localDisplay.getHeight();
final Button localButton = (Button)findViewById(2131296257);
final Spinner localSpinner = (Spinner)findViewById(2131296260);
final TextView localTextView = (TextView)findViewById(2131296259);
localButton.setVisibility(4);
localSpinner.setVisibility(4);
localTextView.setVisibility(4);
if (this.height <= 480)
{
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 20 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -20 + (this.height - this.height / 3)));
localTextView.setText("Image Quality");
localTextView.setText("Image Quality");
this.img = ((ImageView)findViewById(2131296258));
this.img.setBackgroundResource(2130837504);
//first error is here
.......................................................................................
***(-160 + this.height);***
(-160 + this.height);
((int)(0.8D * this.width));
AbsoluteLayout.LayoutParams localLayoutParams1 = new AbsoluteLayout.LayoutParams((int)(0.8D * this.width), (int)(0.5D * this.height), (int)(this.width - 0.9D * this.width), (int)(this.height - 0.9D * this.height));
this.img.setLayoutParams(localLayoutParams1);
ImageView localImageView = this.img;
View.OnClickListener local1 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
GetImageActivity.this.img.setImageDrawable(null);
GetImageActivity.this.img.setBackgroundResource(2130837504);
localButton.setVisibility(0);
localSpinner.setVisibility(0);
localTextView.setVisibility(0);
GetImageActivity.this.openAddPhoto();
}
};
localImageView.setOnClickListener(local1);
if (this.height > 480)
break label505;
localButton.setBackgroundResource(2130837507);
(-160 + this.height);
}
for (AbsoluteLayout.LayoutParams localLayoutParams2 = new AbsoluteLayout.LayoutParams(50, 50, -25 + this.width / 2, -51 + this.height); ; localLayoutParams2 = new AbsoluteLayout.LayoutParams(170, 170, -85 + this.width / 2, -170 + this.height))
{
localButton.setLayoutParams(localLayoutParams2);
View.OnClickListener local2 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
}
};
localButton.setOnClickListener(local2);
return;
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 30 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -10 + (this.height - this.height / 3)));
break;
label505: localButton.setBackgroundResource(2130837506);
(-160 + this.height);
}
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(2131230720, paramMenu);
return true;
}
public void onMediaScannerConnected()
{
try
{
this.conn.scanFile(filePath, "image/*");
return;
}
catch (IllegalStateException localIllegalStateException)
{
}
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == 2131296262)
shareagain();
while (true)
{
return true;
if (paramMenuItem.getItemId() == 2131296263)
try
{
startActivity(new Intent(this, readddme.class));
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
}
else if (paramMenuItem.getItemId() == 2131296264)
System.exit(0);
}
}
public void onScanCompleted(String paramString, Uri paramUri)
{
this.conn.disconnect();
}
public void rotateImage(Bitmap paramBitmap, int paramInt)
{
Matrix localMatrix = new Matrix();
localMatrix.setRotate(paramInt);
this.picture = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
}
public void share()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.SUBJECT", "#RABIDO");
localIntent.putExtra("android.intent.extra.TEXT", "#RABIDO");
localIntent.setType("image/*");
localIntent.putExtra("android.intent.extra.STREAM", this.selectedImageUri);
startActivity(Intent.createChooser(localIntent, "Share Image"));
}
public void shareagain()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "Check out 'RABIDO' - https://play.google.com/store/apps/details?id=decrease.image.uploader");
startActivity(Intent.createChooser(localIntent, "Share via"));
}
public String sizee(Uri paramUri)
{
Object localObject;
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
byte[] arrayOfByte = new byte[1024];
int i = 0;
float f;
while (true)
{
if (localInputStream.read(arrayOfByte) == -1)
{
f = i / 1000;
if (f >= 1000.0F)
break;
localObject = " " + i / 1000 + " KB";
break label164;
}
i += arrayOfByte.length;
}
String str = " " + f / 1000.0F + " MB";
localObject = str;
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error 5 " + localException.getMessage(), 0).show();
return "";
}
//second is here
..................................................................
label164: return localObject;
}
}
For the First error can you try something like this:
(this.height = this.height - 160);
The error indicates you are trying to make an assignment operation but you have not put a variable in the left hand side of the equation.
there may also be a short hand way to do this such as:
(this.height =- 160);
for the second error is seems that you have declared "localObject" as an Object.
can you just declare it as a String. seems that you are assigning a string to it and then wanting to return a string. See if that works.
Here's what it looks like. I'm hoping a visual will help you help me!
I have tested it on three devices and four emulators with various screen sizes (so different image sizes) and versions of Android, and I haven't gotten any out of memory errors. I let my 3-year-old repeatedly pound on the animals and flip through them like crazy and still no OOM.
According to Google Play there are close to 200 installations since September 3rd 2013. I've only gotten one report of an OOM error so far, but now I'm worried that they are going to start rolling in. I'm including the whole activity in case one of my overridden methods has relevant information or something like that. This is my first published app so please excuse any newbie mistakes and feel free to criticize anything (as long as you include some suggestions for correcting it!)
setImages method from Game2Show (includes line 235, 'int currentAnimalImage...'):
private void setImages() {
//Get current letter and switch in name, letter and image that corresponds.
getLetter();
String l_img = "letter_" + currentLetter;
String a_img = "animal_" + currentLetter;
String n_img = "name_" + currentLetter;
int currentLetterImage = getResources().getIdentifier(l_img, "drawable", this.getPackageName());
ImageView l_iv = (ImageView) findViewById(R.id.current_letter);
l_iv.setImageResource(currentLetterImage);
int currentAnimalImage = getResources().getIdentifier(a_img, "drawable", this.getPackageName());
ImageView a_iv = (ImageView) findViewById(R.id.animal_image);
a_iv.setImageResource(currentAnimalImage);
int currentAnimalName = getResources().getIdentifier(n_img, "drawable", this.getPackageName());
ImageView n_iv = (ImageView) findViewById(R.id.animal_name);
n_iv.setImageResource(currentAnimalName);
Log.v(TAG, "voice: " + voice);
Log.v(TAG, "Config.alphabetSoundsArray_voice1: " + Config.alphabetSoundsArray_voice1);
Log.v(TAG, "Config.alphabetSoundsArray_voice2: " + Config.alphabetSoundsArray_voice2);
Log.v(TAG, "currentIndex: " + currentIndex);
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
if (voice == 1) {
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
else {
}
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
if (voice == 2) {
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
else {
}
System.gc();
}
Stack trace:
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
at android.content.res.Resources.loadDrawable(Resources.java:1937)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.widget.ImageView.resolveUri(ImageView.java:542)
at android.widget.ImageView.setImageResource(ImageView.java:315)
at com.zenlifegames.teachtryabc123.Game2Show.setImages(Game2Show.java:235)
at com.zenlifegames.teachtryabc123.Game2Show.onCreate(Game2Show.java:57)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Game2Show:
package com.zenlifegames.teachtryabc123;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Game2Show extends Activity {
private TextView textViewa;
private ImageView homeClicked;
int voice;
Handler handler = new Handler();
Intent i;
int currentIndex = 1;
String currentLetter;
ArrayList<Integer> alphabetNums;
String TAG = "Game2Show: ";
//private final String TAG = "Game2Show: ";
private int minAlphaRange = 1;
private int maxAlphaRange = 26;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game2_show);
i = new Intent(Game2Show.this, MyMusicService.class);
getMyViews();
setupPrefs();
Config.getPrefs(this);
musicToggleCheck();
userPreferences();
setFont();
setupAlphabetArray();
setImages();
Toast.makeText(Game2Show.this,
"Touch the letters, animals and words to hear audio.",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, GameSelector.class);
startActivity(intent);
super.onBackPressed();
}
public void returnHome(View view) {
homeClicked.setImageResource(R.drawable.homebuttonclicked);
if (Config.soundArray[0] !=0){Sound(Config.soundArray[0]);}
Intent intent = new Intent(this, GameSelector.class);
startActivity(intent);
}
private void musicToggleCheck() {
ImageButton musicToggleButton =(ImageButton)findViewById(R.id.music_toggle);
if (isMyServiceRunning()) {
musicToggleButton.setImageResource(R.drawable.music_toggle);
}
else {
musicToggleButton.setImageResource(R.drawable.music_toggle_off);
}
}
private void getMyViews() {
TextView textViewa = (TextView)findViewById(R.id.childs_name);
this.textViewa = textViewa;
final ImageView homeClicked = (ImageView) findViewById(R.id.home);
this.homeClicked = homeClicked;
}
private void setFont() {
Typeface t = Typeface.createFromAsset(this.getAssets(), "fonts/pen.ttf");
textViewa.setTypeface(t);
int[] color = {Color.RED, Color.BLUE};
float[] position = {0, 1};
TileMode tile_mode = TileMode.MIRROR; // Or TileMode.REPEAT;
LinearGradient lin_grad = new LinearGradient(0, 0, 0, 50,color,position, tile_mode);
Shader shader_gradient = lin_grad;
textViewa.getPaint().setShader(shader_gradient);
}
private void userPreferences() {
//Store childs name
textViewa.setText(Config.childsNameString);
//Set voice choice
int getVoiceChoice = Integer.parseInt(Config.storeVoiceChoice);
if (getVoiceChoice == 1) {
int voice = 1; //Mom
this.voice = voice;
}
else {
int voice = 2; //yg
this.voice = voice;
}
//Log.v(TAG, "voice: " + voice);
}
private void setupAlphabetArray() {
alphabetNums = new ArrayList<Integer>(maxAlphaRange);
for(currentIndex = minAlphaRange; currentIndex <= maxAlphaRange; currentIndex++) {
alphabetNums.add(currentIndex);
}
}
private void getLetter(){
if (currentIndex < minAlphaRange)
currentIndex = maxAlphaRange;
if (currentIndex > maxAlphaRange)
currentIndex = minAlphaRange;
if (currentIndex == 1) currentLetter = "a";
if (currentIndex == 2) currentLetter = "b";
if (currentIndex == 3) currentLetter = "c";
if (currentIndex == 4) currentLetter = "d";
if (currentIndex == 5) currentLetter = "e";
if (currentIndex == 6) currentLetter = "f";
if (currentIndex == 7) currentLetter = "g";
if (currentIndex == 8) currentLetter = "h";
if (currentIndex == 9) currentLetter = "i";
if (currentIndex == 10) currentLetter = "j";
if (currentIndex == 11) currentLetter = "k";
if (currentIndex == 12) currentLetter = "l";
if (currentIndex == 13) currentLetter = "m";
if (currentIndex == 14) currentLetter = "n";
if (currentIndex == 15) currentLetter = "o";
if (currentIndex == 16) currentLetter = "p";
if (currentIndex == 17) currentLetter = "q";
if (currentIndex == 18) currentLetter = "r";
if (currentIndex == 19) currentLetter = "s";
if (currentIndex == 20) currentLetter = "t";
if (currentIndex == 21) currentLetter = "u";
if (currentIndex == 22) currentLetter = "v";
if (currentIndex == 23) currentLetter = "w";
if (currentIndex == 24) currentLetter = "x";
if (currentIndex == 25) currentLetter = "y";
if (currentIndex == 26) currentLetter = "z";
}
public void goBack(View view) {
if (Config.soundArray[0] !=0){
Sound(Config.soundArray[0]);
}
currentIndex--;
setImages();
}
public void goForward(View view) {
if (Config.soundArray[0] !=0){
Sound(Config.soundArray[0]);
}
currentIndex++;
setImages();
}
public void sayLetter(View view) {
if (voice == 1) {
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
if (voice == 2) {
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
}
public void sayAnimal(View v) {
if (voice == 1) {
if (Config.animalNamesArray_voice1[currentIndex] !=0){
Sound(Config.animalNamesArray_voice1[currentIndex]);
}
}
if (voice == 2) {
if (Config.animalNamesArray_voice2[currentIndex] !=0){
Sound(Config.animalNamesArray_voice2[currentIndex]);
}
}
}
public void animalNoise(View v) {
if (Config.animalSoundsArray[currentIndex] !=0){
Sound(Config.animalSoundsArray[currentIndex]);
}
}
public void sideLetterClicked(View v) {
int id = v.getId();
if (id == R.id.side_letter_1)
currentIndex=1;
else if (id == R.id.side_letter_2) currentIndex=2;
else if (id == R.id.side_letter_3) currentIndex=3;
else if (id == R.id.side_letter_4) currentIndex=4;
else if (id == R.id.side_letter_5) currentIndex=5;
else if (id == R.id.side_letter_6) currentIndex=6;
else if (id == R.id.side_letter_7) currentIndex=7;
else if (id == R.id.side_letter_8) currentIndex=8;
else if (id == R.id.side_letter_9) currentIndex=9;
else if (id == R.id.side_letter_10) currentIndex=10;
else if (id == R.id.side_letter_11) currentIndex=11;
else if (id == R.id.side_letter_12) currentIndex=12;
else if (id == R.id.side_letter_13) currentIndex=13;
else if (id == R.id.side_letter_14) currentIndex=14;
else if (id == R.id.side_letter_15) currentIndex=15;
else if (id == R.id.side_letter_16) currentIndex=16;
else if (id == R.id.side_letter_17) currentIndex=17;
else if (id == R.id.side_letter_18) currentIndex=18;
else if (id == R.id.side_letter_19) currentIndex=19;
else if (id == R.id.side_letter_20) currentIndex=20;
else if (id == R.id.side_letter_21) currentIndex=21;
else if (id == R.id.side_letter_22) currentIndex=22;
else if (id == R.id.side_letter_23) currentIndex=23;
else if (id == R.id.side_letter_24) currentIndex=24;
else if (id == R.id.side_letter_25) currentIndex=25;
else if (id == R.id.side_letter_26) currentIndex=26;
else {
}
setImages();
}
private void setImages() {
//Get current letter and switch in name, letter and image that corresponds.
getLetter();
String l_img = "letter_" + currentLetter;
String a_img = "animal_" + currentLetter;
String n_img = "name_" + currentLetter;
int currentLetterImage = getResources().getIdentifier(l_img, "drawable", this.getPackageName());
ImageView l_iv = (ImageView) findViewById(R.id.current_letter);
l_iv.setImageResource(currentLetterImage);
int currentAnimalImage = getResources().getIdentifier(a_img, "drawable", this.getPackageName());
ImageView a_iv = (ImageView) findViewById(R.id.animal_image);
a_iv.setImageResource(currentAnimalImage);
int currentAnimalName = getResources().getIdentifier(n_img, "drawable", this.getPackageName());
ImageView n_iv = (ImageView) findViewById(R.id.animal_name);
n_iv.setImageResource(currentAnimalName);
Log.v(TAG, "voice: " + voice);
Log.v(TAG, "Config.alphabetSoundsArray_voice1: " + Config.alphabetSoundsArray_voice1);
Log.v(TAG, "Config.alphabetSoundsArray_voice2: " + Config.alphabetSoundsArray_voice2);
Log.v(TAG, "currentIndex: " + currentIndex);
if (Config.alphabetSoundsArray_voice1[currentIndex] !=0){
if (voice == 1) {
Sound(Config.alphabetSoundsArray_voice1[currentIndex]);
}
}
else {
}
if (Config.alphabetSoundsArray_voice2[currentIndex] !=0){
if (voice == 2) {
Sound(Config.alphabetSoundsArray_voice2[currentIndex]);
}
}
else {
}
System.gc();
}
//new
#Override
protected void onPause() {
super.onPause();
//Implemented to force music to stop when home is pressed.
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
if(isMyServiceRunning()){
stopService(i);
}
}
}
}
#Override
protected void onRestart() {
super.onRestart();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void setupPrefs() {
ImageButton settingsClicked = ((ImageButton) findViewById(R.id.prefButton));
settingsClicked.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView settingsClicked = ((ImageView) findViewById(R.id.prefButton));
settingsClicked.setImageResource(R.drawable.settings_button_clicked);
MediaPlayer buttonClicked = MediaPlayer.create(Game2Show.this, R.raw.click);
buttonClicked.start();
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
}
});
}
public boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyMusicService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void musicToggle(View v) {
final ImageButton musicToggleButton =(ImageButton)findViewById(R.id.music_toggle);
if ((!isMyServiceRunning())) {
startService(i);
Toast.makeText(Game2Show.this, "Music on.", Toast.LENGTH_SHORT).show();
musicToggleButton.setImageResource(R.drawable.music_toggle);
}
else {
stopService(i);
Toast.makeText(Game2Show.this, "Music off.", Toast.LENGTH_SHORT).show();
musicToggleButton.setImageResource(R.drawable.music_toggle_off);
}
}
public void Sound(int s){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Config.spool.play(s, volume, volume, 1, 0, 1f);
};
#Override
protected void onResume() {
Log.v(TAG, "onResume called.");
super.onResume();
if (Config.spool != null) {
}
else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}