Slow and unresponsive activity in Android - java

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);
}

Related

Cannot get android studio app to start login screen after initial splash screen

I am new to java coding and Android Studio, so please bear with me. However, I am trying to get a login screen to start after the splash screen and the app crashes after the splash screen. The splash screen works no problem. Anyways, here is the first set of code and this is the splash screen code in Main activity.
package com.example.xxxx.safetyxxxxxxx;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tv;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
tv = (TextView) findViewById(R.id.tv);
iv = (ImageView) findViewById(R.id.imageView);
Animation mine = AnimationUtils.loadAnimation(this, R.anim.transition);
final Intent go = new Intent(MainActivity.this, LoginPageActivity.class);
//set duration ... 1 second ... :p
mine.setDuration(1000);
tv.startAnimation(mine);
iv.startAnimation(mine);
//make a thread to go to second activity...
Thread t = new Thread() {
#Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
MainActivity.this.startActivity(go);
finish();
}
}
};
t.start();
}
}
this is the Login Page activity called "LoginPageActivity.java" that I would like to have the app go to after the splash screen.
package com.example.xxxx.safetyxxxxxxx;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import static com.example.xxxx.safetyxxxxxxx.R.layout.activity_login_page;
public class LoginPageActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_login_page);
findViewById(R.id.textViewSignUp).setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.textViewSignUp:
startActivity(new Intent(this, SignUpActivity.class));
break;
}
}
}
This is the androidmanifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xxxx.safetyxxxxxxx">
<application
android:name=".Database"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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=".LoginPageActivity"
android:label="#string/app_name">
</activity>
<activity android:name=".Main2Activity" />
<activity android:name=".SignUpActivity" />
</application>
</manifest>
Here is the logcat error
1-28 12:55:33.490 7647-7670/com.example.xxxx.safetyxxxxxxx E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.xxxx.safetyxxxxxxx, PID: 7647
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.xxxx.safetyxxxxxxx/com.example.xxxx.safetyxxxxxxx.LoginPageActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4791)
at android.app.Activity.startActivity(Activity.java:4759)
at com.example.mike.safetychecker.MainActivity$1.run(MainActivity.java:39)
Also if needed the file activity_login_page.xml code is below
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".LoginPageActivity">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="Hi, Welcome to Safety xxxxxx Please Login or Signup"
android:textAlignment="center"
android:textColor="#android:color/holo_green_dark"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.995"
tools:layout_editor_absoluteX="0dp"
tools:ignore="MissingConstraints" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="398dp"
tools:ignore="MissingConstraints" />
<EditText
android:id="#+id/editTextEmail"
android:layout_width="346dp"
android:layout_height="50dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="email"
android:inputType="textEmailAddress"
android:text=" email"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="270dp"
tools:ignore="MissingConstraints" />
<EditText
android:id="#+id/Password"
android:layout_width="346dp"
android:layout_height="50dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:inputType="textVisiblePassword"
android:text=" Password"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="336dp"
tools:ignore="MissingConstraints" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="219dp"
android:layout_height="229dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/editTextEmail"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/safetyxxxx" />
<TextView
android:id="#+id/textViewSignUp"
android:layout_width="351dp"
android:layout_height="34dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Do Not Have An Account? Click Here"
android:textAlignment="center"
android:textColor="#android:color/holo_green_dark"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.529"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="459dp"
tools:ignore="MissingConstraints" />
</android.support.constraint.ConstraintLayout>
Also there is this transition.xml file contained in a anim folder that might help
<?xml version="1.0" encoding="utf-8"?>
<alpha
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0.0"
android:toAlpha="1.0"
/>
you have to try to open your LoginPageActivity like this way
Paste this code
openActivity();
instead of this
Thread t = new Thread() {
#Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
MainActivity.this.startActivity(go);
finish();
}
}
};
t.start();
and put this method
public void openActivity()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent go = new Intent(MainActivity.this,LoginPageActivity.class);
startActivity(go);
finish();
}
}, 5000);
}
import this packages
import android.os.Bundle;
import android.os.Handler;
and also mention in your manifest like this
<activity android:name=".LoginPageActivity"
android:label="#string/app_name"/>
You have to declare your Activity in your AndroidManifest.xml. Almost all of your system-related classes have to be declared in it, this includes Activities, Services, BroadCast Receivers. You can read up on how Manifest works over here
Back to your problem, you can fix it by add the following line inside the application tag in your Android Manifest. Remove any intent filters you have applied to it
<activity android:name=".LoginPageActivity" />
Remove :
<intent-filter>
<action android:name="com.example.xxxx.safetyxxxxxxx.LoginPageActivity" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Because there is always remains only one LAUNCHER activity in application. And also intent filter is wrong there.
change LAUNCHER TO DEFAULT in your mainfest, Two launcher is not possible at same time (Assuming MainActivity as LAUNCHER)
</activity android:name=".LoginPageActivity>
<intent-filter>
<action android:name="com.example.xxxx.safetyxxxxxxx.LoginPageActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
use this
<activity android:name=".LoginPageActivity"
android:label="#string/app_name"/>
instead of
<activity android:name=".LoginPageActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.example.xxxx.safetyxxxxxxx.LoginPageActivity" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this,com.example.xxxx.safetyxxxxxxx.LoginPageActivity.class);
startActivity(intent);
finish();
}
}, 5000);
//where 5000 is the delayed time

