Issue
I am adding images to the firebase storage. But before adding i want to check the network connectivity for that i used a AsyncTask. But after adding it my app started crashing...Following is my AddImages.java File of fragment_add_images.xml file
package com.example.lenovo.jdstudio;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
import static java.security.AccessController.getContext;
/**
* A simple {@link Fragment} subclass.
*/
public class AddImages extends Fragment {
private static final int GALLERY_REQUEST = 1;
ArrayAdapter<CharSequence> adapter;
private EditText mtitle;
private EditText mresolution;
private EditText mImageType;
private EditText mprice;
private Spinner mcategory;
private ImageView mSelectImage;
private Button mSbtn;
private ProgressDialog mProgress;
private Uri mImageuri = null;
private StorageReference mStorage;
public AddImages() {
// Required empty public constructor
}
// checks if connection has active_internet connection
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
return true;
}
return false;
}
// checks if user is connected to the any network
private static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_images, container, false);
mtitle = (EditText) v.findViewById(R.id.edit_title);
mresolution = (EditText) v.findViewById(R.id.edit_resol);
mSelectImage = (ImageView) v.findViewById(R.id.imageView);
mImageType = (EditText) v.findViewById(R.id.edit_image_type);
mprice = (EditText) v.findViewById(R.id.edit_price);
mcategory = (Spinner) v.findViewById(R.id.cat_spin);
mSbtn = (Button) v.findViewById(R.id.submit_btn);
//Initialisee progress dialog
mProgress = new ProgressDialog(getContext());
mProgress.setIndeterminate(true);
mProgress.setMessage("Uploading Please Wait...");
// DB instance
mStorage = FirebaseStorage.getInstance().getReference();
//setting the spinner
adapter = ArrayAdapter.createFromResource(getContext(), R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mcategory.setAdapter(adapter);
final String category_value = mcategory.getSelectedItem().toString();
//Image Selection from gallery
mSelectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
//Posting the activity on the database
mSbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
return v;
}
// Start adding the images to the DB
private void startAdding(String category_value) {
StorageReference filepath = mStorage.child("My_Images").child(category_value).child(mImageuri.getLastPathSegment());
filepath.putFile(mImageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mProgress.setMessage(e.getMessage());
mProgress.show();
}
});
}
//show Alert box
private void showAlert(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(title);
builder.setMessage(message);
builder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
//To show the progress dialog
private void showProgressDialog(boolean shouldShow) {
if (shouldShow) {
mProgress.show();
} else {
mProgress.dismiss();
}
}
// checks if user has entered all the field
@NonNull
private Boolean isFormValid() {
String title_val = mtitle.getText().toString().trim();
String resolution_val = mresolution.getText().toString().trim();
String image_type_val = mImageType.getText().toString().trim();
String price_val = mprice.getText().toString().trim();
String category_value = mcategory.getSelectedItem().toString();
if (!TextUtils.isEmpty(title_val) &&
!TextUtils.isEmpty(resolution_val) &&
!TextUtils.isEmpty(image_type_val) &&
!TextUtils.isEmpty(price_val) &&
mImageuri != null &&
category_value != "Select Category") {
return true;
}
return false;
}
//Reset All the value after uploading the images
private void clearAll() {
mtitle.setText("");
mresolution.setText("");
mprice.setText("");
mImageType.setText("");
mcategory.setSelection(0);
mSelectImage.setImageResource(R.mipmap.add_btn);
}
// Set the selected image from the gallery to the Imageview
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
mImageuri = data.getData();
mSelectImage.setImageURI(mImageuri);
}
}
// perform all the task on the background Thread
class UploadingTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isFormValid()) {
showProgressDialog(true);
} else {
showAlert("Error", "Please fill all the details");
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
showProgressDialog(false);
if (aBoolean) {
showAlert("Successful", "Upload complete.");
} else {
showAlert("Failed", "Upload doesn't complete");
}
clearAll();
}
@Override
protected Boolean doInBackground(String... params) {
String catValue = params[0];
if (hasInternetAccess(getContext())) {
showAlert("Error", "Network is not available");
} else {
startAdding(catValue);
}
return null;
}
}
}
Following is the Error I am getting
E/WindowManager: android.view.WindowLeaked: Activity com.example.lenovo.jdstudio.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42192078 V.E..... R....... 0,0-683,378} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:422)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:250)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:297)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:958)
at com.example.lenovo.jdstudio.AddImages.showAlert(AddImages.java:173)
at com.example.lenovo.jdstudio.AddImages.access$300(AddImages.java:45)
at com.example.lenovo.jdstudio.AddImages$UploadingTask.onPreExecute(AddImages.java:236)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.lenovo.jdstudio.AddImages$2.onClick(AddImages.java:136)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
D/GraphicBuffer: create handle(0x6178f580) (w:688, h:378, f:1)
D/OpenGLRenderer: Flushing caches (mode 0)
D/GraphicBuffer: close handle(0x6177a680) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x63688d98) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x6178f580) (w:688 h:378 f:1)
D/ActivityThread: ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy@42190ad0
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 2
D/SQLiteDatabase: beginTransaction()
D/SQLiteDatabase: endTransaction()
V/FA: Inactivity, disconnecting from the service
I/Process: Sending signal. PID: 10017 SIG: 9
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Please Help me out!!
Solution
This is a problem I came across when attempting to show a ProgressDialog
in onPreExecute()
in an AsyncTask
. The only solution I found was to manage the dialog outside the task, so instead of
mSbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
try instead:
mSbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isFormValid()) {
showProgressDialog(true);
new UploadingTask().execute(category_value);
} else {
showAlert("Error", "Please fill all the details");
}
}
});
And remove the corresponding code from the onPreExecute()
method in UploadingTask
.
I think the dialog can be dismissed in onPostExecute()
without problem, but you could set up a callback interface to the task to notify the caller when the task is complete to allow it to manage the dismissal.
Answered By - AGDownie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.