I have an activity where the user can update some data related to his profile (for example, his name) and he can also upload a new profile image.
After the update operation, the user is redirected to a new activity.
The problem is that when the user comes back to his profile activity, the showed image is still the old one and not the new one while the name updated correctly.
In order to see the new profile image, the user needs to close the app and open is again.
How can I solve this problem?
I use a function updateInfo(), but it seems to not work as I would like.
Can you help me, please?
public class ProfileActivity extends BaseActivity implements ProfileView {
#BindView(R.id.avatar)
ImageView p_avatar;
#BindView(R.id.ib_back)
ImageButton ibBack;
#BindView(R.id.txt_title)
TextView txtTitle;
#BindView(R.id.ib_right)
ImageButton ibRight;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.et_fullname)
EditText etFullname;
#BindView(R.id.et_email)
EditText etEmail;
#BindView(R.id.btn_update)
Button btnUpdate;
#BindView(R.id.txt_logout)
TextView txtLogout;
#BindView(R.id.ll_main)
LinearLayout llMain;
private static final String TAG = "ProfileActivity";
private String userName = null, userEmail = null;
private ProfilePresenter profilePresenter;
private Dialog dialog;
Bitmap FixBitmap;
Bitmap bitmap_to_save;
ImageView ShowSelectedImage;
String converted_img;
ByteArrayOutputStream byteArrayOutputStream;
byte[] byteArray ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
byteArrayOutputStream = new ByteArrayOutputStream();
init_view();
upDateInfo();
}
private void init_view() {
txtTitle.setText(R.string.profileActivity_title);
ibRight.setImageResource(R.drawable.ic_edit);
dialog = commonUtils.createCustomLoader(ProfileActivity.this, false);
profilePresenter = new ProfilePresenterImpl(this);
upDateInfo();
}
private void upDateInfo() {
if (Conts.USERINFO != null) {
String subName = firstTwoChar(Conts.USERINFO.getName());
// Picasso.get().load("http://www.server.com/uploads/avatars/73.png").transform(transformation).into(p_avatar);
final int radius = 30;
final int margin = 1;
final RoundedCornersTransformation transformation = new RoundedCornersTransformation(radius, margin);
Picasso.get().load("http://www.server.com/uploads/avatars/"+Conts.USERINFO.getId()).transform(transformation).into(p_avatar);
etFullname.setText(Conts.USERINFO.getName().toLowerCase());
etFullname.setEnabled(false);
etEmail.setText(Conts.USERINFO.getEmail());
etEmail.setEnabled(false);
btnUpdate.setVisibility(View.INVISIBLE);
}
}
#OnClick({R.id.ib_back, R.id.ib_right, R.id.btn_update, R.id.txt_logout, R.id.avatar})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ib_back:
onBackPressed();
break;
case R.id.ib_right:
etFullname.setEnabled(true);
etFullname.setSelection(etFullname.getText().toString().length());
btnUpdate.setVisibility(View.VISIBLE);
Log.d(TAG, "validate ID: " + Conts.USERINFO.getId());
return;
case R.id.avatar:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
return;
case R.id.btn_update:
if (validate()) {
if (!commonUtils.isNetworkAvailable()) {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
return;
}
profilePresenter.dataListAPI(Conts.USERINFO.getId(), userName, Conts.USERINFO.getEmail(), converted_img);
}
break;
case R.id.txt_logout:
get_dialog();
break;
}
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
FixBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap_to_save = scaleBitmapAndKeepRation(FixBitmap, 320, 320);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap_to_save);
final float roundPx = (float) bitmap_to_save.getWidth() * 0.15f;
roundedBitmapDrawable.setCornerRadius(roundPx);
roundedBitmapDrawable.setAntiAlias(true);
p_avatar.setImageDrawable(roundedBitmapDrawable);
bitmap_to_save.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
converted_img = Base64.encodeToString(byteArray, Base64.DEFAULT); // this is the image string to send to the server!
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(this, "An error has occurred!", Toast.LENGTH_SHORT).show();
}
}
public static Bitmap scaleBitmapAndKeepRation(Bitmap TargetBmp, int reqHeightInPixels, int reqWidthInPixels)
{
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, TargetBmp.getWidth(), TargetBmp.getHeight()), new RectF(0, 0, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.CENTER);
Bitmap scaledBitmap = Bitmap.createBitmap(TargetBmp, 0, 0, TargetBmp.getWidth(), TargetBmp.getHeight(), m, true);
return scaledBitmap;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private void get_dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, null);
builder.setView(view);
final AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alertDialog.show();
TextView txtyes, txtno;
txtyes = view.findViewById(R.id.txt_yes);
txtno = view.findViewById(R.id.txt_no);
txtyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
sharedPref.setBoolean(Conts.IsLogin, false);
sharedPref.clearAllPref();
Conts.USERINFO = null;
Intent iLogin = new Intent(ProfileActivity.this, MainActivity.class);
iLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(iLogin);
}
});
txtno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
public String firstTwoChar(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
#Override
public void showLoader() {
dialog.show();
}
#Override
public void hideLoader() {
if (dialog != null)
dialog.dismiss();
}
#Override
public void showError(String msg) {
Snackbar snackbar = Snackbar
.make(llMain, msg, Snackbar.LENGTH_INDEFINITE)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
// nothing anything
}
});
snackbar.show();
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
#Override
public Context getContextAppp() {
return this;
}
#Override
public void onBackPress() {
}
#Override
public void successResponse(Data data) {
if (data != null) {
Toast.makeText(this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
UserInfo userInfo = new UserInfo(data.getId(), data.getName(), data.getEmail());
Conts.USERINFO = userInfo;
String userinfo = gson.toJson(Conts.USERINFO, UserInfo.class);
sharedPref.setDataInPref(Conts.UserInfo, userinfo);
startActivity(getIntent());
Intent iPlace = new Intent(ProfileActivity.this, AddPlaceActivity.class);
iPlace.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(this, "Profile saved!", Toast.LENGTH_SHORT).show();
startActivity(iPlace);
}
}
#Override
public void errorResponce(String msg) {
if (msg != null) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
private boolean validate() {
commonUtils.hideKeyboard(this);
if (etFullname.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Fullname", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() <= 2) {
Toast.makeText(this, "Minimum 3 character require", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() > 30) {
Toast.makeText(this, "Maximum 30 character require", Toast.LENGTH_SHORT).show();
}
/*else if (etEmail.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
} else if (!validation.checkEmail(etEmail)) {
Toast.makeText(this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
}
*/
if (!etFullname.getText().toString().trim().isEmpty() && etFullname.getText().toString().trim().length() > 2 && etFullname.getText().toString().trim().length() <= 30) {
userName = etFullname.getText().toString().trim();
} else {
userName = null;
}
/*if (!etEmail.getText().toString().trim().isEmpty() && validation.checkEmail(etEmail)) {
userEmail = etEmail.getText().toString().trim();
} else {
userEmail = null;
}
*/
if (userName != null /*&& userEmail != null*/) {
Log.d(TAG, "validate: " + userName);
return true;
} else {
return false;
}
}
}
When you turn back to your profile activity your application's task stack is bringing back your profile activity which is already in memory. So you should inform your profile activity that it was updated. In the onStart callback of your profile activity check if it is updated. If so load the new image. In short put your upDateInfo() method inside onStart().
After you update the information, in callback method onResponse you need to call updateInfo() to make an update on your UI after update of information is successfully finished. Make sure you provide new values from server especially to static variables because they will keep values as long as app is live. If you don't update them with new values they will keep old ones.
Currently on that way you are trying to update informations only in onCreate() which is called when Activity needs to be created. In this scenario it is when you exit and enter app again only by pressing Back button while on Home button it will not work as well until app is destroyed by OS.
You could also use onResume method which is called after Activity is returned from pause and that will happen when you create a new Activity upon already exiting one.
Related
I have done implementing "set wallpaper as home screen".but im not getting how can I set wallpaper as lock screen and both(home and lock).in following code "if" part is for setting as homescreen..rest is for "lock" and "both(home and lock)"..what will the logic for it to set wallpaper as lock and both(home and lock).?
code:
public class ViewImage extends AppCompatActivity {
Button button1, button2;
public List<RetroPhoto> product_lists=new ArrayList<>();
private RecyclerView recyclerView;
WallpaperManager myWallpaperManager;
public static FavoriteDatabase favoriteDatabase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewimage_layout);
ImageView mPlace = findViewById(R.id.imagewall);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
ImageButton back = (ImageButton) findViewById(R.id.backToMain);
ImageButton downloadimage = findViewById(R.id.downloadimg);
ImageView favimg = findViewById(R.id.favimg);
recyclerView = findViewById(R.id.rec);
favoriteDatabase = Room.databaseBuilder(getApplicationContext(), FavoriteDatabase.class, "myfavdb").allowMainThreadQueries().build();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
final Bundle bundle = this.getIntent().getExtras();
final String imgUrl = bundle.getString("Title");
Glide.with(this).load(imgUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(mPlace);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ViewImage.this);
// Set the alert dialog title
builder.setTitle("Set Wallpaper");
// Initialize a new string array of flowers
final String[] flowers = new String[]{
"Home Screen",
"Lock screen",
"Both"
};
// Set a list for alert dialog
builder.setItems(
flowers, // Items array
new DialogInterface.OnClickListener() // Item click listener
{
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Get the alert dialog selected item's text
String selectedItem = Arrays.asList(flowers).get(i);
if(selectedItem.equals(flowers[0])) {
Glide.with(ViewImage.this)
.load(imgUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
try {
WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
Toast.makeText(ViewImage.this, "successfully set as home wallpaper", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
else if(selectedItem.equals(flowers[1]))
{
Uri bitmap = MediaStore.Images.Media.getContentUri(imgUrl);
final Uri finalBitmap = bitmap;
try {
WallpaperManager.getInstance(getApplicationContext()).setBitmap(finalBitmap,null,false,WallpaperManager.FLAG_LOCK);
// myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK);
Toast.makeText(ViewImage.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(ViewImage.this, "successfully set as Lock wallpaper", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(ViewImage.this, "successfully set as both", Toast.LENGTH_LONG).show();
}
}
});
// Create the alert dialog
AlertDialog dialog = builder.create();
// Get the alert dialog ListView instance
ListView listView = dialog.getListView();
// Set the divider color of alert dialog list view
listView.setDivider(new ColorDrawable(Color.RED));
// Set the divider height of alert dialog list view
listView.setDividerHeight(0);
// Finally, display the alert dialog
dialog.show();
}
});
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte= Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Check my code if its working for you :)
WallpaperManager myWallpaperManager;
private static final int CHOOSE_IMAGE = 22;
private Button btnSetWallpaper;
String[] options = new String[]{
"Home Screen",
"Lock Screen",
"Both"
};
In OnCreate()
btnSetWallpaper = findViewById(R.id.btnSetWallpaper);
btnSetWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "choose image"), CHOOSE_IMAGE);
}
});
In OnActivityResult()
if (requestCode == CHOOSE_IMAGE && data != null) {
mCropImageUri = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mCropImageUri);
Log.e(TAG, "onActivityResult: BIT " + bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose from below");
final Bitmap finalBitmap = bitmap;
builder.setItems(options, new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedItem = Arrays.asList(options).get(i);
if (selectedItem.equals(options[0])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_SYSTEM);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
} else if (selectedItem.equals(options[1])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
} else if (selectedItem.equals(options[2])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
}
}
});
dialog = builder.create();
dialog.show();
}
You wanna just set Flags for various Wallpaper Options.
Flags like...
WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM : for both Screen
WallpaperManager.FLAG_SYSTEM : for Home Screen
WallpaperManager.FLAG_LOCK :for Lock Screen
Thanks :)
I am working on a filter activity in which there are 3 images at the bottom. By default, image 3 will be selected as it is the last one that will be clicked.
This same activity contains Latitude and Longitude which will be sent to next activity to fetch nearby locations.
The problem that I am facing is that among those 3 images when I select a filter for Image 1 and select the image 2, the activity gets restarted and because of this, the lat and long values are reset to 0.0 and 0.0 respectively.
Code -
public class MainActivity extends AppCompatActivity implements FiltersListFragment.FiltersListFragmentListener, EditImageFragment.EditImageFragmentListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_activity_main_filter);
instagramFilterIntent = new Intent(this, MainActivity.class);
ButterKnife.bind(this);
getBundleValues();
loadImage();
setupViewPager(viewPager);
setBitmap(originalImage);
ivSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery();
startingActivtity();
}
});
ivClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery();
}
});
}
double latitude,longitude;
private void getBundleValues() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("image")) {
Log.e("image", extras.getString("image"));
editingImage = extras.getString("image");
imgFile = new File(extras.getString("image"));
originalFile = imgFile;
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
originalImage = myBitmap;
}
}
if(extras.containsKey("PESDK")){
initiated=extras.getBoolean("PESDK");
}
if(extras.containsKey("Latitude")){
latitude=extras.getDouble("Latitude");
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
if(extras.containsKey("Longitude")){
longitude=extras.getDouble("Longitude");
}
if (extras.containsKey("Filters")) {
filters = extras.getBoolean("Filters");
instagramFilterIntent.putExtra("Filters", filters);
}
if (extras.containsKey("Image1")) {
files[0] = extras.getString("Image1");
instagramFilterIntent.putExtra("Image1", files[0]);
}
if (extras.containsKey("Image2")) {
files[1] = extras.getString("Image2");
instagramFilterIntent.putExtra("Image2", files[1]);
}
if (extras.containsKey("Image3")) {
files[2] = extras.getString("Image3");
instagramFilterIntent.putExtra("Image3", files[2]);
}
initializeImages();
}
}
private void initializeImages() {
if (files[0] != null) {
//Glide.with(getApplicationContext()).load(files[0]).into(preview1Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[0]);
preview1Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[0])) {
preview1B.setVisibility(View.VISIBLE);
}
}
else {
preview1Layout.setVisibility(View.GONE);
preview1B.setVisibility(View.INVISIBLE);
}
if (files[1] != null) {
//Glide.with(getApplicationContext()).load(files[1]).into(preview2Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[1]);
preview2Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[1])) {
preview2B.setVisibility(View.VISIBLE);
}
}
else {
preview2Layout.setVisibility(View.GONE);
preview2B.setVisibility(View.INVISIBLE);
}
if (files[2] != null) {
//Glide.with(getApplicationContext()).load(files[2]).into(preview3Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[2]);
preview3Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[2])){
preview3B.setVisibility(View.VISIBLE);
}
}
else {
preview3Layout.setVisibility(View.GONE);
preview3B.setVisibility(View.INVISIBLE);
}
}
public static void setBitmap(Bitmap originalImage) {
ORIGINAL = originalImage;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adding filter list fragment
filtersListFragment = new FiltersListFragment();
filtersListFragment.setInitiatedPESDK(initiated);
filtersListFragment.setListener(this);
// adding edit image fragment
editImageFragment = new EditImageFragment();
editImageFragment.setListener(this);
adapter.addFragment(filtersListFragment, getString(R.string.tab_filters));
adapter.addFragment(editImageFragment, getString(R.string.tab_edit));
//filtersListFragment.prepareThumbnail(originalImage);
viewPager.setAdapter(adapter);
}
#Override
public void onFilterSelected(Filter filter, ImageFilter imageFilter) {
// reset image controls
resetControls();
// applying the selected filter
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
// preview filtered image
if(filter!=null) {
imagePreview.setImageBitmap(filter.processFilter(filteredImage));
}else{
imagePreview.setImageBitmap(imageFilter.renderImage(filteredImage,false));
}
finalImage = filteredImage.copy(Bitmap.Config.ARGB_8888, true);
}
/**
* Resets image edit controls to normal when new filter
* is selected
*/
private void resetControls() {
if (editImageFragment != null) {
editImageFragment.resetControls();
}
brightnessFinal = 10;
saturationFinal = 1.0f;
contrastFinal = 1.0f;
}
/**
* Image View click listners
* */
public void image1Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[0])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[0]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
public void image2Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[1])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[1]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
public void image3Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[2])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[2]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
// load the default image from assets on app launch
private void loadImage() {
//#todo
// originalImage = BitmapUtils.getBitmapFromGallery(this, Uri.parse(IMAGE_NAME), 300, 300);
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
imagePreview.setImageBitmap(originalImage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == SELECT_GALLERY_IMAGE) {
Log.e("data.getData()", data.getData() + "");
Bitmap bitmap = BitmapUtils.getBitmapFromGallery(this, data.getData(), 800, 800);
// clear bitmap memory
originalImage.recycle();
finalImage.recycle();
finalImage.recycle();
originalImage = bitmap.copy(Bitmap.Config.ARGB_8888, true);
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
imagePreview.setImageBitmap(originalImage);
bitmap.recycle();
// render selected image thumbnails
filtersListFragment.prepareThumbnail(originalImage);
}
}
/*
* saves image to camera gallery
* */
private void saveImageToGallery() {
Dexter.withActivity(this).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
if (originalFile.exists()) {
originalFile.delete();
}
// final String path = BitmapUtils.insertImage(getContentResolver(), finalImage, System.currentTimeMillis() + "_profile.jpg", null);
new MainActivity.SaveImageTask(finalImage, originalFile).execute();
//finish();
}
else {
Toast.makeText(getApplicationContext(), "Permissions are not granted!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
Bitmap finalBitmap;
File name;
public SaveImageTask(Bitmap finalBitmap, File name) {
this.finalBitmap = finalBitmap;
this.name = name;
}
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File file = name;
if (file.exists()) {
} else {
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.e("FIlter MainACTIVITY", "SAVED");
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
}
}
public void startingActivtity(){
Intent chekInActivity = new Intent(MainActivity.this, CurrentLocationPlaces.class);
if(files[0] != null) {
chekInActivity.putExtra("Image1",files[0].toString());
}
if(files[1] != null) {
chekInActivity.putExtra("Image2",files[1].toString());
}
if(files[2] != null) {
chekInActivity.putExtra("Image3",files[2].toString());
}
chekInActivity.putExtra("source","gallery");
chekInActivity.putExtra("Latitude", latitude);
chekInActivity.putExtra("Longitude", longitude);
startActivity(chekInActivity);
}
}
May I know how to either stop restarting the activity and select the image to get its preview to apply filters or how to save the lat and long values so that it won't get reset when the activity restarts?
If the value should be held across activity restarts you should be using an activity or shared preference.
Basically in your onCreate, load the values and assign them to your Textview (or other component). When they change just update the preference value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load the lat/lng
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
double lat = preferences.getDouble("latitude", 0);
double lon = preferences.getDouble("longitude", 0);
}
Then where you have your application update that value simply update the preference value.
private void updatePreference(double lat, double lng) {
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("latitude", lat);
editor.putInt("longitude", lon);
editor.commit();
}
That will hold your values and allow you to update/interface with them across activity restarts.
SEE: SharedPreferences
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.
I'm trying to implement in app-billing in my application, but I have a little problem with it. I'm using the example from android developer's site and everytime I start the activity which will connect to the billing service it's showing me a dialog that I cannot connect to server and when I press learn more it's going to a web page which is explaining me to update my android market app, but it's already the latest one. And the other thing, before implementing the code on my application I create a test application where I can connect with the same code and I don't get problems. But in my application I can't do that. Is there any connection with the developer api key, which you can use only in one application or something like that. Because I'm using the same for test and real app.
And here is my code if you can see something which is not really like it should be :
public class StampiiStore extends Activity {
String servername;
int userId;
int storageID;
RPCCommunicator rpc;
String path;
Button envelope1, envelope2, envelope3;
private static final String TAG = "STAMPII";
/**
* The SharedPreferences key for recording whether we initialized the
* database. If false, then we perform a RestoreTransactions request
* to get all the purchases for this user.
*/
private static final String DB_INITIALIZED = "db_initialized";
private mStampiiPurchaseObserver mStampiiPurchaseObserver;
private Handler mHandler;
private BillingService mBillingService;
private TextView mLogTextView;
private Cursor mOwnedItemsCursor;
private PurchaseDatabase mPurchaseDatabase;
private Set<String> mOwnedItems = new HashSet<String>();
/**
* The developer payload that is sent with subsequent
* purchase requests.
*/
private static final int DIALOG_CANNOT_CONNECT_ID = 1;
private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;
#SuppressWarnings("static-access")
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.store);
SystemDatabaseHelper sysDbHelper = new SystemDatabaseHelper(this, null, 1);
sysDbHelper.initialize(this);
ImageView icon = (ImageView) findViewById (R.id.store_img);
final int collId = getIntent().getIntExtra("collection_id",0);
Log.e("collId","collId : "+collId);
// Getting all variables from SharedPreferences to build the right path to images
servername = rpc.getCurrentServerName(this);
Log.d("","Current Server Name : "+servername);
userId = rpc.getUserId(this);
Log.d("","User Id : "+userId);
storageID = rpc.getCurrentStoragePath(this);
Log.d("","storage ID : "+storageID);
//
TextView colltitle = (TextView) findViewById(R.id.collection_title);
TextView sTitle = (TextView) findViewById(R.id.store_collId);
TextView collInfo = (TextView) findViewById(R.id.store_coll_info);
envelope1 = (Button) findViewById(R.id.buyone);
envelope1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("android.test.purchased", "");
}
});
envelope2 = (Button) findViewById(R.id.buytwo);
envelope2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("android.test.canceled", "");
}
});
envelope3 = (Button) findViewById(R.id.buythree);
envelope3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingService.requestPurchase("com.stampii.stampii.envelopesthree", "");
}
});
mHandler = new Handler();
mStampiiPurchaseObserver = new mStampiiPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
mPurchaseDatabase = new PurchaseDatabase(this);
setupWidgets();
// Check if billing is supported.
ResponseHandler.register(mStampiiPurchaseObserver);
if (!mBillingService.checkBillingSupported()) {
showDialog(DIALOG_CANNOT_CONNECT_ID);
}
Button back = (Button) findViewById(R.id.store_back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = settings.getBoolean("isLoggedIn", false);
ImageButton sync = (ImageButton) findViewById(R.id.sync_store);
if(isLoggedIn){
sync.setVisibility(View.VISIBLE);
} else if(!isLoggedIn){
sync.setVisibility(View.GONE);
}
sync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(StampiiStore.this, Synchronization.class);
intent.putExtra("process", 2);
startActivity(intent);
}
});
String titleSql = "SELECT title FROM collection_lang WHERE collection_id= " + collId + " AND lang_code='en_US'";
Cursor title = sysDbHelper.executeSQLQuery(titleSql);
if(title.getCount()==0){
title.close();
} else if(title.getCount()>0){
for(title.move(0); title.moveToNext(); title.isAfterLast()){
String collectionTitle = title.getString(title.getColumnIndex("title"));
sTitle.setText(collectionTitle);
if (collectionTitle.length() > 20){
String newTitle = collectionTitle.substring(0, 20);
colltitle.setText(newTitle + "...");
} else {
colltitle.setText(collectionTitle);
}
}
}
title.close();
String infoSql = "SELECT DISTINCT c.total_cards AS cardsCount, " +
" c.cards_per_envelope AS cardsPerEnvelope " +
"FROM collections AS c, collection_lang AS cl " +
"WHERE c.collection_id = cl.collection_id AND c.collection_id=" + collId;
Cursor info = sysDbHelper.executeSQLQuery(infoSql);
if(info.getCount()==0){
info.close();
} else if (info.getCount()>0){
info.moveToFirst();
int cardsCount = info.getInt(info.getColumnIndex("cardsCount"));
int cardsPerEnvelope = info.getInt(info.getColumnIndex("cardsPerEnvelope"));
collInfo.setText(cardsCount+" Stampii\n"+cardsPerEnvelope+" cards per envelope");
}
String sqlite2 = "SELECT media_id FROM collection_media WHERE collection_id="+collId+" AND media_type_id="+3018;
Cursor bg = sysDbHelper.executeSQLQuery(sqlite2);
if (bg.getCount() == 0) {
bg.close();
} else if (bg.getCount() > 0) {
for (bg.move(0); bg.moveToNext(); bg.isAfterLast()) {
int objectId = Integer.parseInt(bg.getString(bg.getColumnIndex("media_id")));
String filename = "mediacollection-"+objectId+".png";
//if(storageID==1){
path = rpc.getPublicPathsInternal(servername, 3018, filename, StampiiStore.this);
/*} else if(storageID==2){
path = rpc.getPublicPathsExternal(servername, 3007, objectId);
}*/
}
}
bg.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[3*1024];
Bitmap ops = BitmapFactory.decodeFile(path, options);
BitmapDrawable bitmapDrawable = new BitmapDrawable(ops);
icon.setBackgroundDrawable(bitmapDrawable);
Button promoCode = (Button) findViewById(R.id.promo_code_btn);
promoCode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences isSelectedCode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String isSelected = isSelectedCode.getString("isSelected", "");
Log.i("isSelected", "isSelected" + isSelected);
EditText input = new EditText(StampiiStore.this);
input.setText(isSelected);
final int loggedOut = getIntent().getIntExtra("statement", 0);
if(loggedOut==0){
new AlertDialog.Builder(getParent())
.setTitle("Promotional Code")
.setView(input)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog","Negative");
dialog.cancel();
}
}).show();
} else if (loggedOut==1){
new AlertDialog.Builder(Collections.parentActivity)
.setTitle("Promotional Code")
.setView(input)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog","Negative");
dialog.cancel();
}
}).show();
}
}
});
Button savedCodes = (Button) findViewById(R.id.saved_codes_btn);
savedCodes.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent previewMessage = new Intent(getParent(), SavedCodes.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Saved Codes", previewMessage);
}
});
}
/**
* Sets up the UI.
*/
private void setupWidgets() {
//TODO: If need any changes in the UI!
}
/**
* If the database has not been initialized, we send a
* RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
* for this user. This happens if the application has just been installed
* or the user wiped data. We do not want to do this on every startup, rather, we want to do
* only when the database needs to be initialized.
*/
private void restoreDatabase() {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
if (!initialized) {
mBillingService.restoreTransactions();
Toast.makeText(this, "Restoring Transactions", Toast.LENGTH_LONG).show();
}
}
private void prependLogEntry(CharSequence cs) {
SpannableStringBuilder contents = new SpannableStringBuilder(cs);
contents.append('\n');
contents.append(mLogTextView.getText());
mLogTextView.setText(contents);
}
private void logProductActivity(String product, String activity) {
SpannableStringBuilder contents = new SpannableStringBuilder();
contents.append(Html.fromHtml("<b>" + product + "</b>: "));
contents.append(activity);
prependLogEntry(contents);
}
//PurchaseObserver
private class mStampiiPurchaseObserver extends PurchaseObserver {
public mStampiiPurchaseObserver(Handler handler) {
super(StampiiStore.this, handler);
}
#Override
public void onBillingSupported(boolean supported) {
if (Consts.DEBUG) {
Log.i(TAG, "supported: " + supported);
}
if (supported) {
restoreDatabase();
envelope1.setEnabled(true);
envelope2.setEnabled(true);
envelope3.setEnabled(true);
} else {
showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
}
}
#Override
public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
int quantity, long purchaseTime, String developerPayload) {
if (Consts.DEBUG) {
Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState);
}
if (developerPayload == null) {
logProductActivity(itemId, purchaseState.toString());
} else {
logProductActivity(itemId, purchaseState + "\n\t" + developerPayload);
}
if (purchaseState == PurchaseState.PURCHASED) {
mOwnedItems.add(itemId);
}
mOwnedItemsCursor.requery();
}
#Override
public void onRequestPurchaseResponse(RequestPurchase request,
ResponseCode responseCode) {
if (Consts.DEBUG) {
Log.d(TAG, request.mProductId + ": " + responseCode);
}
if (responseCode == ResponseCode.RESULT_OK) {
if (Consts.DEBUG) {
Log.i(TAG, "purchase was successfully sent to server");
}
logProductActivity(request.mProductId, "sending purchase request");
} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
if (Consts.DEBUG) {
Log.i(TAG, "user canceled purchase");
}
logProductActivity(request.mProductId, "dismissed purchase dialog");
} else {
if (Consts.DEBUG) {
Log.i(TAG, "purchase failed");
}
logProductActivity(request.mProductId, "request purchase returned " + responseCode);
}
}
#Override
public void onRestoreTransactionsResponse(RestoreTransactions request,
ResponseCode responseCode) {
if (responseCode == ResponseCode.RESULT_OK) {
if (Consts.DEBUG) {
Log.d(TAG, "completed RestoreTransactions request");
}
// Update the shared preferences so that we don't perform
// a RestoreTransactions again.
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(DB_INITIALIZED, true);
edit.commit();
} else {
if (Consts.DEBUG) {
Log.d(TAG, "RestoreTransactions error: " + responseCode);
}
}
}
}
/**
* Called when this activity becomes visible.
*/
#Override
protected void onStart() {
super.onStart();
ResponseHandler.register(mStampiiPurchaseObserver);
}
/**
* Called when this activity is no longer visible.
*/
#Override
protected void onStop() {
super.onStop();
ResponseHandler.unregister(mStampiiPurchaseObserver);
}
#Override
protected void onDestroy() {
super.onDestroy();
mPurchaseDatabase.close();
mBillingService.unbind();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CANNOT_CONNECT_ID:
return createDialog("Server cannot Connect",
"Server cannot connect");
case DIALOG_BILLING_NOT_SUPPORTED_ID:
return createDialog("Billing not supported",
"Billing not supported");
default:
return null;
}
}
/**
* Replaces the language and/or country of the device into the given string.
* The pattern "%lang%" will be replaced by the device's language code and
* the pattern "%region%" will be replaced with the device's country code.
*
* #param str the string to replace the language/country within
* #return a string containing the local language and region codes
*/
private String replaceLanguageAndRegion(String str) {
// Substitute language and or region if present in string
if (str.contains("%lang%") || str.contains("%region%")) {
Locale locale = Locale.getDefault();
str = str.replace("%lang%", locale.getLanguage().toLowerCase());
str = str.replace("%region%", locale.getCountry().toLowerCase());
}
return str;
}
private Dialog createDialog(String titleId, String messageId) {
String helpUrl = replaceLanguageAndRegion(getString(R.string.help_url));
if (Consts.DEBUG) {
Log.i(TAG, helpUrl);
}
final Uri helpUri = Uri.parse(helpUrl);
AlertDialog.Builder builder = null;
final int loggedOut = getIntent().getIntExtra("statement", 0);
if(loggedOut==0){
builder = new AlertDialog.Builder(getParent());
builder.setTitle(titleId)
.setIcon(android.R.drawable.stat_sys_warning)
.setMessage(messageId)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton("Learn More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, helpUri);
startActivity(intent);
}
});
} else if(loggedOut==1){
builder = new AlertDialog.Builder(Collections.parentActivity);
builder.setTitle(titleId)
.setIcon(android.R.drawable.stat_sys_warning)
.setMessage(messageId)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton("Learn More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, helpUri);
startActivity(intent);
}
});
}
return builder.create();
}
#Override
public void onRestart(){
super.onRestart();
Intent previewMessage = new Intent(StampiiStore.this, StampiiStore.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("StampiiStore", previewMessage);
this.finish();
}
}
And here is how I'm declaring the service in manifest file :
<service android:name="BillingService" />
<receiver android:name="BillingReceiver">
<intent-filter>
<action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
<action android:name="com.android.vending.billing.RESPONSE_CODE" />
<action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
</intent-filter>
</receiver>
Any suggestions how to connect to the market?
I had the same issue and probably your mistake is the same as mine. I was using a TabHost in my activities and I find out that TabSpec cannot bind to services. So check this :
Using getApplicationContext().bindService instead of just bindService
on your activity solves the problem as it is using the higher level
application context.
Can't you debug through that code? Probably, mBillingService.checkBillingSupported() returns false, caused by failing BillingService.bindToMarketBillingService().
i was facing problem like that on my sony ericssion w8 2.1 android device
what i did are the following :
1) getApplicationContext().bindService (as android-droid said)
2) reset my mobile and downloaded apk for market 2.3.4 version and installed it
3) then open the market app on mobile and clicked accepted and when the app i quitted
4) rerunned the app it was working fine
note: before doing this i tested my app on other device using market version 3.x and it was working so i did all these things ...