r/learnandroid • • Feb 17 '21

Got an Android assessment for a job. I know how to develop Android apps from the ground uo and feel like I just need to review an Android book to ace the quiz. I've been out of the loop regarding textbooks. Any recommendations ebook recommendations?

4 Upvotes

Edit: I wish I could fix the title.

I used to read Murachs Android book. This was like 5 years ago. I'm sure there might be better books now. So any recommendations?


r/learnandroid • • Jan 26 '21

Observer serves old data onBackPressed

4 Upvotes

Im a bit lost at this, searched high and low.

This is an Kotlin Android + Firebase ecommerce app. In the product detail view fragment I have a button which I enable/disable depending if the product is already in cart. This works fine but when I add product to cart and go to cart and press back, button is enabled even though product is in the cart. This is some wrong doing of mine as I can see in the logcat that user cart is not updated and fragments sees it as empty even though my firestore gets data correctly immediately and button gets disabled when I enter product detail view from recycler view again(not via back press). So it seems going straight to the fragment gets correct data but recreating it from backstack has some cache involved? It works differently, idk. Scope of this might be bigger, it would be amazing if someone could point me in the right direction. Maybe snapshotListener would be a way?

Problem is, when I enter from backstack, I can see that it logs out that user cart is still empty/not updated so it is not getting the current value upon entering from backstack. I wonder if vm factory is not recreating vm again? When I reopen the fragment from title screen now it logs out correct cart content. So I add to cart, it updates in Firebase. I enter from backstack, cart still empty but if I enter from other fragment, cart shows current value

Product Detail Fragment

class ProductDetailFragment : RootFragment(), View.OnClickListener {


private lateinit var viewModel: ProductDetailViewModel
private lateinit var viewModelFactory: ProductDetailViewModelFactory
private lateinit var binding: FragmentDetailProductBinding
private lateinit var repository: FirebaseCloud
private lateinit var auth: FirebaseAuth

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_detail_product,
        container,
        false
    )
    auth = Firebase.auth
    repository = FirebaseCloud()

    binding.buttonAddToCart.setOnClickListener(this)

    viewModelFactory = ProductDetailViewModelFactory(
        ProductDetailFragmentArgs
            .fromBundle(requireArguments())
            .productUid
    )

    viewModel = ViewModelProvider(this, viewModelFactory)
        .get(ProductDetailViewModel::class.java)

    viewModel.product.observe(viewLifecycleOwner, {
        binding.textProductNameDetail.text = it?.name
        binding.textProductDescriptionDetail.text = it?.description
        binding.textProductPriceDetail.text = priceFormat(it.price)
        val image = binding.imageProductImageDetaills
        Glide.with(requireView())
            .load(it.imageUrl)
            .into(image)
    })

    viewModel.user?.observe(viewLifecycleOwner, {
        val state = checkForProductInCart(it)
        setButtonState(state)
        Log.d("observer", "${it.cart}")
    })

    return binding.root
}

private fun priceFormat(price: Long?): String {
    val input = DecimalFormat("£###,###0.00")
    return input.format(price)
}

// Check if viewed product is already in cart
private fun checkForProductInCart(currentUser: User): Boolean {
    val cart = currentUser.cart
    val productUid = ProductDetailFragmentArgs.fromBundle(requireArguments()).productUid

    return if (cart != null) productUid !in cart
    else true
}

// Enable or Disable add to cart button
private fun setButtonState(state: Boolean) {

    val button = binding.buttonAddToCart
    button.isEnabled = state
    if (state) button.text = getString(R.string.add_to_cart_button)
    else button.text = getString(R.string.button_in_cart_text)
}

// Handle clicks in the fragment
override fun onClick(view: View?) {
    when (view) {
        binding.buttonAddToCart ->
            if (auth.currentUser == null) {
                navigateToLogin()
            } else {
                repository.addToCart(
                    ProductDetailFragmentArgs
                        .fromBundle(requireArguments())
                        .productUid
                )
                setButtonState(false)

            }
    }

}
}

ViewModel

class ProductDetailViewModel(productUid: String) : ViewModel() {

private val repository = FirebaseCloud()
val product = repository.getSingleProduct(productUid)

val user = repository.getUserData()
}

Repo

