NullPointerException when totalPriceEditText is referred - java

I am new to Java and Android and I want to make an Android program that lets the users to type in the tag price and the program is able to show the final price. (after the tax which is 8%) I am required to use Netbean. There are no red lines nor error messages. But every time I ran it, it ended up with "Unfortunately, Tax Price Calculator has to stop" showed in the emulator. Please help me. I do appreciate everyone's answer. Thanks!!!!!!
TaxCalculator.java:
package com.finalproject.taxcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
public class TaxCalculator extends Activity{
private static final String TAG_PRICE = "TAG_PRICE";
private static final String TOTAL_PRICE = "TOTAL_PRICE";
private static final double TAX_RATE = 0.08;//Tax rate in Philadelphia
private double tagPrice;//Tag price entered by the user
private double totalPrice;//Total prices calculated by the program
private EditText tagPriceEditText;//accepts input for tag prices
private EditText totalPriceEditText;//displays total prices after tax
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
// constants used when saving/restoring state
super.onCreate(savedInstanceState);// call superclass's version
setContentView(R.layout.main);// inflate the GUI
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
tagPrice = 0.0; // initialize the tag price to zero
} // end if
else // app is being restored from memory, not executed from scratch
{
// initialize the tag price to saved amount
tagPrice = savedInstanceState.getDouble(TAG_PRICE);
} // end else
// get references to tag and total price edit text
tagPriceEditText = (EditText)findViewById(R.id.tagPriceEditText);
tagPriceEditText = (EditText)findViewById(R.id.totalPriceEditText);
// tagPriceEditTextWatcher handles tagPriceEditText's onTextChanged event
tagPriceEditText.addTextChangedListener(tagPriceEditTextWatcher);
}// end method onCreate
private void updateStandard()
{
// calculate the total price after the tax
totalPrice = tagPrice * (1 + TAX_RATE);
// set totalPriceEditText's text to total price
totalPriceEditText.setText(String.format("%.02f", totalPrice));
} // end method updateStandard
// save values of tagPriceEditText
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putDouble(TAG_PRICE, tagPrice);
} // end method onSaveInstanceState
// event-handling object that responds to tagPriceEditText's events
private TextWatcher tagPriceEditTextWatcher = new TextWatcher()
{
// called when the user enters a number
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
// convert billEditText's text to a double
try
{
tagPrice = Double.parseDouble(s.toString());
} // end try
catch (NumberFormatException e)
{
tagPrice = 0.0; // default if an exception occurs
} // end catch
// update the tagPriceEditText
updateStandard();
} // end method onTextChanged
#Override
public void afterTextChanged(Editable s)
{
} // end method afterTextChanged
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
} // end method beforeTextChanged
}; // end tagPriceEditTextWatcher
} // end class TaxCaculator
from main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#FFF" android:id="#+id/tableLayout"
android:stretchColumns="1,2,3" android:padding="5dp">
<!-- tagPriceInputRow -->
<TableRow android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="#+id/tagPriceInputRow">
<EditText android:layout_width="wrap_content"
android:id="#+id/tagPriceEditText"
android:inputType="number"
android:text="#string/tagPrice"
android:layout_height="wrap_content" android:layout_span="3"
android:layout_weight="1">
</EditText>
</TableRow>
<!-- totalPriceOutputRow -->
<TableRow android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="#+id/totalPriceOutputRow">
<EditText android:layout_width="wrap_content"
android:id="#+id/totalPriceEditText"
android:text="#string/totalPrice"
android:layout_height="wrap_content" android:layout_span="3"
android:inputType="numberDecimal" android:layout_weight="1">
</EditText>
</TableRow>
</TableLayout>
from strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tax Price Calculator</string>
<string name="tagPrice">Tag Price</string>
<string name="totalPrice">Total Price</string>
</resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.finalproject.taxcalculator"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Seems there is a mistake in variable assignment inside onCreate(), which resulting in NullPointerException when totalPriceEditText is referred.
tagPriceEditText = (EditText)findViewById(R.id.tagPriceEditText);
tagPriceEditText = (EditText)findViewById(R.id.totalPriceEditText); // <- wrong?
Should be changed to
tagPriceEditText = (EditText)findViewById(R.id.tagPriceEditText);
totalPriceEditText= (EditText)findViewById(R.id.totalPriceEditText);
Your TaxCalculator activity is not registered yet in your AndroidManifest.xml
Either 1) change the name of app's entry point (if you don't have MainActivity), OR 2) add a new <activity> entry.
Example to change app's entry point to TaxCalculator (replace the current <activity>)
<activity android:name="TaxCalculator"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Bonus: If your layout is already final, the code can be be cleaned up to this. This is just a suggestion for your current layout. I still don't know if you need TableLayout for future use or not though.
<?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"
android:background="#FFF"
android:orientation="vertical"
android:padding="5dp" >
<!-- tagPriceInputRow -->
<EditText
android:id="#+id/tagPriceEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:text="#string/tagPrice" >
</EditText>
<!-- totalPriceOutputRow -->
<EditText
android:id="#+id/totalPriceEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:text="#string/totalPrice" >
</EditText>
</LinearLayout>

