Question

In: Computer Science

android studio Begin a new app and create a Java class for products with data: productName,...

android studio

Begin a new app and create a Java class for products with data: productName, productCode and price and use a file of objects to store product data and read back and display on screen. Do this by creating a simple form using EditTexts, buttons or ActionBar items and display output using an Alert.

Solutions

Expert Solution

<!— activity_main.xml -->

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <RelativeLayout

        android:id="@+id/inputView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp">

        <TextView
            android:id="@+id/nameView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Product Name : "
            android:textSize="20sp"
            android:layout_margin="10dp"
            android:textColor="#000000"
        />

        <EditText
            android:id="@+id/nameTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/nameView"
            android:textSize="20sp"
            android:textColor="#000000"
            />

        <TextView
            android:id="@+id/codeView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/nameTxt"
            android:text="Product Code : "
            android:textSize="20sp"
            android:layout_margin="10dp"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/codeTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/codeView"
            android:textSize="20sp"
            android:textColor="#000000"
            />

        <TextView
            android:id="@+id/priceView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Product Price : "
            android:layout_below="@id/codeTxt"
            android:textSize="20sp"
            android:layout_margin="10dp"
            android:textColor="#000000"
            />

        <EditText
            android:id="@+id/priceTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/priceView"
            android:textSize="20sp"
            android:textColor="#000000"
            android:inputType="numberDecimal"
            />

        <Button
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/priceTxt"
            android:text="Submit"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="50dp"
            android:textSize="20sp"/>


        <Button
            android:id="@+id/show"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/priceTxt"
            android:layout_toRightOf="@id/submit"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:text="Show Products"
            android:textSize="20sp"
            />
    </RelativeLayout>

</RelativeLayout>

<!—end of activity_main.xml -->

//MainActivity.java
package com.example.productdetails;



import android.content.DialogInterface;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;



import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;



import mysimpleapps.com.productdetails.models.Product;



public class MainActivity extends AppCompatActivity implements View.OnClickListener {



    EditText nameTxt, codeTxt, priceTxt;

    Button submit, show;

    FileWriter outFile = null;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        nameTxt = findViewById(R.id.nameTxt);

        codeTxt = findViewById(R.id.codeTxt);

        priceTxt = findViewById(R.id.priceTxt);

        submit = findViewById(R.id.submit);

        show = findViewById(R.id.show);



        submit.setOnClickListener(this);