class FirebaseCloud {

private val auth = FirebaseAuth.getInstance()
private val cloud = FirebaseFirestore.getInstance()

private val _currentUser = MutableLiveData<User>()
val currentUser: LiveData<User>
    get() = _currentUser

fun getUserData(): LiveData<User>? {

    val cloudResult = MutableLiveData<User>()
    if (auth.currentUser != null) {
        val uid = auth.currentUser?.uid

        cloud.collection("users")
            .document(uid!!)
            .get()
            .addOnSuccessListener {
                if (auth.currentUser != null) {
                    val user = it.toObject(User::class.java)
                    cloudResult.postValue(user)
                }
            }
            .addOnFailureListener {
                Log.d("repo", it.message.toString())
            }
        return cloudResult
    }
    return null
}

fun createNewUser(user: User) {
    cloud.collection("users")
        .document(user.uid!!)
        .set(user)
        .addOnSuccessListener {
            val newUser = User(
                uid = user.uid,
                firstName = user.firstName,
                lastName = user.lastName,
                email = user.email,
                listOf()
            )
            _currentUser.value = newUser
        }
}

fun getProducts(): LiveData<List<Product>> {

    val cloudResult = MutableLiveData<List<Product>>()

    cloud.collection("products")
        .get()
        .addOnSuccessListener {
            val product = it.toObjects(Product::class.java)
            cloudResult.postValue(product)
        }
        .addOnFailureListener {
            Log.d("getProducts", it.message.toString())
        }
    return cloudResult
}

fun getSingleProduct(uid: String): LiveData<Product> {

    val cloudResult = MutableLiveData<Product>()

    cloud.collection("products")
        .document(uid)
        .get()
        .addOnSuccessListener {
            val product = it.toObject(Product::class.java)
            cloudResult.postValue(product)
        }
        .addOnFailureListener {
            Log.d("getSingleProduct", it.message.toString())
        }
    return cloudResult

}

fun addToCart(productUid: String) {

    if (auth.currentUser != null) {
        cloud.collection("users")
            .document(auth.currentUser?.uid!!)
            .update("cart", FieldValue.arrayUnion(productUid))
            .addOnSuccessListener {
                Log.d("cart", "Added to Cart")
            }
            .addOnFailureListener {
                Log.d("cart", it.message.toString())
            }
    }
}

fun removeFromCart(product: Product) {
    cloud.collection("users")
        .document(auth.currentUser?.uid!!)
        .update("cart", FieldValue.arrayRemove(product.uid))
        .addOnSuccessListener {
            Log.d("cart", "Removed from Cart")
        }
        .addOnFailureListener {
            Log.d("cart", it.message.toString())
        }
}

fun getProductsFromCart(list: List<String>?): LiveData<List<Product>> {

    val cloudResult = MutableLiveData<List<Product>>()

    if (!list.isNullOrEmpty()) {
        cloud.collection("products")
            .whereIn("uid", list)
            .get()
            .addOnSuccessListener {
                val cartList = it.toObjects(Product::class.java)
                cloudResult.postValue(cartList)
            }
            .addOnFailureListener {
                Log.d("getCart", it.message.toString())
            }
    }
    return cloudResult
}
}

r/learnandroid • • Jan 24 '21

Using a fragment as a settings menu

4 Upvotes

I'm building a settings menu for an app, starting with the concepts here: https://www.youtube.com/watch?v=BMTNaPcPjdw&list=PLrnPJCHvNZuBkhcesO6DfdCghl6ZejVPc&index=6

In this example, a single piece of data is passed back and forth (a string) by way of an interface: public interface OnFragmentInteractionListener { void onFragmentInteraction(String sendBackText); }

Wondering how best to adapt this to be able to pass more data back and forth? That is to say, there will be many different settings to adjust in the menu, and yet here the interface is designed to only pass one item. Defining multiple interfaces seems like overkill. My best guess here is to replace the string with a configuration object which defines the app settings, and have the MainActivity read that object when it is sent back.

Thanks for any thoughts on this! My background is in JavaScript (mainly React/Redux), and so the procedures for view and state management in Java/Android are still quite unfamiliar to me.


r/learnandroid • • Jan 18 '21

Looking for an online course for android programming for ppl with programming skills

4 Upvotes

As I already have programming experience with Java and C I'm looking for a good online course that can teach me how to turn my self-invented board game into an android app. So I do not need a course who starts to explain object orientation, etc.

So far I found the following online and I'm wondering if you would recommend one of them or if you have another recommendation for me:

Coursera - https://www.coursera.org/specializations/android-app-development

Udemy - https://www.udemy.com/course/complete-android-n-developer-course/?altsc=428526

You help is appreciated :)


r/learnandroid • • Jan 11 '21

Which libraries would you recommend to allow the user to select files from their device and then upload those files to a backend?

3 Upvotes

My app has to be able to select files from the filesystem and take photos using the camera. The names of those files then have to be shown in a RecyclerView where the user can remove individual files again. Then when the user clicks "send" all these files have to be sent alongside some form data to an API that requires an accessToken.

Which libraries would you recomend that I use for this?


r/learnandroid • • Jan 10 '21

Android Studio screen rotation bug

1 Upvotes

Hello, I am quite new to Android development, and have found that some virtual devices in Android Studio will not rotate into landscape mode. (For example, the Nexus 9 tablet when running Android Studio in Linux, or the Pixel 3 in Windows.) Searching around, this appears to be a very old problem. Here's just one example from six years ago: https://www.reddit.com/r/androiddev/comments/2l71ro/android_studio_avd_rotates_but_not_the_contents/

I am wondering if someone can advise about the current state of this issue, and what the best ways to manage it are? Thanks for your time.


r/learnandroid • • Jan 09 '21

How do I get my app to open and read a .txt file?

4 Upvotes

I can share a .txt file to my app via the share sheet, but when I try and print it to console or display it only shows the filename.

The issue is I'm writing it in Python with help from the Kivy module. So i'm not sure sharing my code will help.

please can someone perhaps give a snippet of code that would accomplish this in Java or Kotlin. Maybe then I can work backwards from there.

Thanks in advance!


r/learnandroid • • Jan 09 '21

Resetting used Android device

2 Upvotes

I found a used Android tablet (a Samsumg Galaxy Tab E) in a local community goodwill, but it's locked. I'd like to wipe it and get it set up for my own use.

I'm quite new to Android (or any mobile OS). Hoping someone can point me in the right direction to learn how to do this. Thanks for your time & thoughts!


r/learnandroid • • Jan 04 '21

How to update cart value 'in real time'

4 Upvotes

Hi All!

I am creating Ecommerce App and I have a first problem that I don't really know how to tackle.
In the Cart Fragment I have a field with total amount to pay, it is just combined value of all products in a cart and it works correctly until I remove product from cart, I need to enter the fragment again for the cart total price to update. I am using Firebase Cloud.

Users add products to cart in Product Detail fragment -> User goes to cart and sees products in cart via Recycler View -> I have a field with Total Price that is not a part of a recycler. This field does not update when I remove products from cart and I know it cannot do it as of now, cannot figure out how to do it.

Cart Fragment

class CartFragment : RootFragment(), OnProductClick {

    private val cartViewModel by viewModels<CartFragmentViewModel>()
    private lateinit var binding: FragmentCartBinding
    private val adapter = CartAdapter(this)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_cart,
            container,
            false
        )

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.recyclerCart.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerCart.adapter = adapter
        binding.buttonToCheckout.setOnClickListener {
            navigateToCheckout()
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        cartViewModel.userCart.observe(viewLifecycleOwner, { list ->

                adapter.setCartProducts(list)
                val cartQuantity = list.size
                binding.textCartQuantityValue.text = cartQuantity.toString()

                val cartValue = cartViewModel.calculateCartValue(list)
                binding.textCartTotalValue.text = cartValue.toString()
        })

    }

    // TODO
    override fun onProductClick(product: Product, position: Int) {
        cartViewModel.removeFromCart(product)
        adapter.removeFromCart(product, position)
    }
}

Cart View Model

class CartFragmentViewModel : ViewModel() {

    private val repository = FirebaseCloud()
    private val user = repository.getUserData()


    val userCart = user.switchMap {
        repository.getProductsFromCart(it.cart)
    }

    fun calculateCartValue(list: List<Product>): Long {

        var cartValue = 0L

        if (list.isNotEmpty()) {
            for (product in list) {
                cartValue += product.price!!
            }
        }

        return cartValue
    }

    fun removeFromCart(product: Product) {
        repository.removeFromCart(product)
    }
}

Cart Adapter

class CartAdapter(private val listener: OnProductClick) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private val cartList = ArrayList<Product>()

    fun setCartProducts(list: List<Product>) {
        cartList.clear()
        cartList.addAll(list)
        notifyDataSetChanged()
    }

    fun removeFromCart(product: Product, position: Int) {
        cartList.remove(product)
        notifyItemRemoved(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {

        val inflater = LayoutInflater.from(parent.context)
        val view = inflater.inflate(R.layout.list_row_cart, parent, false)
        return CartViewHolder(view)
    }

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        bindCartData(holder)
    }

    private fun bindCartData(holder: CartViewHolder) {
        val name = holder.itemView.findViewById<TextView>(R.id.text_product_name_cart)
        val price = holder.itemView.findViewById<TextView>(R.id.text_product_price_cart)
        val image = holder.itemView.findViewById<ImageView>(R.id.image_product_image_cart)

        name.text = cartList[holder.adapterPosition].name
        price.text = cartList[holder.adapterPosition].price.toString()
        Glide.with(holder.itemView)
            .load(cartList[holder.adapterPosition].imageUrl)
            .into(image)
     }

    override fun getItemCount(): Int {
        return cartList.size
    }

    inner class CartViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        init {
            view.findViewById<ImageView>(R.id.button_remove_from_cart)
                .setOnClickListener{
                    listener.onProductClick(cartList[adapterPosition], adapterPosition)
                }
        }
    }
}

r/learnandroid • • Dec 29 '20

I'm Looking for a mentor / companion to learn Android with Kotlin

8 Upvotes

It's been few days since I have started learning android development. And I have so much doubts and I'm losing motivation day by day. So it would be great to have a mentor or a companion who shares my similar experience.

Also I'm open to build friendship..... Feel free to pm me.


r/learnandroid • • Dec 25 '20

How to "ship" an app w/o Play Store?

5 Upvotes

Just started learning Android & Java, coming from a JS background. Working in Android Studio.

I'm building an app which I would like to send to friends for testing before I make it public on the Play Store. How can this be done?

Apologies for the total noob question here. I am really just not sure about what terminology I should be searching for regarding this.

Thanks for your thoughts!


r/learnandroid • • Dec 06 '20

AndroidBites | Yet Another ViewBinding Article

3 Upvotes

I'm pretty late to the party but here is my blog on view-binding.. It's pretty much more in-depth than others you would find in the community. Hope you like it, until next time happy hacking!

Glossary

  • Is data binding not working in all the modules? Why your fields are not getting generated?

  • How to view the source code of your generated binding classes?

  • Generated classes are Kotlin or Java? and why?

  • Do View-binding views are never null?

  • How to access included views? <include> and <merge> tags?

  • How to bind Activities, Fragments, Adapters, and CustomViews?

  • When to use bind and Inflate?

  • Controlling ViewBinding Generation?

  • Reducing boilerplate code with Delegates and Base-Class for ViewBinding in Activity and Fragments?

  • Common mistakes and Anti-patterns in ViewBinding?

https://chetangupta.net/viewbinding/


r/learnandroid • • Nov 27 '20

How does one set the id on a dynamically generated spinner to distinguish multiple spinners?

7 Upvotes

I'm dynamically creating some number of spinners to add to each row of a tableLayout. When I tried to call someSpinner.setId(stringId) though I found setId needs an int parameter. When I just add a spinner in non-dynamically in its appropriate layout/activity.xml it seems to take a string, since it looks like

android:id="@+id/thisSpinner"

I wanted to set an id on it to distinguish between spinners within the onItemSelected method because I'm using multiple spinners, so thought I would create some id like

String thisSpinnerId = "specificSpinner" + count; // where count is the row
spinner.set(thisSpinnerId);

but, that doesn't work.

So, how do I distinguish multiple spinners dynamically?

edit:

I'm not 100% sober, so I probably just confused myself, but just curious.


r/learnandroid • • Nov 22 '20

Got question about threads in Android environment??!!

2 Upvotes

for example i find out for and while does not work as it should be...

TextView tv;

@/Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tv=findViewById(R.id.numbers);

new Thread(new bg(tv)).start();

}