Related

ScrollView hides the title bar

My small app was working well. When I used ScrollView it overrides the title bar of my App which is JustJava.
content.xml code
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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_height="match_parent"
android:layout_width="match_parent"
tools:context=".MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
android:text="Toppings"
android:textAllCaps="true" />
<CheckBox
android:id="#+id/whipped_cream_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Whipped Cream"
android:textSize="16sp"
android:layout_marginBottom="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
android:text="Quantity"
android:textAllCaps="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/decrease"
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="decrement"
android:text="-" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="0"
android:textColor="#android:color/black" />
<Button
android:id="#+id/increase"
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="increment"
android:text="+" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16sp"
android:text="Order summary"
android:textAllCaps="true"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16sp"
android:text="$0"
android:textColor="#android:color/black"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16sp"
android:onClick="submitOrder"
android:text="Order" />
</LinearLayout>
</ScrollView>
MainActivity.java
package com.example.bablu.justjava;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.w3c.dom.Text;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 0;
int pricePerCoffee = 5;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
quantity = quantity + 1;
displayQuantity(quantity);
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity > 0) {
quantity = quantity - 1;
}
displayQuantity(quantity);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
CheckBox whippedCreamCheckbox = (CheckBox)findViewById(R.id.whipped_cream_checkbox);
boolean hasChecked = whippedCreamCheckbox.isChecked();
String priceMessage = createOrderSummary(hasChecked);
displayMessage(priceMessage);
}
private int CalculatePrice(int numberOfCoffees) {
int price = numberOfCoffees * pricePerCoffee;
return price;
}
private String createOrderSummary(boolean hasChecked) {
int getPrice = CalculatePrice(quantity);
String priceMessage = "Name: Bablu Kumar" +
"\nAdd whipped cream? " + hasChecked +
"\nQuantity: " + quantity + "\n" + "Total: $" + getPrice;
priceMessage = priceMessage + "\nThank you!";
return priceMessage;
}
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given quantity value on the screen
*/
private void displayMessage(String message) {
TextView OrderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
OrderSummaryTextView.setText(message);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.bablu.justjava/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.bablu.justjava/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bablu.justjava">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.bablu.justjava.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
And here is the picture.
here is the picture
Please help provide a solution to resolve the problem.
Did you tried like this :
<ScrollView
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_height="match_parent"
android:layout_width="match_parent"
tools:context=".MainActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
Or add android:layout_below="+#id/toolbar" or like android:layout_below="+#id/appbarlayout"

attempting multiple activites via button click

I am writing an app that will display a menu of juices at a vape shop.
I have the main screen which displays the name and a button that once clicked will send the user to a new screen displaying the menu.
I am having trouble setting up the button click and when i run the app it crashes after the button is clicked
any input would be appreciated!
MainActivity
package com.example.vitoriano_vaz.easybayvapes;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
public void sendMessage(View view){
Intent intent = new Intent(FromActivity.this, ToActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startJuiceMenu(View view) {
Log.d("MyApp", "button clicked");
}
}
Second activity once the button is clicked
package com.example.vitoriano_vaz.easybayvapes;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class juiceMenu extends AppCompatActivity {
ArrayList<String> juiceMenu = new ArrayList<String>(50);
private static String VALUE = "myValue";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
juiceMenu.add("#1 Blueberry Bombshell");
juiceMenu.add("#2 Richie Rich");
juiceMenu.add("#3 Chiquita");
juiceMenu.add("#4 Afternoon Delight");
juiceMenu.add("#5 Poppin Otters");
juiceMenu.add("#6 Viva La Sangria");
juiceMenu.add("#7 Okole Maluna");
juiceMenu.add("#8 Carmen Miranda");
juiceMenu.add("#9 Pomalade");
juiceMenu.add("#10 Izual");
juiceMenu.add("#11 Butter Stotch ");
juiceMenu.add("#12 Blue Bulls");
juiceMenu.add("#13 Grape Ape");
juiceMenu.add("#14 Bruce Juice");
juiceMenu.add("#15 Doc Holiday");
juiceMenu.add("#16 Peachy Keen");
juiceMenu.add("#17 Hula");
juiceMenu.add("#18 New York");
juiceMenu.add("#19 Al Gore");
juiceMenu.add("#20 Lux Charms");
juiceMenu.add("#21 Sailor jack");
juiceMenu.add("#22 Get Him to the Greek");
juiceMenu.add("#23 Key We Lie Chi");
juiceMenu.add("#24 Spring Fling");
juiceMenu.add("#25 Gumby");
juiceMenu.add("#26 Chai-Milk");
juiceMenu.add("#27 Mr. Bean");
juiceMenu.add("#28 50 Shades of Orange");
juiceMenu.add("#29 Blue Waffles");
juiceMenu.add("#30 Enigma");
juiceMenu.add("#31 Mr. Freeze");
//juiceMenu.add("#32 New Flavor"); need to update to get newest flavor
}
}
Activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vitoriano_vaz.easybayvapes.MainActivity"
android:id="#+id/main_view">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:text="Welcome to East Bay Vapes"
android:textAllCaps="true"
android:textColor="#000000"
android:textSize="20sp"
android:id="#+id/textView" />
<Button
android:id="#+id/juicemenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="#string/JuiceMenu"
android:layout_marginTop="42dp"
android:layout_alignParentTop="true" />
</RelativeLayout>
Activity_juice_menu
here i have a LinearLayout for the ArrayList I declared in juicemenu.java class
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.vitoriano_vaz.easybayvapes.juiceMenu">
<ListView
android:id="#+id/JuiceMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vitoriano_vaz.easybayvapes">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".juiceMenu"></activity>
</application>
</
The Intent that you are building needs to reference your own Activity classes.
The first parameter is a Context and the second is the Class of the Activity you want to start so it should be the following.
Intent intent = new Intent(this, juiceMenu.class);
Since your question has already been answered, I thought I'd suggest a more efficient means of populating your array to remove that blemish from your code. For example you can use a string-array resource. With that you simply add the values using a single code line. As an example:
String[] juiceArray = getResources().getStringArray(R.array.JuiceTextArray);
The array values themselves are populated in your arrays.xml file (found in values folder) as such:
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation">
<string-array name="JuiceTextArray" tools:ignore="MissingTranslation">
<item name="Juice1">#1 Blueberry Bombshell.</item>
<item name="Juice2">#2 Richie Rich.</item>
[etc., etc.]
</string-array>
</resources>

Slow and unresponsive activity in Android

I have a simple activity that needs to be active for 10-15 minutes. The activity is using TelephonyManager to get three LTE parameters: RSRP, RSRQ, PCI. It collects these three parameters and a timestamp once per second, and therefore, the UI gets updated once per second.
The method used to get the LTE parameters is run on a background thread. Other than the UI getting updated every second, nothing is very computationally intensive. However, if I run the activity for more than five minutes then I get the lovely Android Monitor message: "I/Choreographer: Skipped 91 frames! The application may be doing too much work on its main thread."
So I must be doing something wrong because I believed I was doing all the hard work on the background thread. If I run the activity for 10-15 minutes it will skip ~1,000 frames. Then if I go through the app and press the button to run another test it will start off skipping as many frames as it did at the end of the previous 15 minute test and by the end of the second test it can skip as many as 2500 frames. Then it takes longer and longer each time you press a button to start the next activity (even on activities where literally nothing is being done). And there are only five activities!
Here is a screenshot of the activity that I need to have active collecting data for 15 minutes:
And the corresponding Android Monitor log:
Here is my code for the activity called Third.java:
package com.parksjg.its.pscrindoortesttool;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.CellInfo;
import android.telephony.CellInfoLte;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import au.com.bytecode.opencsv.CSVWriter;
/**
* Created by josephparks on 1/27/16.
*/
public class Third extends Activity implements Runnable {
SignalStrengthListener signalStrengthListener;
TextView lteRsrp;
TextView lteRsrq;
TextView cellPciTextView, fileName;
ImageView img;
Button stopButton;
TelephonyManager tm;
List<CellInfo> cellInfoList;
String lte1, lte2;
int cellPci = 0;
ArrayList data;
CSVWriter writer;
String mydate;
String startDate;
boolean done = false;
#Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
// This runs the code to grab the LTE parameters
startTele();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_activity);
// Sets up the TextViews and UI
setupUI();
// Runs telephony method on background thread
run();
// takes the collected data and adds it to the CSV format once per second
setupCSV();
// Sets up the stop button, writes data to CSV, and starts next activity
setupButton();
}
// This method is called by startTele() and is responsible for grabbing the LTE params
private class SignalStrengthListener extends PhoneStateListener {
#Override
public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) {
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String ltestr = signalStrength.toString();
String[] parts = ltestr.split(" ");
lte1 = parts[9];
lte2 = parts[10];
try {
cellInfoList = tm.getAllCellInfo();
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
// cast to CellInfoLte and call all the CellInfoLte methods you need
// Gets the LTE PCI: (returns Physical Cell Id 0..503, Integer.MAX_VALUE if unknown)
cellPci = ((CellInfoLte) cellInfo).getCellIdentity().getPci();
}
}
} catch (Exception e) {
// Log.d("SignalStrength", "+++++++++++++++++++++++++++++++ null array spot 3: " + e);
}
// Gets the timestamp of when these LTE params where collected
mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
// Updates the UI TextViews for RSRP, RSRQ, and PCI
lteRsrp.setText(String.valueOf(lte1));
lteRsrq.setText(String.valueOf(lte2));
cellPciTextView.setText(String.valueOf(cellPci));
super.onSignalStrengthsChanged(signalStrength);
}
}
// This takes the collected LTE data and timestamps and concatenates them into one object
// which is then easy to create a CSV file from
private void setupCSV() {
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
data.add(new String[]{mydate, lte1, lte2, String.valueOf(cellPci)});
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
}
private void setupUI () {
data = new ArrayList();
// startDate is used to name the CSV file
startDate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
lteRsrp = (TextView) findViewById(R.id.lteRsrp);
lteRsrq = (TextView) findViewById(R.id.lteRsrq);
cellPciTextView = (TextView) findViewById(R.id.cellPciTextView);
fileName = (TextView) findViewById(R.id.fileName);
fileName.setText(startDate);
stopButton = (Button) findViewById(R.id.stopButton);
img = (ImageView) findViewById(R.id.imageView);
img.setImageResource(R.drawable.recording);
// Log.d("Time and Date", "+++++++++++++ DATE : " + mydate);
}
private void startTele() {
// start the signal strength listener
signalStrengthListener = new SignalStrengthListener();
((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try {
cellInfoList = tm.getAllCellInfo();
} catch (Exception e) {
// Log.d("SignalStrength", "+++++++++++++++++++++++++++++++++++++++++ null array spot 1: " + e);
}
}
private void setupButton() {
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Third.this, "Writing output to CSV!", Toast.LENGTH_LONG).show();
// Writes the data to a CSV file named by startDate
writeCSV();
try{
if(signalStrengthListener != null) {
tm.listen(signalStrengthListener, SignalStrengthListener.LISTEN_NONE);
// Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Stop button Success!!!!!!");
}
}catch(Exception e){
e.printStackTrace();
// Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Stop button Fail!!!!!! with error = " + e);
}
// Intent passes startDate and the boolean done to indicate when the CSV has been written
Intent intent = new Intent(getBaseContext(), Fourth.class);
intent.putExtra("START_DATE", startDate);
intent.putExtra("DONE", done);
startActivity(intent);
finish();
}
});
}
private void writeCSV() {
try {
File file = new File(getExternalFilesDir(null), startDate+".csv");
writer = new CSVWriter(new FileWriter(file, true), ',');
// Headers
String[] headers = "Time, RSRP, RSRQ, PCI".split(",");
writer.writeNext(headers);
writer.writeAll(data);
writer.flush();
writer.close();
Toast.makeText(Third.this, "CSV Successful!", Toast.LENGTH_SHORT).show();
done = true;
// Log.d("CSV Writer", "CSV Writer Successful!");
} catch (IOException e) {
// Log.d("CSV Writer", "Error writing CSV file : " + e);
Toast.makeText(Third.this, "Error writing CSV file", Toast.LENGTH_SHORT).show();
}
}
}
Here is the corresponding XML called third_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffdc1d">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Recording"
android:textSize="26sp"
android:textColor="#000000"
android:id="#+id/lteRecording"
android:layout_alignParentTop="true"
android:textAlignment="center"
android:background="#f91616"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textSize="22sp"
android:textColor="#000000"
android:id="#+id/lteRsrp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="29dp"
android:layout_marginTop="120dp"
android:textAlignment="textEnd"
android:background="#ffdc1d"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE RSRP"
android:textSize="22sp"
android:textColor="#000000"
android:id="#+id/textView2"
android:background="#ffdc1d"
android:textStyle="bold"
android:layout_alignTop="#+id/lteRsrp"
android:layout_toEndOf="#+id/stopButton" />
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#a71b1b"
android:textSize="22sp"
android:id="#+id/lteRsrq"
android:layout_below="#+id/lteRsrp"
android:layout_alignStart="#+id/lteRsrp"
android:textAlignment="textEnd"
android:textStyle="bold"
android:background="#ffdc1d"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE RSRQ"
android:textSize="22sp"
android:textColor="#a71b1b"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_alignStart="#+id/textView2"
android:textStyle="bold"
android:background="#ffdc1d"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="210dp"
android:layout_height="wrap_content"
android:text="0"
android:textSize="22sp"
android:textColor="#075f09"
android:id="#+id/cellPciTextView"
android:layout_below="#+id/lteRsrq"
android:layout_alignStart="#+id/lteRsrq"
android:textAlignment="textEnd"
android:background="#ffdc1d"
android:textStyle="bold"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="= LTE PCI"
android:textSize="22sp"
android:textColor="#075f09"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_alignStart="#+id/textView3"
android:background="#ffdc1d"
android:textStyle="bold"
android:layout_marginTop="20dp" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Stop"
android:textSize="22sp"
android:textColor="#ffdc1d"
android:id="#+id/stopButton"
android:background="#f91616"
android:textStyle="bold"
android:padding="4dp"
android:textAlignment="center"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="41dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#drawable/recording"
android:layout_above="#+id/textView2"
android:layout_alignStart="#+id/lteRsrp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Filename:"
android:textColor="#000000"
android:textSize="26sp"
android:id="#+id/textView6"
android:layout_marginTop="50dp"
android:layout_below="#+id/cellPciTextView"
android:layout_alignStart="#+id/cellPciTextView"
android:textStyle="bold|italic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000000"
android:textSize="26sp"
android:id="#+id/fileName"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:textStyle="bold" />
</RelativeLayout>
And here is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parksjg.its.pscrindoortesttool" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".First"
android:screenOrientation="portrait"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Second"
android:screenOrientation="portrait"
android:noHistory="true">
</activity>
<activity android:name=".Third"
android:screenOrientation="portrait"
android:noHistory="true">
</activity>
<activity android:name=".Fourth"
android:screenOrientation="portrait"
android:noHistory="true">
</activity>
<activity android:name=".Final"
android:screenOrientation="portrait"
android:noHistory="true">
</activity>
</application>
</manifest>
Am I putting the wrong code to execute in the background thread? How can I make this run smoother and more responsive? Again, it is fast when run under 5 minutes, but we use this to test research indoor LTE networks and our walk tests/drive tests need to be 10-15 minutes, but when I hit the stop button, or the new test button I need it to respond within a second or two. Sometimes it takes 20-30 seconds for the action to take effect after having pressed the button, particularly after consecutive testing.
Below is the complete flow of the app:
The button from the last activity restarts the second activity. Let me know if you need any other code, I can also post the whole AndroidStudio project on GitHub if anyone is interested in running the code themselves.
Thanks!
Since it's something that builds over time it propably means that Views or objects are not being garbage collected properly by the OS because their references are not being released...which leads to memory problems. I suggest as a first step to use a memory profiler and check how much of your memory is being used over the duration of your test. Other than that you could check the time that your methods need to be executed by doing something like this
void methodName(){
long startTime = System.currentTimeMillis();
.
.
.
.
Log.w("time needed for this method",Long.toString(System.currentTimeMillis()-startTime);
}

Android SeekBar Application - Unfortunately, project has stopped

I am new to Android dev and for my project, I am creating two seekbars. The first seekbar has a minimum of 50 and a maximum of 180 while the second seekbar has a minimum of 180 and a maximum of 400. I also added textview labels below each seekbar to show the current value of each. My code compiled fine without any errors and displayed fine on the Android emulator, but when I clicked on the slider to change the value of the seekbar, my app ended up crashing and saying, "Unfortunately, your project has stopped." Below is my code:
MainActivity.java
package com.example.myname.projectname;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.R.*;
public class MainActivity extends ActionBarActivity implements OnSeekBarChangeListener {
private SeekBar lowBar;
private SeekBar highBar;
private TextView lowtext;
private TextView hightext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializevariables();
lowBar = (SeekBar)findViewById(R.id.lowbar);
highBar = (SeekBar)findViewById(R.id.highbar);
lowtext = (TextView)findViewById(R.id.lowval);
hightext = (TextView)findViewById(R.id.highval);
lowBar.setOnSeekBarChangeListener(this);
highBar.setOnSeekBarChangeListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void initializevariables(){
lowBar = (SeekBar) findViewById(R.id.lowbar);
highBar = (SeekBar) findViewById(R.id.highbar);
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
progress = 0;
int lowbarmin = progress + 50;
int highbarmin = progress + 180;
lowtext.setText(lowbarmin);
hightext.setText(highbarmin);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<EditText android:text="CGM Alarm System" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lowbar"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:indeterminate="false"
android:progress="0"
android:max="180"/>
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/highbar"
android:layout_below="#+id/lowbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="66dp"
android:layout_alignRight="#+id/lowbar"
android:layout_alignEnd="#+id/lowbar"
android:progress="0"
android:max="400"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="50"
android:id="#+id/lowval"
android:layout_below="#+id/lowbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="180"
android:id="#+id/highval"
android:layout_below="#+id/highbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myname.projectname"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myname.projectname.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you in advance!
Your seekbar's minimum value is 50, you can not increase +50;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
int lowbarmin = progress + 1;
int highbarmin = progress + 1;
lowtext.setText(lowbarmin);
hightext.setText(highbarmin);
}
Crash is probably because of these lines :
lowtext.setText(lowbarmin);
hightext.setText(highbarmin);
When you do this and the value of lowbarmin and highbarmin are integers, android looks for string resources with those values as their resourceId and it cannot find one.
So what you instead want to do is, pass string values to setText() :
lowtext.setText(Integer.toString(lowbarmin));
hightext.setText(Integer.toString(highbarmin));

How can I use the square root of a number that the user enters in an input box, instead of the number itself?

I'm trying to make an Android app, and the feature that I'm working on right now is calculating the square root of a number entered by the user.
How can I take a number that the user enters in a text box, and use the square root of that number in the doCalc part of my program? I'm limiting the number to be an integer between 1 and 20. For example, if the user enters 2 in the input box, I want to use 1.41 in the doCalc method.
Here is my .java code:
package learn.text;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LearntextActivity extends Activity {
TextView text;
EditText input;
TextView text2;
EditText input2;
TextView text3;
EditText input3;
Button calc;
TextView output;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text);
text.setText("Enter the design GPM for Chiller");
input = (EditText) findViewById(R.id.input);
text2 = (TextView) findViewById(R.id.text2);
text2.setText("Enter the Square root of the actual pressure drop across the coil");
input2 = (EditText) findViewById(R.id.input2);
text3 = (TextView) findViewById(R.id.text3);
text3.setText("Enter the design pressure drop of coil");
input3 = (EditText) findViewById(R.id.input3);
calc = (Button) findViewById(R.id.calc);
output = (TextView) findViewById(R.id.output);
}
public void doCalc (View view) {
double mInput = Double.parseDouble(input.getText().toString());
double mInput2 = Double.parseDouble(input2.getText().toString());
double mInput3 = Double.parseDouble(input3.getText().toString());
double mOutput = (mInput*mInput2)/(mInput3);
output.setText("GPM is" + mOutput);
}
}
Here is the .xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<TextView android:layout_height="wrap_content" android:text="" android:layout_width="wrap_content" android:id="#+id/text"></TextView>
<EditText android:layout_height="wrap_content" android:text="" android:layout_width="match_parent" android:id="#+id/input"></EditText>
<TextView android:layout_height="wrap_content" android:text="" android:layout_width="wrap_content" android:id="#+id/text2"></TextView>
<EditText android:layout_height="wrap_content" android:text="" android:layout_width="match_parent" android:id="#+id/input2"></EditText>
<TextView android:layout_height="wrap_content" android:text="" android:layout_width="wrap_content" android:id="#+id/text3"></TextView>
<EditText android:layout_height="wrap_content" android:text="" android:layout_width="match_parent" android:id="#+id/input3"></EditText>
<Button android:layout_height="wrap_content" android:text="Get GPM" android:layout_width="wrap_content" android:id="#+id/calc" android:password="false" android:onClick="doCalc"></Button>
<TextView android:layout_height="wrap_content" android:text="" android:layout_width="wrap_content" android:id="#+id/output"></TextView>
</LinearLayout>
Here is the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="learn.text"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher" android:label="string/app_name">
android:label="#string/app_name" >
<activity
android:name=".LearntextActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Probably I'm misunderstanding something, but — can't you just change
Double.parseDouble(input2.getText().toString())
to
Math.sqrt(Double.parseDouble(input2.getText().toString()))
? (See http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#sqrt(double) for documentation of Math.sqrt.)

Categories