FirebaseTableCategory_insert_image_add(image sava and upload)_ideal

//Step 10 and 11 frgment thi karvu hoy to j leva and fragment,java ma load image no part kadi nakhvo jrrur na hoy to

//aama image add tse firebase ma example me jyare app kholis tyare me floatin buttton hse ie(pop box jeveu 1 small button hse)
aene pr click kris ne to crop image ,image gallary mathi save karvanu and pche save and upload karvanu to firebase ma save and upload tai jse
//
//aama phela firebase ma table nai bnaviye to pn chalse direct j bni jse ie sv thi phela aama firebase ma table bnavya vgar j try karvo
Step 1:firebase ma jai ne database pr click karvu aema real time database pr click karvu pche spiner pr click karvu database ni baju ma che aene pr
ane real time database select karvo
Step 2:pche firbase ma Category name aapi ne table bnai devu(image,table)  (aama image automatically Category vada tabale ma image add tai jse ie run app krishu tyare je image aapde gallary mathi laishu ae firebase storage ma save tai jse)
Step 3:rulse ma jai ne read and write true kri deva
{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": true,
    ".write": true
  }
}
Step 4:Storage na rules ma jai ne aatlu change kre kadvu
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
Step 5:activity_main.xml &MainActivity.java

Step 6:Categoryadd.xml
Step 7:aa ma Model name ne pkg bnavanu and aene under Category name nu java class bnavo
Model(Category.java)
Step 8:ViewHolder(MenuViewHolder.java)
Step 9:Common.java
Step 10:aa khale fragment thi aa activity kreye tyare j step 10 add karvu ie aa code fragment ma nai add karvano only main activity ma j add kre devo
Step 11:fragment.java &  activity_main..xml j lai leve

Step 5:activity_main.xml &MainActivity.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/maincontainer"
    tools:context="demoproject.aalap.com.aalap.MainActivity">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#EFEFEF">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/categoryRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none"
            android:padding="5dp" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fabNewCategory"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:src="@drawable/common_google_signin_btn_icon_dark" />

    </RelativeLayout>

</LinearLayout>

Step 5:MainActivity.java


public class MainActivity extends AppCompatActivity {

    //Add new category layout
    EditText edtCategoryName;
    ImageView imgCategory, imgCancel;
    TextView txtUpload,txtSave;

    LinearLayout maincontainer;
    Category newCategory;
    private Uri categoryImageUri = null;

    private FirebaseDatabase database;
    private FirebaseStorage storage;
    private StorageReference storageReference;
    private DatabaseReference categoryReference, productReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        maincontainer=findViewById(R.id.maincontainer);
        database = FirebaseDatabase.getInstance();
        categoryReference = database.getReference("Category");//aama("Category")lkheyu che aema firebase na table ma je name hoy ae lkhvu)
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabNewCategory);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAddCategoryDialog();
            }
        });
    }

    private void showAddCategoryDialog() {
        final android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(this);
        builder1.setCancelable(true);

        LayoutInflater inflater =LayoutInflater.from(this);
        final View layout_add_category = inflater.inflate(R.layout.add,null);

        imgCancel = layout_add_category.findViewById(R.id.imgCancel);

        imgCategory = layout_add_category.findViewById(R.id.imgCategory);
        edtCategoryName = (EditText) layout_add_category.findViewById(R.id.edtCategoryName);



        txtUpload = (TextView) layout_add_category.findViewById(R.id.txtUpload);
        txtSave = (TextView) layout_add_category.findViewById(R.id.txtSave);

        builder1.setView(layout_add_category);

        final android.app.AlertDialog alertDialog = builder1.create();

        imgCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setMinCropResultSize(300, 300)
                        .setAspectRatio(1, 1)
                        .start(MainActivity.this);
            }
        });

        txtUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });

        txtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Here just create new category
                if (newCategory != null)
                {
                    categoryReference.push().setValue(newCategory);
                    alertDialog.cancel();
                    Snackbar.make(maincontainer,"Category "+newCategory.getName()+" was added",Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        imgCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });


        alertDialog.show();
    }

    private void uploadImage() {
        if (categoryImageUri!=null) {
            final ProgressDialog mDialog = new ProgressDialog(this);
            mDialog.setMessage("Uploading...");
            mDialog.show();

            String imageName = UUID.randomUUID().toString();    //Random name image upload
            final StorageReference imageFolder = storageReference.child("categoryImages/" + imageName);

            imageFolder.putFile(categoryImageUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            mDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "Uploaded !!!", Toast.LENGTH_SHORT).show();
                            imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    //Set value for new category if image upload and we can get download link
                                    newCategory = new Category();
                                    newCategory.setName(edtCategoryName.getText().toString().trim());
                                    newCategory.setImage(uri.toString());

                                    Toast.makeText(getApplicationContext(), ""+edtCategoryName.getText().toString(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            mDialog.dismiss();
                            Toast.makeText(getApplicationContext(), ""+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());
                            mDialog.setMessage("Uploading : "+progress+"%");
                        }
                    });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                categoryImageUri = result.getUri();
                imgCategory.setImageURI(categoryImageUri);

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();

            }
        }
    }
}