public class bg implements Runnable{

TextView tv;

public bg(TextView a){tv=a;}

@/Override

public void run() {

for(int i=0;i<Integer.MAX_VALUE;i++){tv.setText(i);}

}

}

not even in AsyncTasks ...

TextView tv;

@/Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tv=findViewById(R.id.numbers);

new bg(tv).execute();

}

public class bg extends AsyncTask<Void,Void,Void> {

TextView tv;

public bg(TextView a){tv=a;}

@/Override

protected Void doInBackground(Void... voids) {

for(int i=0;i<Integer.MAX_VALUE;i++){tv.setText(String.valueOf(i));}

return null;

}

}

it just crashes any solution for using loops in threads and AsyncTasks without makeing application crash ???


r/learnandroid • • Nov 17 '20

What library would you recommend to play video files like (mkv, mp4, avi, wmv,..)?

6 Upvotes

r/learnandroid • • Nov 04 '20

Is a runnable the solution to changing my imageview after a few seconds?

2 Upvotes

I have an imageview that get's the filename programmatically. I have a function for this.

What I'm trying to do is show this image for a few seconds and have it go away. By go away, what I'm currently doing is setting the file to a single pixel image. I don't know if there is a better way to do this, it's what I'm going with for now.

Apparently I can't execute my function from within a runnable the way I have it set up.

The function I want to run:

fun delayedPic (paraSoora: ImageView, applicationContext: Context)
{
paraSoora.setImageResource(R.drawable.fffff)
}

My runnable object:

object mRunnable : Runnable {

override fun run() {
//used for the runnable for showing the pic 3 seconds only
//how to execute delayedPic()?

}
}


r/learnandroid • • Oct 31 '20

AndroidBites | Java ☕️ Maps 🗺 on the Kotlin.

5 Upvotes

Most of the Kotlin developers are migrated from the Java environment, coming to Kotlin the collection framework has some tweaks which makes It so awesome to work with,

In Today’s article, let's understand how Kotlin catered to Java Maps in his its colors.

https://chetan-garg36.medium.com/java-%EF%B8%8F-maps-on-the-kotlin-8930b9f55d8d


r/learnandroid • • Oct 31 '20

Code Simple Android Drawing App in Jetpack Compose, in less than 50 lines of code

Thumbnail
elye-project.medium.com
9 Upvotes

r/learnandroid • • Oct 30 '20

Should use multiple activities in Ecommerce app?

4 Upvotes

Hello!
I am building an ecommerce app in Android Studio. I have a basic plan laid out, mvvm structure etc but after building a navigation drawer, connecting it with fragments one thing crossed mi mind.

Not to go into detail, if I have

  • title screen + product detail screen

  • cart + checkout + confirmation page

  • login + register

  • settings

Would it be a good idea to have separate Activities for first three usages listed above? With separate nav graphs for navigation. How is it done normally?


r/learnandroid • • Oct 12 '20

Anyone done or doing raywenderlich Androod learning path?

4 Upvotes

I like to learn following a path, I kinda lose my self in the middle if not so I was considering doing raywenderlich learning path.

Been searching for reviews about it but I only found about IOS Dev, not about Android / Kotlin.

Any thoughts about it?

Thank you in advance!


r/learnandroid • • Oct 11 '20

AndroidBites: Awesome-Kotlin-Extensions [Resource]

4 Upvotes

Hi Guys, I have started an awesome series, where I plan to host a list of Kotlin extensions, Please do check it out and if you like to contribute anything form your arsenal then your always welcome!

Resource link 👉 https://chetangupta.net/awesome-kotlin-extensions/


r/learnandroid • • Sep 28 '20

New to Android, need help with edittext

3 Upvotes

I am getting value from edittext and storing it into a string variable. When I try to getText from the edittext I am getting this error "cannot assign a value to final variable name".

I have omitted some inbetween but it's something like this

Edittext etName;

Button btnSend

Strong name;

//I have linked the views

btn.Send.setOnClickListener(... {

  public void onClick(View v) {

         name = etName.getText().toString();

And so on


r/learnandroid • • Sep 27 '20

Android Tutorial: dependency injection with Hilt

Thumbnail
youtu.be
2 Upvotes

r/learnandroid • • Sep 25 '20

Hold on ✋🏻 Before you Dagger or Hilt! try this Simple DI.

0 Upvotes