My sharedprefrences not sharing correctly - java

I have an app where you upload images to my company server
So The user enters their login details, Email, Password and clientID(4 digit code)(in LoginActivity.java) and then this information must be passed to all the other activities, this passed information is then used to build a URL. Now the issue I am having is the Sharedprefrences doesn't share correctly...they either come up as NULL on the url or as just "email" or "password"
The Information is saved correctly in login activity but when i try to pass it to other activities it fails
Login activity here I save the prefrences
public class LoginActivity extends AppCompatActivity implements TextWatcher {
SharedPreferences MyPrefs;
Intent intent;
SharedPreferences.Editor editor;
public static final String PREF_NAME= "MYPREFS";
public static final String ID = "ClientID" ;
public static final String EMAIL = "username" ;
public static final String PASS = "password";
EditText email, password, id;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button buttonOne=findViewById(R.id.button);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent activity2Intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(activity2Intent);
}
});
MyPrefs= getSharedPreferences(PREF_NAME, 0);
editor = MyPrefs.edit();
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
email.setText(MyPrefs.getString(EMAIL,"username"));
password.setText(MyPrefs.getString(PASS,"password"));
id.setText(MyPrefs.getString(ID, "id"));
email.addTextChangedListener(this);
password.addTextChangedListener(this);
id.addTextChangedListener(this);
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
intent = new Intent(LoginActivity.this,CameraActivity.class);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
managePrefs();
}
#Override
public void afterTextChanged(Editable editable) {
managePrefs();
}
private void managePrefs(){
SharedPreferences.Editor editor =MyPrefs.edit();
editor.putString(EMAIL, email.getText().toString().trim());
editor.putString(PASS, password.getText().toString().trim());
editor.putString(ID, id.getText().toString().trim());
editor.apply();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Camera Activity this is where the shared prefrences must be passed to
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
String myURL;
String email;
String clientId;
String pwd;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
My code for calling sharedprefrences
SharedPreferences sharedPreferences = getSharedPreferences(LoginActivity.PREF_NAME, 0);
email = sharedPreferences.getString(LoginActivity.EMAIL, "username");
clientId = sharedPreferences.getString(LoginActivity.ID, "id");
pwd = sharedPreferences.getString(LoginActivity.PASS, "password");
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
} else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
pd.setMessage("Uploading, Please Wait....");
pd.show();
Intent intent = getIntent();
String Item= intent.getStringExtra("Spinner");
String Item2= intent.getStringExtra("Spinner2");
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-ruben.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("category",Item )
.appendQueryParameter("client",Item2 );
myURL=builder.build().toString();
Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
toast.show();
File imageFile=persistImage(bitmap,currentTimeStamp);
Ion.with(this)
.load(myURL)
.uploadProgressDialog(pd)
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
pd.cancel();
Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir=getApplicationContext().getFilesDir();
File imageFile=new File(filesDir, name + ".jpg");
OutputStream os;
try {
os=new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream=getContentResolver().openInputStream(data.getData());
bitmap=BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras=data.getExtras();
bitmap=(Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

To store data in shared preference do something like this:
private SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit();
editor.putString("email", email);
editor.putString("ID", id);
editor.putString("Pass", password);
editor.apply();
so I'll give you bit of explanation, when you write editor.putString("email", email); it tells editor to put your email against key "email".
Now, if you want to read these values back do it like this:
String email = getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("email", "");
String ID= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("ID", "");
String password= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("Pass", "");
Leme know if you don't understand anything.

getSharedPrerencences(String name, int mode) returns a reference to a shared preferences file name. That is, after the lines
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
your variable MyPrefs points to shared preferences file named password, which is probably not what you intended, since later you read from a file named MYPREFS.
Also, you don't need to call editor = MyPrefs.edit(); if you are just reading from the preferences, like you are doing in onCreate. That is why you get the warning that you have suppressed using #SuppressLint("CommitPrefEdits")

Related

How To Create An App That Allows For Profile Picture Upload/Change permanently

I want to allow users to upload a profile picture in my app so far I have achieved this, but the problem is when I exit the app the profile picture disappears, so I was asking is there a way to store the picture in cache I'm using glide but don't know how to go about it
changing load defaults on my oncreate method but still does not work.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_IMAGE = 100;
#BindView(R.id.img_profile)
ImageView imgProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadProfileDefault();
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
GlideApp.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
}
private void loadProfileDefault() {
GlideApp.with(this).load(R.drawable.baseline_account_circle_black_48)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
}
#OnClick({R.id.img_plus, R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePickerActivity.showImagePickerOptions(this, new ImagePickerActivity.PickerOptionListener() {
#Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
#Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePickerActivity.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want the selected image to remain even after closing the app how do I go about it please enter
There are 2 ways to achieve your result.
Using Shared Preferences. You can save your variable uri to shared preference and fetch data from it next time. For this, you can check if uri is available in Shared Preference or not.
Using Room database library.
Below is the code using Shared Preference :
Your onCreate() will be like :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadImageFromSharedPrefernce();
}
private void loadImageFromSharedPrefernce() {
SharedPreferences prefs = getSharedPreferences("PREF_NAME", MODE_PRIVATE);
if (prefs.contains("imageUrl")){
String imageUrl = prefs.getString("imageUrl", "");
loadProfile(imageUrl); //your method
}
else {
loadProfileDefault(); //your method
}
}
Your onActivityResult() will be like :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
saveImageToSharedPreference(uri);
loadImageFromSharedPrefernce();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveImageToSharedPreference(Uri uri) {
SharedPreferences.Editor editor = getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putString("imageUrl", String.valueOf(uri));
editor.apply();
}
You should save profile pic URI in SharedPreference which is being received in onActivityResult() method. Adding the sample code below, have a look.
private void saveProfilePicLocal(String uri){
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putString("profile_uri", uri); // Storing string
editor.commit(); // commit changes
}
Now you have to call above function in onActivityResult() method like below.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
saveProfilePicLocal(uri.toString())
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
After that, you should check whether you have any profile locally saved or not if there is any URI exists in SharedPreference read it and load otherwise load default one. Check the sample code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
//Check whether profile pic URI exists in Local SharedPreference
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
if (prefs.contains("profile_uri")){
String uri = pref.getString("profile_uri", null);
if(TextUtils.isEmpty(uri.trim())
loadProfileDefault();
else
loadProfile(uri);
}
}
Happy coding!.

Can't Edit or Update Room database entries

I am building an app where the user can store his/her usernames and passwords. The app has a simple UI. The Main thread has a list of entries, a FAB and a delete all icon on the action bar. My issue is that I am not able to edit and update existing entries.
I have the following code in the onCreate() of my MainActivity.java. When the user holds an entry, it launches the AddEditEntry.java activity. What happens here is that the launched activity does not have the existing entry data in its EditText fields:
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
In my AddEditEntry.java activity, I have the following code in the onClick of the save button. I am adding the new data as extras to the intent:
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
and back in my MainActivity.jav, this is my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
Entries entry = new Entries(username, hint, password);
viewModel.insert(entry);
Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();
}else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
int id = Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
if (id == -1){Toast.makeText(addEditEntry, "Something went wrong", Toast.LENGTH_SHORT).show();}
Entries entry = new Entries(username, hint, password);
entry.setId(id);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
}
When I run the app and try to edit an entry, the Toast message reads "Entry updated!" so it does run that code but the changes do not exist. I tried stopping the app and restarting it to refresh it but it still doesn't exist.
ViewModel.java:
public class EntryViewModel extends AndroidViewModel {
private EntryRepository repository;
private LiveData<List<Entries>> allEntries;
public EntryViewModel(#NonNull Application application) {
super(application);
repository = new EntryRepository(application);
allEntries = repository.getAllEntries();
}
public void insert(Entries entries){repository.insert(entries);}
public void update(Entries entries){repository.update(entries);}
public void delete(Entries entries){repository.delete(entries);}
public void deleteAll(){repository.deleteAllEntries();}
public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}
EntryRepository.java:
public class EntryRepository {
private EntryDAO entryDAO;
private LiveData<List<Entries>> allEntries;
public EntryRepository(Application application){
EntryDatabase database = EntryDatabase.getInstance(application);
entryDAO = database.generateDao();
allEntries = entryDAO.getAllEntries();
}
public void insert(Entries entries){new InsertEntryAsyncTask(entryDAO).execute(entries);}
public void update(Entries entries){new UpdateEntryAsyncTask(entryDAO).execute(entries);}
public void delete(Entries entries){new DeleteEntryAsyncTask(entryDAO).execute(entries);}
public void deleteAllEntries(){new DeleteAllEntriesAsyncTask(entryDAO).execute();}
public LiveData<List<Entries>> getAllEntries(){return allEntries;}
public static class InsertEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private InsertEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.insert(entries[0]);
return null;
}
}
public static class UpdateEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private UpdateEntryAsyncTask(EntryDAO entryDAO){
this.entryDAO = entryDAO;
}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.update(entries[0]);
return null;
}
}
public static class DeleteEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private DeleteEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.delete(entries[0]);
return null;
}
}
public static class DeleteAllEntriesAsyncTask extends AsyncTask<Void, Void, Void>{
private EntryDAO entryDAO;
private DeleteAllEntriesAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Void... voids) {
entryDAO.deleteAllEntries();
return null;
}
}
}
EntryDAO.java:
#Dao
public interface EntryDAO {
#Insert
void insert(Entries entries);
#Update
void update(Entries entries);
#Delete
void delete(Entries entries);
#Query("DELETE FROM entries_table")
void deleteAllEntries();
#Query("SELECT * FROM entries_table")
LiveData<List<Entries>> getAllEntries();
}
Entries.java:
#Entity(tableName = "entries_table")
public class Entries {
#PrimaryKey(autoGenerate = true)
private int id;
private String username, hint, password;
public Entries(String username, String hint, String password){
this.username = username;
this.hint = hint;
this.password = password;
}
public Entries(){}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getHint() {return hint;}
public void setHint(String hint) {this.hint = hint;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
This is the onCreate() of my AddEditEntry.java class. I've added the following Toast messages to see if it was receiving the data at all and turns out it doesn't. The Toast messages were empty:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addedit_entry);
usernameEditText = findViewById(R.id.username_field);
passwordEditText = findViewById(R.id.password_field);
hintEditText = findViewById(R.id.hint_field);
passwordABCD = findViewById(R.id.upp_checkbox);
passwordabcd = findViewById(R.id.low_checkbox);
password0123 = findViewById(R.id.num_checkbox);
passwordSymbols = findViewById(R.id.sym_checkbox);
radio4 = findViewById(R.id.four);
radio8 = findViewById(R.id.eight);
radio12 = findViewById(R.id.twelve);
radio16 = findViewById(R.id.sixteen);
Button generatePassword = findViewById(R.id.btn_password_generate);
Button saveEntry = findViewById(R.id.btn_save);
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_ID)){
setTitle("Edit Entry");
usernameEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME));
passwordEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD));
hintEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT));
Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT), Toast.LENGTH_SHORT).show();
}
else{setTitle("Add Entry");}
generatePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {passwordEditText.setText(generatedPassword());}});
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
}
Do it like this
In your MainActivity.java
....
....
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
entry = entries; // this is very important, entry holds the current edited item
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
// no need to pass the id, it's a autogenerated field
// intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
....
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
...
...
} else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK) {
// in an Edit operation, id should not be modified, so, no need to pass this parameter
// int id =
// Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
// entry already exists, so, no need to create a new one
//Entries entry = new Entries(username, hint, password);
//entry.setId(id);
entry.setUsername(username);
entry.setPassword(password);
entry.setHint(hint);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Other remarks...
In your RecyclerViewAdapter.java
// This is not needed. Your list is already created in your Room query
//private List<Entries> entries = new ArrayList<>();
private List<Entries> entries;
In your MainActivity.java
// This is not needed
// AddEditEntry addEditEntry;
....
....
// addEditEntry = new AddEditEntry();

Class variable not changing in IF or Switch statements

Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.

Retrieve contact from mobile's phone directory

This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}

Camera Issue in Android

I am trying to open camera intent in my app.But I just need to make sure that the image doesn't get saved in either the SD Card or in the Internal Storage.Also the image should get displayed in the app when the picture is clicked.
public class FBCheckInActivity extends Activity{
private CallbackManager callbackManager;
private LoginManager loginManager;
private File mFileTemp;
public static final int REQUEST_CODE_TAKE_PICTURE = 2;
public String path;
Bitmap sharingPhoto;
String caption="";
ImageView chooseImage;
EditText captionText;
Button postFacebook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_sharing);
printHashKey();
sharingPhoto= BitmapFactory.decodeResource(this.getResources(), R.drawable.no_image);
FacebookSdk.sdkInitialize(getApplicationContext());
fbSharing(sharingPhoto);
}
private void fbSharing(Bitmap sharingPhoto) {
chooseImage=(ImageView) findViewById(R.id.share_image);
chooseImage.setImageBitmap(sharingPhoto);
captionText=(EditText) findViewById(R.id.caption_text);
postFacebook=(Button) findViewById(R.id.buttonPost);
postFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginFaceBook();
}
});
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCamera();
}
});
captionText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
caption = captionText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
protected void onResume() {
super.onResume();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if(requestCode==REQUEST_CODE_TAKE_PICTURE){
Log.d("zambo","after selecting pic");
path = mFileTemp.getPath();
Log.d("zambo", path);
sharingPhoto = BitmapFactory.decodeFile(path);
chooseImage.setImageBitmap(sharingPhoto);
fbSharing(sharingPhoto);
}
else {
Log.d("zambo","callback manager for facebook sharing");
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
public void printHashKey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.urbanwand",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
public void loginFaceBook(){
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(FBCheckInActivity.this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
graphApi(accessToken);
}
#Override
public void onCancel() {
Toast.makeText(FBCheckInActivity.this, "cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(FBCheckInActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
}
public void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment
.getExternalStorageDirectory(), "IMG_"
+ ".jpg");
mImageCaptureUri = Uri.fromFile(mFileTemp);
} else {
/*
* The solution is taken from here:
* http://stackoverflow.com/questions
* /10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mFileTemp = new File(getFilesDir(), "IMG_"
+ ".jpg");
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
//Log.d("User_Photo", "cannot take picture", e);
}
}
public void graphApi(AccessToken accessToken){
GraphRequest request = GraphRequest.newUploadPhotoRequest(accessToken, "me/photos", sharingPhoto, caption, null, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d("zambo","On Completed Callback");
AlertDialog.Builder completeDialog = new AlertDialog.Builder(FBCheckInActivity.this);
completeDialog.setMessage("Thank you for sharing your happiness!!");
completeDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(FBCheckInActivity.this, DinerHotSellers.class));
overridePendingTransition(0, 0);
}
});
completeDialog.create();
completeDialog.show();
}
});
request.executeAsync();
}
This is what i have implemnted till now. But it doesn't give me the image back in the activity if it is stored in SD Card. Also the image is getting saved. Is is possible not to save the image in the storage media?
Thanks
A simple demo:
maim.xml
<button android:id="#+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="TakePhoto" button="">
<imageview android:id="#+id/imageView1" android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="wrap_content"></imageview></button>
MainActivity.java(not all)
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
private Button takePhotoBn;
private ImageView showImage;
private Uri imageUri;
private String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhotoBn = (Button) findViewById(R.id.button1);
showImage = (ImageView) findViewById(R.id.imageView1);
takePhotoBn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat(yyyyMMddHHmmss);
Date date = new Date(System.currentTimeMillis());
filename = format.format(date);
//File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File outputImage = new File(path,filename+.jpg);
try {
if(outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch(IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent(android.media.action.IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,TAKE_PHOTO);
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
Toast.makeText(MainActivity.this, ActivityResult resultCode error, Toast.LENGTH_SHORT).show();
return;
}
switch(requestCode) {
case TAKE_PHOTO:
Intent intent = new Intent(com.android.camera.action.CROP); //cut
intent.setDataAndType(imageUri, image/*);
intent.putExtra(scale, true);
intent.putExtra(aspectX, 1);
intent.putExtra(aspectY, 1);
intent.putExtra(outputX, 340);
intent.putExtra(outputY, 340);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
Toast.makeText(MainActivity.this, " ", Toast.LENGTH_SHORT).show();
//flush
Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intentBc.setData(imageUri);
this.sendBroadcast(intentBc);
startActivityForResult(intent, CROP_PHOTO);
break;
case CROP_PHOTO:
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageUri));
Toast.makeText(MainActivity.this, imageUri.toString(), Toast.LENGTH_SHORT).show();
showImage.setImageBitmap(bitmap); //show image
} catch(FileNotFoundException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
you need add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.CAMERA"> </uses-permission></uses-permission>

Categories

Resources