Image capture with camera & upload to Firebase (Uri in onActivityResult() is null) - android-studio

So I've got a problem, previously mentioned in the question I've asked: Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage
I've searched for the issue a bit more, and applied the Android Studio documentation: https://developer.android.com/training/camera/photobasics.html#TaskPhotoView
So, before you read the code, I basically want to say what is needed: I just want to capture a photo with camera and upload it directly to Firebase storage. To do that I need the Uri to contain the picture I just took (Uri.getLastPathSegment()), however I still couldn't succeed doing this.
So now, this is what my code look like (only related parts):
AndroidManifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
I have the res/xml/file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.serjardovic.firebasesandbox/files/Pictures" />
</paths>
and finaly the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Button b_gallery, b_capture;
private ImageView iv_image;
private StorageReference storage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog progressDialog;
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance().getReference();
b_gallery = (Button) findViewById(R.id.b_gallery);
b_capture = (Button) findViewById(R.id.b_capture);
iv_image = (ImageView) findViewById(R.id.iv_image);
progressDialog = new ProgressDialog(this);
b_capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Need a solution! Still, the app crashes after I take the picture and press the confirm button and I get the following crash report:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.serjardovic.firebasesandbox/com.serjardovic.firebasesandbox.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference

Try changing mCurrentPhotoPath = image.getAbsolutePath(); to mCurrentPhotoPath = "file:" + image.getAbsolutePath();.
I didnt spot any other differences from my code, which has worked.

So the answer is simple, thanks to #wilkas help in the comments. I just forgot to add the photoURI into filepath.putFile(photoURI), it was just filepath.putFile(uri), so the addition of code simply did nothing until I notices this. Hope this Q&A will help someone else with a similar problem!

Related

Android studio how to delete messages in chat properly

I'm facing an issue with deleting messages in my chat app. I have two types of messages, image and text. and I delete them like this:
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
Query query = dbRef.orderByChild("time").equalTo(msgTimeStamp);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot ds: snapshot.getChildren()) {
if (ds.child("sender").getValue().equals(myUID) && !ds.child("message").getValue().toString().equalsIgnoreCase("This message was deleted")) {
holder.messageLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
View view = LayoutInflater.from(mContext).inflate(R.layout.custon_view_for_dialog, null);
builder.setView(view);
Button delete = view.findViewById(R.id.delete);
Button cancel = view.findViewById(R.id.cancel);
final AlertDialog dialog = builder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteMessage(position);
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
And here is the delete function:
private void deleteMessage(int position) {
String msgTimeStamp = mChats.get(position).getTime();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
Query query = dbRef.orderByChild("time").equalTo(msgTimeStamp);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (final DataSnapshot ds: snapshot.getChildren())
{
if(ds.child("type").getValue().equals("text"))
{
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted");
ds.getRef().updateChildren(hashMap);
}
else
{
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference = firebaseStorage.getReferenceFromUrl(ds.child("message").getValue().toString());
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted");
hashMap.put("type","text");
ds.getRef().updateChildren(hashMap);
}
});
}
}
so my idea here is if the message is text, then I set the text as "This message was deleted" and if the message is an image, I change its type to text and set it also to "This message was deleted" and delete the image from Firebase Storage. The deleting works for me and here is how it looks like after deleting:
The issue I'm facing is that I can still delete the message even if it is already deleted!!
I don't want the AlertDialog for deleting to appear when I click on a deleted message !!.
as you can see I added this to my condition :
!ds.child("message").getValue().toString().equalsIgnoreCase("This message was deleted")
but the issue is still there, deleted messages can be deleted more than once! how can I prevent this from happening? please help

Fragment cannot be cast to java.util.concurrent.Executor error