Why Save Button doesn't work in my Sample Android App

I am beginner in Android system and was trying to create a simple registration from. In this app I created all the needed code but Save button doesn't give any response when clicking.
Here is the code of registration form :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtViewName"
android:text="Student's Name :"
android:layout_marginTop="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtViewFather"
android:text="Father's Name :"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/txtViewName"
android:layout_marginTop="29dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtViewMother"
android:text="Mother's Name :"
android:layout_below="#+id/txtViewFather"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtViewAge"
android:text="Age :"
android:layout_below="#+id/txtViewMother"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/txtViewClass"
android:text="Class :"
android:layout_below="#id/txtViewAge"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="29dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/txtEditName"
android:ems="10"
android:layout_toRightOf="#+id/txtViewName"
android:layout_above="#+id/txtViewFather"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/txtEditFather"
android:ems="10"
android:layout_toRightOf="#+id/txtViewFather"
android:layout_above="#+id/txtViewMother"
android:layout_alignParentRight="true"
android:layout_alignLeft="#+id/txtEditName"
android:layout_alignStart="#+id/txtEditName"
android:layout_alignRight="#+id/txtEditName"
android:layout_alignEnd="#+id/txtEditName" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/txtEditMother"
android:ems="10"
android:layout_above="#+id/txtViewAge"
android:layout_toRightOf="#+id/txtViewMother"
android:layout_alignLeft="#+id/txtEditName"
android:layout_alignStart="#+id/txtEditName"
android:layout_alignRight="#+id/txtEditName"
android:layout_alignEnd="#+id/txtEditName" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/txtEditAge"
android:ems="10"
android:layout_above="#+id/txtViewClass"
android:layout_toRightOf="#+id/txtViewAge"
android:layout_alignLeft="#+id/txtEditName"
android:layout_alignStart="#+id/txtEditName"
android:layout_alignRight="#+id/txtEditName"
android:layout_alignEnd="#+id/txtEditName" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtEditClass"
android:layout_alignBottom="#id/txtViewClass"
android:layout_alignLeft="#+id/txtEditName"
android:layout_alignStart="#+id/txtEditName"
android:layout_alignRight="#+id/txtEditName"
android:layout_alignEnd="#+id/txtEditName" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnBack"
android:text="Back"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnSave"
android:text="Save"
android:layout_toLeftOf="#+id/btnBack"
android:layout_alignParentBottom="true" />
</RelativeLayout>
and here is the StudentDetail.java class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.util.ArrayList;
public class StudentDetail extends AppCompatActivity implements android.view.View.OnClickListener {
Button btnSave;
Button btnBack;
EditText txtEditName;
EditText txtEditFather;
EditText txtEditMother;
EditText txtEditAge;
EditText txtEditClass;
private int _student_id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry_form);
btnSave = (Button) findViewById(R.id.btnSave);
btnBack = (Button) findViewById(R.id.btnBack);
txtEditName = (EditText) findViewById(R.id.txtEditName);
txtEditFather = (EditText) findViewById(R.id.txtEditFather);
txtEditMother = (EditText) findViewById(R.id.txtEditMother);
txtEditAge = (EditText) findViewById(R.id.txtEditAge);
txtEditClass= (EditText) findViewById(R.id.txtEditClass);
btnSave.setOnClickListener(this);
btnBack.setOnClickListener(this);
_student_id = 0;
Intent intent = getIntent();
_student_id = intent.getIntExtra("student_Id", 0);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
if (view == findViewById(R.id.btnSave)){
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student.name = txtEditName.getText().toString();
student.father_name = txtEditFather.getText().toString();
student.mother_name = txtEditMother.getText().toString();
student.age = Integer.parseInt(txtEditAge.getText().toString());
student.student_class = txtEditClass.getText().toString();
student.student_id =_student_id;
if (_student_id==0){
_student_id = repo.insert(student);
Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
}
} else if(view== findViewById(R.id.btnBack)){
finish();
}
}
}
Here is the AndroidManifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studentregistration" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<activity
android:name="com.example.studentregistration.StudentDetail"
android:label="#string/title_activity_entry_form" >
</activity>
</application>
</manifest>
Now when I click on Save button nothing happens..
So can somebody help me out from this situation.
Thanks in advance.
Inside onClick function, use switch-case on the view Id as below:
#override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btnSave:
// Your custom save code goes here ...
break;
case R.id.btnBack:
// ...
break;
}
}
Try this code:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StudentRepo repo = new StudentRepo(StudentDetail .this);
Student student = new Student();
student.name = txtEditName.getText().toString();
student.father_name = txtEditFather.getText().toString();
student.mother_name = txtEditMother.getText().toString();
student.age = Integer.parseInt(txtEditAge.getText().toString());
student.student_class = txtEditClass.getText().toString();
student.student_id =_student_id;
if (_student_id==0){
_student_id = repo.insert(student);
Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
instead of
btnSave.setOnClickListener(this);
btnBack.setOnClickListener(this);
Oh thanks to all of you to give time to my question and suggesting me to do to fix the bug.
But after reviewing all the code line to line I found that bug myself.
The bug was launching wrong activity in AndroidManifest.xml file.
To fix this I removed the tag from MainActivity tag and placed this to StudentDetail activity tag and everything started working fine.
The updated code was :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studentregistration" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.studentregistration.StudentDetail"
android:label="#string/title_activity_entry_form" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thanks once again to all.

How to get rid of Bar in Android

I am new to developing but I have a problem
Here is the code of the stuff I believe you need to know
Main Activity
package com.mayubrand.basiccalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Button circumferenceB, areaB, diameterB;
private TextView resultTxt, radiusTxt, headingTxt;
private EditText radiusTF ;
public void onCreate(){
this.requestWindowFeature(Window.FEATURE_NO_TITLE);}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
//Buttons
circumferenceB = (Button) findViewById(R.id.circumferenceB);
areaB = (Button) findViewById(R.id.areaB);
diameterB = (Button) findViewById(R.id.diameterB);
//Text Field (Edit Text)
radiusTF = (EditText) findViewById(R.id.radiusTF);
//Text (Text View)
resultTxt = (TextView) findViewById(R.id.resultTxt);
radiusTxt =(TextView) findViewById(R.id.radiusTxt);
headingTxt = (TextView) findViewById(R.id.radiusTxt);
//==============
//Listeners
circumferenceB.setOnClickListener(this);
areaB.setOnClickListener(this);
diameterB.setOnClickListener(this);
}
public void onClick(View view) {
String radiusEntered = radiusTF.getText().toString();
double pi = Math.PI;
int two = 2;
if(radiusEntered.equals("")) {
radiusTF.setText("");
}else{
switch (view.getId()){
case R.id.circumferenceB:
double circumference = Integer.parseInt(radiusEntered) * pi * two;
resultTxt.setText(String.valueOf(circumference));
break;
case R.id.areaB:
double area = pi * Integer.parseInt(radiusEntered) *Integer.parseInt(radiusEntered);
resultTxt.setText(String.valueOf(area));
break;
case R.id.diameterB:
double diameter = Integer.parseInt(radiusEntered) * 2;
resultTxt.setText(String.valueOf(diameter));
break;
}
}
}
}
Main Activity XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="MayU Circle Calulator"
android:id="#+id/headingTxt"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Radius"
android:id="#+id/radiusTxt"
android:layout_below="#+id/headingTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="36dp"
android:textSize="23dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/radiusTF"
android:layout_alignBottom="#+id/radiusTxt"
android:layout_alignRight="#+id/headingTxt"
android:layout_alignEnd="#+id/headingTxt" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/radiusTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Find Circumference"
android:id="#+id/circumferenceB"
android:layout_weight="0.08" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Find Area"
android:id="#+id/areaB"
android:layout_weight="0.08" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Find Diameter"
android:id="#+id/diameterB"
android:layout_gravity="center_horizontal"
android:layout_weight="0.08" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Result"
android:id="#+id/resultTxt"
android:layout_gravity="center_horizontal"
android:layout_weight="0.08"
android:textSize="40dp" />
</LinearLayout>
Android Manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Circle Calculator"
android:theme="#style/AppTheme"
>
<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>
When I'm in the layout area where you arrange all your buttons and text and any other component you have visually it looks fine, however as soon as I launch it in the emulator or on my phone there is a bar black/brown bar that just stays there. How do I remove that?
One other thing on the side, how do I change the default color of buttons
My guess is that you are referring to the action bar.
If that is the case in your styles.xml change the AppTheme theme to NoActionBar.
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
</style>
To change the default color of your buttons, you can use styles as well.