Step 6:Categoryadd.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="12dp"
        android:background="#EFEFEF">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ADD CATEGORY"
            android:layout_centerHorizontal="true"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="#000000"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/imgCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/common_google_signin_btn_icon_dark"
            android:layout_alignParentEnd="true"/>

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#A8A8A8"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imgCategory"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:scaleType="fitXY"
                android:background="#efefef" />

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:layout_marginBottom="25dp">

                <EditText
                    android:id="@+id/edtCategoryName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:maxLength="20"
                    android:inputType="text"
                    android:singleLine="true"
                    android:textSize="20sp"
                    android:hint="Category Name" />

            </android.support.design.widget.TextInputLayout>

        </LinearLayout>

    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <TextView
            android:id="@+id/txtUpload"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:padding="15dp"
            android:background="#ffffff"
            android:text="UPLOAD"
            android:textSize="15dp"
            android:textColor="#000000"
            android:textStyle="bold"
            android:gravity="center"/>

        <TextView android:id="@+id/txtSave"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:padding="15dp"
            android:background="@color/colorPrimary"
            android:text="SAVE"
            android:textSize="15dp"
            android:textColor="#ffffff"
            android:textStyle="bold"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>

Step 7:Model
Category.java

package demoproject.aalap.com.aalap.Model;

/**
 * Created by ADMIN on 01-08-2018.
 */

public class Category {

    private String id, name, image;

    public Category() {
    }

    public Category(String id, String name, String image) {
        this.id = id;
        this.name = name;
        this.image = image;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}


Step 8:(ViewHolder)
MenuViewHolder.java

public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


    public MenuViewHolder(View itemView) {
        super(itemView);
    }

    @Override
    public void onClick(View view) {

    }
}

Step 9:Common.java
kshu add nai karvanu