        show.setOnClickListener(this);

    }



    @Override

    public void onClick(View v) {



        if(v == submit)

        {

            File file = new File(this.getFilesDir(),"products.txt");

            try {

                outFile = new FileWriter(file, true);

            } catch (IOException e) {

                Toast.makeText(getApplicationContext(),"File cannot be created or opened",Toast.LENGTH_SHORT).show();

            }



            if(nameTxt.getText().length() > 0 && codeTxt.getText().length() > 0 && priceTxt.getText().length() > 0)

            {

                Product product = new Product(nameTxt.getText().toString(),codeTxt.getText().toString(),Double.parseDouble(priceTxt.getText().toString()

                ));

                try {

                    outFile.write(product.getName()+","+product.getCode()+","+product.getPrice()+"\n");

                    Toast.makeText(getApplicationContext(),"Product data added to file",Toast.LENGTH_SHORT).show();

                } catch (IOException e) {

                    Toast.makeText(getApplicationContext(),"Product data cannot be stored",Toast.LENGTH_SHORT).show();

                }

            }else

                Toast.makeText(getApplicationContext(),"Please enter all the details for the product",Toast.LENGTH_SHORT).show();

        }else if(v == show)

        {

            try {

                if(outFile != null)

                    outFile.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

            ArrayList<Product> products = new ArrayList<>();

            File file = new File(this.getFilesDir(),"products.txt");

            try {

                Scanner reader = new Scanner(file);

                while(reader.hasNextLine())

                {

                    String line = reader.nextLine();

                    if(line.length() > 0)

                    {

                        Product product = new Product();

                        int index = line.indexOf(",");

                        product.setName(line.substring(0,index));

                        index = line.indexOf(",",index+1);

                        product.setCode(line.substring(line.indexOf(",")+1,index));

                        product.setPrice(Double.parseDouble(line.substring(index+1)));

                        products.add(product);

                    }

                }



                reader.close();



                AlertDialog.Builder alert = new AlertDialog.Builder(this);

                if(products.size() > 0)

                {

                    String alertMessage = "";

                    for(int i=0;i<products.size()-1;i++)

                    {

                        alertMessage += products.get(i).toString()+"\n";

                    }



                    alertMessage += products.get(products.size()-1).toString();



                    alert.setMessage(alertMessage)

                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                                @Override

                                public void onClick(DialogInterface dialog, int which) {

                                    dialog.cancel();

                                }

                            });



                    alert.show();



                }else

                    Toast.makeText(getApplicationContext(),"Add some products first",Toast.LENGTH_SHORT).show();



            } catch (FileNotFoundException e) {

                Toast.makeText(getApplicationContext(),"File products.txt doesn't exist",Toast.LENGTH_SHORT).show();

            }



        }

    }



    @Override

    protected void onDestroy() {

        super.onDestroy();

        try {

            if(outFile != null)

                outFile.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

//end of MainActivity.java

Output:


Related Solutions

Create a Scorekeeper app in android studio by using java language - Layouts | Widgets Create...
Create a Scorekeeper app in android studio by using java language - Layouts | Widgets Create the layout for your score keeping app. The app should have: Two team names (TextViews) Two scores (TextViews) Buttons to increase/ decrease the scores An amount to change the score by (RadioButtons) You must have at least two score options The scores can be changed by anything you want American football: 1, 2, 3, 6 Basketball: 1, 2, 3 Freestyle wrestling: 1, 2, 3,...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called DataBaseManager as in Lecture 5 and create a database table in SQLite, called StudentInfo. The fields for the StudentInfo table include StudentID, FirstName, LastName, YearOfBirth and Gender. Include functions for adding a row to the table and for retrieving all rows, similar to that shown in lecture 5. No user interface is required for this question, t -Continuing from , follow the example in...
Hi! I need it in android studio and in java Design a game app “BouncingBall ”...
Hi! I need it in android studio and in java Design a game app “BouncingBall ” in which the user’s goal is to prevent a bouncing ball from falling off the bottom of the screen. When the user presses the start button, a ball bounces off the top, left and right sides (the “walls”) of the screen. A horizontal bar on the bottom of the screen serves as a paddle to prevent the ball from hitting the bottom of the...
Hi! I need it in android studio and in java Design a game app “BouncingBall ”...
Hi! I need it in android studio and in java Design a game app “BouncingBall ” in which the user’s goal is to prevent a bouncing ball from falling off the bottom of the screen. When the user presses the start button, a ball bounces off the top, left and right sides (the “walls”) of the screen. A horizontal bar on the bottom of the screen serves as a paddle to prevent the ball from hitting the bottom of the...
use android studio or MIT inventor Create a Presidents Quiz App for your project with the...
use android studio or MIT inventor Create a Presidents Quiz App for your project with the following requirements: You must have images Buttons Label Conditional Statement Homepage with instructions Sound (music, buzzer, etc.) - Ensure you are using the correct layout: Gravity(Android Studio), Horizontal or Vertical Arrangement (MIT). - 40POINTS Points System (indicating how many answers they got wrong/correct). 20POINT 1-2 questions per President (45+ questions)
For this IP, you will create a very simple drawing app using Android Studio. The purpose...
For this IP, you will create a very simple drawing app using Android Studio. The purpose of this assignment is to give you more building blocks to use when programming apps. For full credit for this assignment, you should complete the following: Create a menu and display menu items on the app bar Detect when the user touches the screen and moves a finger Be able to change the color and width of a line Be able to save an...
I am doing a 4 function calculator app in java on android studio which calculates math...
I am doing a 4 function calculator app in java on android studio which calculates math expressions (add, subtract, multiply, and divide). I ONLY NEED THE CODE THE EQUAL BUTTON. When the user clicks the equal button, it should take the entire sequence of numbers and operators on the screen, such as 1+2*5 , and save them into a String [I am pretty sure this can be done using the toString() call]. Then, the String should be split using StringTokenizer,...
Android Studio. Java. Please create an application that -> An activity that allows user to enter...
Android Studio. Java. Please create an application that -> An activity that allows user to enter name, gender, date of birth, state of residence (selected from a pre-defined list: CA, AZ, NV, OR), email address and favorite website. This activity has a button "Show Data" that displays detail entered
Android Studio Code: Provide a working android studio code i.e java and xml code for the...
Android Studio Code: Provide a working android studio code i.e java and xml code for the activity below: Develop an application that is capable to turn pages back and forth. Detailed Instructions: For the main activity, create a layout that represents a fictitious title and author. The activity should include a clickable button on the bottom right that allows you to go forward to the next activity. The next activity will simply be an image above simple text that can...
Android Programming Create an app called GuessWho. The point of the app will to have the...
Android Programming Create an app called GuessWho. The point of the app will to have the user play a guessing game based on a displayed image. The user will be greeted with a screen that has an image of a person, four buttons and a next button. The four buttons should each have a different name on it. One of the names will be the actual name of the person in the image. Your guess who quiz should consist of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT