Uploading an image using activityResultLauncher , convert URI into bitmap - java

I am very new to this, and I am trying to put the pieces together so I will get the result I want. I don't really understand what I am doing wrong. The problem is when I am trying to put a profile photo, by the time I am pressing the selected photo to show on image view, the app crashes and I got a message like "URI cannot be null".
public class Profile extends AppCompatActivity {
private ImageView ProfileImg;
private String Tag;
private Uri imagePath = null;
private Uri imageUriPath;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
progressBar = findViewById(R.id.progressBar);
Button btnUpload = findViewById(R.id.btnUploadPhoto);
Button btnLogOut = findViewById(R.id.btnLogOut);
ProfileImg = findViewById(R.id.profile_img);
/* START ACTIVITY FOR RESULT*/
btnLogOut.setOnClickListener(view -> {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(Profile.this,MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
});
ProfileImg.setOnClickListener(view -> {
Intent photoIntent = new Intent(Intent.ACTION_PICK);
photoIntent.setType("image/*");
NewStartActivityForResult.launch(photoIntent);
});
btnUpload.setOnClickListener(view -> {
uploadImage();
});
/*Select photo from device*/
}
private ActivityResultLauncher<Intent> NewStartActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK){
Intent GotResults = result.getData();
if(GotResults == null)
{
Log.d(Tag,"InitializedActivityLaunchers: intent data is null");
return;
}
Uri imageUriPath = GotResults.getData();
GetImageInView();
}
});
private void uploadImage() {
FirebaseStorage.getInstance().getReference("images/" + UUID.randomUUID().toString()).putFile(imagePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful())
{
Toast.makeText(Profile.this, "Image Uploaded!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Profile.this, "Something went Wrong!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void GetImageInView(){
Bitmap bitmap = null;
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUriPath);
}catch (IOException e){
e.printStackTrace();
}
}
I first had a problem with startOnActivityResult in which I had a line through the command saying that is deprecated and MediaStore.Images.Media.getBitmap in which I had the same "error", deprecated on getBitmap, and I tried to use the new methods watching tutorials and other forums, but I think I cannot connect the activityResultLauncher with Bitmap because the output of activityResultLauncher is Intent and Bitmap needs URI.

In NewStartActivityForResult , just manage code as mentioned below
From
Uri imageUriPath = GotResults.getData();
To
imageUriPath = GotResults.getData();
You are declaring and initalising variable instead of only initalising

Related

Firebase storage,relatime database android :User does not have permission to access this object

I made a simple app that has a button and an ImageView. When I click on the button, an image (from drawable) gets displayed on the ImageView. I have also written the code for uploading the image on Firebase, but the exception message of onAddFailureListener gives the message User does not have permission to access this object. What should I do?
This answer does not help me.
User does not have permission to access this object . Firebase storage android
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
/*
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
*/
Objects.requireNonNull(taskSnapshot.getMetadata()).getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity() {
Intent intent = new Intent(this, ImagesActivity.class);
startActivity(intent);
}
}
Realtime Database
{
"rules": {
".read": true,
".write": true
}
}
Storage
rules_version = '2';
service firebase.storage {
match /b/savephoto-a1cc3.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Since I have seen a comment in your code that sounds like this "Allow access by all users", then I recommend you use the following rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
For testing purposes, it will work but I encourage you to change them when you'll launch the application.

Upload Images to Firebase Storage and have a link in Firebase Database

I am currently working on an Incident Reporting application which allows users to choose and upload images.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command "getDownloadUrl" but i believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Failed"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
ReportFragment
import static android.app.Activity.RESULT_OK;
import static com.firebase.ui.auth.AuthUI.getApplicationContext;
public class ReportFragment extends Fragment implements
AdapterView.OnItemSelectedListener{
private Button btnChoose,btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private EditText reportedBy;
private TextView date; //upstairs declare alr as mDisplayDate
private Spinner spinner; //downstairs declare alr as spinner3
private EditText location;
private Spinner spinner2; //downstairs declare alr as spinner2
private EditText details;
private Spinner spinner3; //downstairs declare alr as spinner1
private EditText remarks;
private EditText title;
private Button submitIncident;
public static TextView resultTextView3;
Button scan_btn3;
private ImageView imageView2;
private TextView imgUrl1;
DatabaseReference databaseIncidents;
FirebaseStorage storage;
StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
databaseIncidents =
FirebaseDatabase.getInstance().getReference("Incidents");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (Button) v.findViewById(R.id.btnChoose);
btnUpload = (Button) v.findViewById(R.id.btnUpload);
imageView = (ImageView) v.findViewById(R.id.imgView);
reportedBy = (EditText) v.findViewById(R.id.etreportedby);
// Below have already line 151
// date = (TextView) v.findViewById(R.id.tvdate);
location = (EditText) v.findViewById(R.id.etlocation);
details = (EditText) v.findViewById(R.id.etdetails);
remarks = (EditText) v.findViewById(R.id.etremarks);
title = (EditText) v.findViewById(R.id.ettitle);
submitIncident = (Button) v.findViewById(R.id.btnSubmit);
resultTextView3 = (TextView)v.findViewById(R.id.result_text3);
scan_btn3 = (Button)v.findViewById(R.id.btn_scan3);
imageView2 = (ImageView)v.findViewById(R.id.ivimagescardinput);
imgUrl1 = (TextView)v.findViewById(R.id.tvimagescard);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
// btnUpload.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// uploadImage();
// }
// });
scan_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new
Intent(getActivity(),ScanCodeActivity.class));
}
});
submitIncident.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incidentSubmit();
uploadImage();
Glide.with(getActivity()).load(URL).into(imageView2);
}
});
return`
}
private void incidentSubmit(){
String reportedname = reportedBy.getText().toString().trim();
String location1 = location.getText().toString();
String details1 = details.getText().toString();
String remarks1 = remarks.getText().toString();
String urgency1 = spinner.getSelectedItem().toString();
String type1 = spinner2.getSelectedItem().toString();
String splocation1 = spinner3.getSelectedItem().toString();
String date1 = mDisplayDate.getText().toString();
String title1 = title.getText().toString();
String qrlocation1 = resultTextView3.getText().toString();
String image1 = imgUrl1.getText().toString();
if(!TextUtils.isEmpty(reportedname)) {
String incidentId = databaseIncidents.push().getKey();
Incident incident = new
Incident(reportedname,location1,details1,remarks1,urgency1,type1,splocation1,date1,title1,qrlocation1,image1);
databaseIncidents.child(incidentId).setValue(incident);
Toast.makeText(getActivity(), "Incident Added", Toast.LENGTH_LONG).show();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new IncmanFragment());
fragmentTransaction.commit();
} else {
Toast.makeText(getActivity(), "All fields must be entered",Toast.LENGTH_LONG).show();
}
}
private void uploadImage() {
if (filePath != null) {
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
databaseIncidents.child("imageId").setValue(URL.toString());
}
});
}
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Any help or tutorials is greatly appreciated!
Database Inputs (not including image)
For storing the images to your Firebase Storage, you first set a correct reference and just store the image there, very similar to Firebase Database data storing.
To have a link in the Firebase Database, you can just use downloadUri you can get from storage and have it stored in the database.
The code for this looks something like this, you can take an inspiration from this and come up with a code that suits you more:
private void uploadFile(Bitmap bitmap) {
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = ImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("whatTheFuck:",exception.toString());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (!task.isSuccessful()) {
Log.i("problem", task.getException().toString());
}
return ImagesRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());
Log.i("seeThisUri", downloadUri.toString());// This is the one you should store
ref.child("imageURL").setValue(downloadUri.toString());
} else {
Log.i("wentWrong","downloadUri failure");
}
}
});
}
});
}
If i understand correctly you can upload images to storage succesfully but you are having trouble when you want to get that image direct url.
Try this code:
StorageReference storageRef=FirebaseStorage.getInstance().getReference().child("images/"+ UUID.randomUUID().toString());
storageRef.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
//This is your image url do whatever you want with it.
}
});
}
}
});

save url when re rotate screen from landscape to protrit

I'm trying to play video on player and the video is url that I fetch from an api
so I have a channels in recycleview1 and when I click on one channel the channel start play in new activity
in that activity the player take half of screen and the rest is for recycleview2 which contain some channels for easy and fast navigate between channels
so when I open the channel from recycleview1 and it start playing then I rotate the screen to landscape it work fine then restore the screen to portrate again the channel still working
but the problem is when I click on channel from recycleview2 which lead to update the url that already played and start the new one
so each time I click on channel from recycleview2 the videoview updated to new channel url that clicked
I face problem when I rotate the screen after played channel from recycleview2 the videoview start play a channel that I clicked from recyclewview1 before clicking on new channel from recycleview2 because it return to onCreate method which build the url depend on the information passed with on click
so I used to save the instance state of url so when I rotate the screen to landscape the vidoeview still played the last channel that played
but the problem is when I re rotate the screen to portrate again the videoview here return to the first channel played when start the activity
I tried to save instance state too but it doesn't working
this is the code:
public class TVChannel extends AppCompatActivity implements
TVAdapter.TVAdapterOnClickHandler {
private VideoView videoView;
private int position = 0;
private String video;
private MediaController mediaController;
String mChannelTitle;
String mChannelApp;
String mChannelStreamname;
String mChannelCat;
TVAdapter mAdapter;
RecyclerView mSportsList;
private TextView mCategory;
private TextView mErrorMessageDisplay;
private ProgressBar mLoadingIndicator;
Context mContext ;
public TVItem channelObject;
Uri vidUri;
String myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_tv_channel);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapper();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
} else {
setContentView(R.layout.activity_tv_channel2);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(false);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.controlBackground));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapperFullScreen();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putString("video", String.valueOf(vidUri));
videoView.start();
}
// After rotating the phone. This method is called.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
video = savedInstanceState.getString("video");
videoView.start();
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel, View view) {
if (channel != null) {
mChannelTitle = String.valueOf(channel.getTitle());
mChannelApp = String.valueOf(channel.getApp());
mChannelStreamname = String.valueOf(channel.getStreamName());
}
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(playerControlView.getMediaControllerWrapper());
//
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
}
private void showTVDataView() {
mErrorMessageDisplay.setVisibility(View.INVISIBLE);
mSportsList.setVisibility(View.VISIBLE);
}
private void showErrorMessage() {
mSportsList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(TVChannel.this, jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
mCategory.setText(TVData.get(0).getCat());
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
showErrorMessage();
}
}
}
}
you can see that I use:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
}
else{
}
to set content view for portrait and landscape
and inside else this is the code that I use to save the url in landscape mode:
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
and if savedInstanceState null so build url like this from on click information that I pass in portrait mode:
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
how can I save the url channel when I re rotate screen from landscape to portrait mode again?

How to stop receiving data from a web server?

I have an Activity that receives and displays information from the web server and saves it to the database and, if it has already received the information once, it will read from the database.
There is no problem running the program, only when the user enters the activity and still does not receive the information from the server, exit the activity, in another Activity the application crashes.
This problem is to quit the activity because when staying in activity and loaded data completely, we have not any problems. also when reading data from the database we have not any problems.
How can stop receive data when the user quit the activity or solve this problem form another way.
This is my activity codes:
public class ShowProduct extends AppCompatActivity {
private RequestQueue mQueue;
private String id;
private Products products;
private DatabaseHelper databaseHelper;
private ProgressBar progressBar;
private Typeface IranSans,IranSansBold;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_product);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
databaseHelper = new DatabaseHelper(this);
products = new Products();
progressBar = (ProgressBar)findViewById(R.id.progressBar);
IranSans = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb.ttf");
IranSansBold = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb_Bold.ttf");
Bundle extras = getIntent().getExtras();
id= extras.getString("id");
try {
if (databaseHelper.dbContentChecker(id)) {
if (connectionCheck() == false){
Intent intent = new Intent(this, NoInternetConnection.class);
startActivity(intent);
}
String url = "https://website.com/webserver/?id=" + id;
mQueue = Volley.newRequestQueue(this);
jsonParse(url);
} else {
products = databaseHelper.getOneProduct(id);
showFromDB(products);
}
}catch (Exception ex){
}
//footer set
Footer footer = new Footer();
footer.footerSet(ShowProduct.this, this);
}
private void showFromDB(Products products) {
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(products.getName());
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(products.getImage())
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(products.getContent()));
progressBar.setVisibility(View.GONE);
}
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("send");
JSONObject send = jsonArray.getJSONObject(0);
String title = send.getString("title");
String image = send.getString("image");
String content = send.getString("content");
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(title);
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(image)
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(content));
//Save in Database
try {
products.setProductId(id);
products.setName(title);
products.setImage(image);
products.setContent(content);
databaseHelper.editProduct(products);
}catch (Exception ex){
Toast.makeText(ShowProduct.this, "Error DB", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
//Toast.makeText(getApplicationContext(), ""+Temp , Toast.LENGTH_SHORT).show();
}
public boolean connectionCheck() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
}
First of all you should think about your architecture. Handling fetching data inside an Activity is not a good practice. Look at MVVM or MVP and try to put your data fetching logic in another layer.
For your specific problem you should try to cancle the request in the onStop() method of the Activity, see:
https://developer.android.com/training/volley/simple#cancel

Passing Image Captured to FilePathUri

I have problem to pass the Captured Image to the FilePathUri where the image will be stored and then uploaded to Firebase. I need to integrate them together cause the FilePathUri is always returning null.
Hope somebody can show me an Example with Code. Thanks
On-Create Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_takephoto);
// Assign FirebaseStorage instance to storageReference.
storageReference = FirebaseStorage.getInstance().getReference();
// Assign FirebaseDatabase instance with root database name.
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);
// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);
// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);
// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(PhotoActivity.this);
// Adding click listener to Choose image button.
ChooseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FilePathUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
OnActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Line 1:
FilePathUri = data.getData();
// Line 2:
Bitmap photo = (Bitmap) data.getExtras().get("data");
SelectImage.setImageBitmap(photo);
ChooseButton.setText("Image Selected");
}
}
Uploading Image Part
// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + FilePathUri);
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
progressDialog.dismiss();
// Showing toast message after done uploading.
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
#SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Hiding the progressDialog.
progressDialog.dismiss();
// Showing exception erro message.
Toast.makeText(PhotoActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
}
});
}
else {
Toast.makeText(PhotoActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}

Categories

Resources