Step 10:fragment(aa fragment ma add nai karvano jyaa thi parse karvano hoy tya j add kre devi mainactiviy ke draweer ma aatlu add kre deveu)
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                fragment.onActivityResult(requestCode, resultCode, data);
                Log.d("Activity", "ON RESULT CALLED");
            }
        }catch (Exception e){
            Log.d("ERROR", e.toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Step 11:fragment.java

public class CategoryFragment extends Fragment {

    View view;

    private FirebaseDatabase database;
    private FirebaseStorage storage;
    private StorageReference storageReference;
    private DatabaseReference categoryReference, productReference;
    private RecyclerView categoryRecyclerView;
    private FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;

    //Add new category layout
    EditText edtCategoryName;
    ImageView imgCategory, imgCancel;
    TextView txtUpload,txtSave;

    Category newCategory;
    private Uri categoryImageUri = null;

    public CategoryFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_category, container, false);

        try {
            ((AppCompatActivity) getActivity()).getSupportActionBar().show();
            getActivity().setTitle("Our Category");
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        database = FirebaseDatabase.getInstance();
        categoryReference = database.getReference(Config.category_tbl);
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference();

        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fabNewCategory);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAddCategoryDialog();
            }
        });


        loadCategory();


        //INITIALIZE RV
        categoryRecyclerView = view.findViewById(R.id.categoryRecyclerView);
        categoryRecyclerView.setHasFixedSize(true);
        categoryRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));

        return view;
    }

    private void showAddCategoryDialog() {
        final android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(getActivity());
        builder1.setCancelable(true);

        LayoutInflater inflater =LayoutInflater.from(getActivity());
        final View layout_add_category = inflater.inflate(R.layout.layout_add_category,null);

        imgCancel = layout_add_category.findViewById(R.id.imgCancel);

        imgCategory = layout_add_category.findViewById(R.id.imgCategory);
        edtCategoryName = (EditText) layout_add_category.findViewById(R.id.edtCategoryName);

        txtUpload = (TextView) layout_add_category.findViewById(R.id.txtUpload);
        txtSave = (TextView) layout_add_category.findViewById(R.id.txtSave);

        builder1.setView(layout_add_category);

        final android.app.AlertDialog alertDialog = builder1.create();

        imgCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setMinCropResultSize(300, 300)
                        .setAspectRatio(1, 1)
                        .start(getActivity());
            }
        });

        txtUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });

        txtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Here just create new category
                if (newCategory != null)
                {
                    categoryReference.push().setValue(newCategory);
                    alertDialog.cancel();
                    Snackbar.make(refreshLayout,"Category "+newCategory.getName()+" was added",Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        imgCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        alertDialog.show();
    }

    private void uploadImage() {
        if (categoryImageUri!=null) {
            final ProgressDialog mDialog = new ProgressDialog(getActivity());
            mDialog.setMessage("Uploading...");
            mDialog.show();

            String imageName = UUID.randomUUID().toString();    //Random name image upload
            final StorageReference imageFolder = storageReference.child("categoryImages/" + imageName);

            imageFolder.putFile(categoryImageUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            mDialog.dismiss();
                            Toast.makeText(getActivity(), "Uploaded !!!", Toast.LENGTH_SHORT).show();
                            imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    //Set value for new category if image upload and we can get download link
                                    newCategory = new Category();
                                    newCategory.setName(edtCategoryName.getText().toString().trim());
                                    newCategory.setImage(uri.toString());

                                    Toast.makeText(getContext(), ""+edtCategoryName.getText().toString(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            mDialog.dismiss();
                            Toast.makeText(getActivity(), ""+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());
                            mDialog.setMessage("Uploading : "+progress+"%");
                        }
                    });
        }
    }

    private void loadCategory() {
        FirebaseRecyclerOptions<Category> options = new FirebaseRecyclerOptions.Builder<Category>().setQuery(categoryReference, Category.class).build();
        adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(options) {
            @Override
            protected void onBindViewHolder(CategoryViewHolder holder, final int position, final Category model) {
                Picasso.with(getActivity())
                        .load(model.getImage())
                        .resize(300, 300)
                        .into(holder.imgCategory);
                holder.txtCategory.setText(model.getName());

                holder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        final String url=adapter.getRef(position).getKey();
                        Bundle bundle=new Bundle();
                        bundle.putString("categoryId",url);
                        AppCompatActivity activity=(AppCompatActivity) view.getContext();
                        ProductFragment productFragment=new ProductFragment();
                        productFragment.setArguments(bundle);
                        activity.getSupportFragmentManager().beginTransaction().replace(R.id.mainContainer,productFragment).addToBackStack(null).commit();
                    }
                });

            }

            @Override
            public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_category, parent, false);
                return new CategoryViewHolder(view);
            }
        };
        adapter.notifyDataSetChanged();     //Refresh data if data have changed
        adapter.startListening();
        categoryRecyclerView.setAdapter(adapter);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (adapter!=null)
        {
            adapter.startListening();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                categoryImageUri = result.getUri();
                imgCategory.setImageURI(categoryImageUri);

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();

            }
        }

    }
}



Comments

Popular posts from this blog

Seaborn

profile fragment firebase ie image and information vadu page update tay firebase ma

Payment ideal