Sending Telnet commands on Android

I am trying to send some commands over telnet.
Everything works fine when executed locally on a PC on basis of a swing GUI, but when using the same code on Android, the app freezes for a few seconds and the commands are not carried out (same result on emulator and real device), although it runs to the end. No error message is being thrown, but after this procedure the device is not reachable via Telnet, not even via PC (restart of target device is then necessary). What I do not understand is that it seems that the 500 milliseconds restriction I set is being ignored on Android.
I am a novice on Android so please bear with me. Glad for any help.
package com.test.test.remote;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
}
public void calculate(View view) throws Exception {
System.out.println("Calc button executed");
command("MO");
}
public String command(String cmd) {
String output = "test";
Log.e("Msg", "command reached");
Log.e("Msg", cmd);
Socket pingSocket = null;
PrintWriter out = null;
BufferedReader in = null;
pingSocket = new Socket();
try {
pingSocket.connect(new InetSocketAddress("10.10.10.107", 23), 500);
out = new PrintWriter(pingSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
pingSocket.getInputStream()));
out.println(cmd);
output = in.readLine();
out.close();
in.close();
pingSocket.close();
System.out.println(output);
Log.e("Msg", "end of command reached");
} catch (Exception e) {
Log.e("com.example.test.MainActivity", e.getMessage());
e.printStackTrace();
}
return output;
}
}
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: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=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:layout_marginTop="31dp"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
<requestFocus />
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="28dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/kmh" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_centerVertical="true"
android:onClick="calculate"
android:text="#string/calc" />
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.test.remote"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>

NullPointerException when totalPriceEditText is referred

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>

Categories