I'm attempting to sign in or sign up using fragments, and after a successful sign-in/sign up, the HomeActivity supposed to load. The issue is that when I click the sign-in/sign up button, it returns to the same fragment instead of going to the HomeActivity.class. The app's initialization page is called LoginRegistrationActivity.class where it will call the SignIn fragment. I confirmed that Sign in/Sign Up is working well, but I am unable to navigate to the HomeActivity.class after successful authentication. I'm not sure if there is an issue with the AndroidManifest.xml file.
I got this logcat error after I clicked sign in:
java.lang.ClassCastException: com.fyp.selfzen.fragments.O_LoginRegistration.SignIn cannot be cast to java.util.concurrent.Executor
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn.login(SignIn.java:124)
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn$1.onClick(SignIn.java:87)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
SignIn.java fragment
public class SignIn extends Fragment{
private EditText editText_email, editText_password;
private String email, password;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
LoginRegisrationActivity loginRegistration;
public SignIn(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
}
public static SignIn newInstance(LoginRegisrationActivity loginRegistration) {
SignIn fragment = new SignIn(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_email = view.findViewById(R.id.editText_email_login_activity);
editText_password = view.findViewById(R.id.editText_password_login_activity);
TextView button_login = view.findViewById(R.id.button_login_activity);
TextView textView_signup_login = view.findViewById(R.id.textView_signup_login);
final SmoothCheckBox checkBox = view.findViewById(R.id.checkbox_login_activity);
checkBox.setChecked(false);
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = editText_email.getText().toString();
password = editText_password.getText().toString();
editText_email.clearFocus();
editText_password.clearFocus();
login(email, password);
}
});
textView_signup_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignUp f2 = SignUp.newInstance(loginRegistration);
loginRegistration.loadFrag(f2, getResources().getString(R.string.regis));
}
});
return view;
}
public void login(String email, String password) {
editText_email.setError(null);
editText_password.setError(null);
if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if(password.isEmpty()){
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else {
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Successfully sign in!", Toast.LENGTH_LONG).show();
// Intent i = new Intent(loginRegistration, HomeActivity.class); //First try to go to HomeActivity
Intent i = new Intent(getContext(), HomeActivity.class); //Second try
startActivity(i);
//loginRegistration.finish();
} else {
Toast.makeText(getContext(), "Sign in failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
} //onComplete
}); // firebaseAuth
}// else
} // login end
}
SignUp.java fragments
public class SignUp extends Fragment{
private EditText editText_name, editText_email, editText_password, editText_phoneNo;
private String name, email, password, phoneNo;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
LoginRegisrationActivity loginRegistration;
public SignUp(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
// Required empty public constructor
}
public static SignUp newInstance(LoginRegisrationActivity loginRegistration) {
SignUp fragment = new SignUp(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_name = view.findViewById(R.id.editText_name_register);
editText_email = view.findViewById(R.id.editText_email_register);
editText_password = view.findViewById(R.id.editText_password_register);
editText_phoneNo = view.findViewById(R.id.editText_phoneNo_register);
TextView button_submit = view.findViewById(R.id.button_submit);
TextView textView_login = view.findViewById(R.id.textView_login_register);
// Go to login page
textView_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn f1 = SignIn.newInstance(loginRegistration);
loginRegistration.loadFrag(f1, getResources().getString(R.string.login));
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText_name.getText().toString();
email = editText_email.getText().toString();
password = editText_password.getText().toString();
phoneNo = editText_phoneNo.getText().toString();
form();
}
});
return view;
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void form() {
editText_name.setError(null);
editText_email.setError(null);
editText_password.setError(null);
editText_phoneNo.setError(null);
if (name.equals("") || name.isEmpty()) {
editText_name.requestFocus();
editText_name.setError(getResources().getString(R.string.please_enter_name));
}
else if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if (password.equals("") || password.isEmpty()) {
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else if (phoneNo.equals("") || phoneNo.isEmpty()) {
editText_phoneNo.requestFocus();
editText_phoneNo.setError(getResources().getString(R.string.please_enter_phone));
}
else {
editText_name.clearFocus();
editText_email.clearFocus();
editText_password.clearFocus();
editText_phoneNo.clearFocus();
}
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Successfully registered!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(loginRegistration, HomeActivity.class);
Intent i = new Intent(getActivity(), HomeActivity.class);
startActivity(i);
//loginRegistration.finish();
}
else{
Toast.makeText(getContext(), "Sign up failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
} // end of form
}
LoginRegistrationActivity.class
public class LoginRegisrationActivity extends AppCompatActivity {
private String curent;
VideoView vide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_regisration);
vide = findViewById(R.id.vide);
String video_url = "android.resource://" + getPackageName() + "/" + R.raw.login_video;
Uri videoUri = Uri.parse(video_url);
vide.setVideoURI(videoUri);
vide.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
vide.requestFocus();
vide.start();
}
});
SignIn f1 = SignIn.newInstance(this);
loadFrag(f1, getResources().getString(R.string.login));
}
public void loadFrag(Fragment f1, String name) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(!name.equals(curent)){
curent =name;
ft.replace(R.id.frame_layout, f1, name);
}
ft.commitAllowingStateLoss();
}
}
AndroidManifest.xml
<activity
android:name="com.fyp.selfzen.activities.LoginRegisrationActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.fyp.selfzen.activities.HomeActivity"
android:label="#string/title_activity_home"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Have you solved your problem yet?
I ran into a similar but different issue when trying to use Fragments with FirebaseAuth. All of the documentation I found only referenced using Activities. Changing .addOnCompleteListener to .addOnSuccessListener and adding an .addOnFailureListener made my app work as expected. My app was originally crashing because of the Executor even though it would successfully authenticate users; the success/failure listeners fixed my issue.
My original code (written with help from Firebase Docs):
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( (java.util.concurrent.Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
FragmentFactory.startAdminFragment((MainActivity) getActivity());
} else
Toast.makeText( getContext(), "Authentication failed.", Toast.LENGTH_SHORT ).show();
}
});
}
Current/Working code:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener( new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FragmentFactory.startAdminFragment((MainActivity) getActivity());
}
})
.addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// If sign in fails, display a message to the user.
Log.d(TAG, "signInWithEmail:failure");
Toast.makeText( getContext(), e.getMessage(), Toast.LENGTH_LONG ).show();
}
} );
}
Note:
I only have 1 Activity so I was able to login and continue to my desired Fragment but you should be able to modify my code (FragmentFactory.startAdminFragment((MainActivity) getActivity());) to continue to your HomeActivity.class
This video helped a lot: https://www.youtube.com/watch?v=fPhy1PKR1Wg
I hope this helps.
In SignIn.java and SignUp.java fragment you add addOnCompleteListener() for firebaseAuth. So, pass arguments in it,
Instead of,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {}
To,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(getContext(), new OnCompleteListener<AuthResult>() {}
IF, getContext() not work then try to write getActivity().

Download File using download manager and save file based on click

I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks

Unable to find AppLovin SDK key. Please add meta-data android:name="applovin.sdk.key" android:value="YOUR_SDK_KEY_HERE" into AndroidManifest.xml

Hello everyone today I was busy with camera actions just applied rutin camera action on my application and apploving sdk key error actualy application is working but I need to know why I have this this warming on my android monitor
1. Here is my class where I start action and putExtra into intend
public class CameraActionFragment extends Fragment
{
private static final int REQUEST_CODE_IMG = 2;// for image
private static final int REQUEST_CODE_VIDEO = 1;// for video
public static final int RESULT_OK = -1;
Button btn_frag_camera_image;
Button btn_frag_camera;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_camera_action_3, container, false);
//return inflater.inflate(R.layout.fragment_camera_action_3, container, false);
btn_frag_camera_image = (Button) view.findViewById(R.id.btn_frag_camera_image);
btn_frag_camera = (Button) view.findViewById(R.id.btn_frag_camera);
// Image Action
btn_frag_camera_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Hello From Image", Toast.LENGTH_SHORT).show();
Intent intenImatToSec = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intenImatToSec, REQUEST_CODE_IMG);
}
});
// Camera Action
btn_frag_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
//intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_IMG) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
// aldıgımız imagi burda yonlendirdiğimiz sınıfa iletiyoruz
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intentBitMap.putExtra("byteArray", _bs.toByteArray());
startActivity(intentBitMap);
} else if (requestCode == REQUEST_CODE_VIDEO) {
Uri videoUrl = data.getData();
Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
startActivity(intenToDisplayVideo);
}
}
} }
1. And I play my video here
public class DisplayVideo extends Activity
{
private static final int REQUEST_CODE_VIDEO = 100;
VideoView videoView;
Button btn_cancel;
Button btn_send_cahallenge;
Button btn_image_play;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_video_activity);
videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
btn_cancel = (Button) findViewById(R.id.btn_display_image_cancel);
btn_send_cahallenge = (Button) findViewById(R.id.btn_display_image_send_cahallenge);
btn_image_play = (Button) findViewById(R.id.btn_display_image_play);
// CameraActionFragmentten gelen uri
Bundle extras = getIntent().getExtras();
Uri myUri = Uri.parse(extras.getString("videoUri"));
videoView.setVideoURI(myUri);
btn_image_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoView.start();
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences shp = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = shp.edit();
editor.putInt("frag_no", 2);
editor.commit();
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_VIDEO && resultCode == RESULT_OK) {
Uri videoUrl = data.getData();
videoView.setVideoURI(videoUrl);
//videoView.setMediaController(new MediaController(getApplicationContext()));
//videoView.requestFocus();
}
}
}
3. Cant find some usefull guide about AppLovin SDK key. Lately I
defined facebook sdk key and everything was good and after camera
actions ı have this problem
Error is
E/AppLovinSdk: Unable to find AppLovin SDK key. Please add meta-data android:name="applovin.sdk.key" android:value="YOUR_SDK_KEY_HERE" into AndroidManifest.xml.
07-29 16:24:26.390 12911-12911/? E/AppLovinSdk: Called with an invalid SDK key from: java.lang.Throwable:
at com.applovin.impl.sdk.AppLovinSdkImpl.a(Unknown Source)
at com.applovin.sdk.AppLovinSdk.b(Unknown Source)
at com.applovin.sdk.AppLovinSdk.c(Unknown Source)
at com.applovin.sdk.AppLovinSdk.b(Unknown Source)
at com.qihoo.security.SecurityApplication.onCreate(360Security:263)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1014)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4806)
at android.app.ActivityThread.access$1600(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1452)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
you have an invalid SDK key you need to setup AppLovin correctly
please try to add:
<meta-data android:name="applovin.sdk.key"
android:value="YOUR_SDK_KEY_HERE"/>
to your AndroidManifest file inside application tag.
Please check below link to find AppLovin SDK Key
Click Here To open AppLovin's Key Window

W/IMediaDeathNotifier﹕ media server died

I'm trying to record audio using Google Glass MIC but I keep getting W/IMediaDeathNotifier﹕ media server died error. Thoughts?
It should start recording on the first touch and stops on the second touch, but the error happens on the first click.
package com.google.android.glass.sample.charades;
import android.media.MediaRecorder;
import java.io.IOException;
import android.util.Log;
import android.os.Environment;
public class SlideshowActivity extends Activity {
private static final String LOG_TAG = "AudioRecordTest";
private MediaRecorder mRecorder = null;
private static String mFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/audiorecordtest.3gp";
private boolean recording = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slideshow);
mGestureDetector = new GestureDetector(this).setBaseListener(mBaseListener);
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
Log.e(LOG_TAG, "File name: " + mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
}
Log:
4242-4242/com.google.android.glass.sample.charades E/AudioRecordTest﹕ File name: /storage/emulated/0/audiorecordtest.3gp
4242-4255/com.google.android.glass.sample.charades W/IMediaDeathNotifier﹕ media server died
I've also added the following permission on the AndroidManifest.xml file:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
Try calling setPreviewDisplay, it isn't noted anywhere but some people say the preview is used as source to store the video file.
http://developer.android.com/reference/android/media/MediaRecorder.html#setPreviewDisplay(android.view.Surface)
I similar this on audio record.
Fix: change format recorder
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
Change example:
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

Resources