I am following this tutorial to use SOAP web services.
At first it presented some problems but after doing a few things (mentioned in the comments on the tutorial), it started working, but it is not working properly.
The problem is that after adding the input in the edit text, when i click on the corresponding number to convert the temperature, it does not do anything.
I am pasting the code below, This is an external link for LogCat (of pastebin.com, where I am pasting the logcat) since adding it here exceeds the permissible length of the question
.
Any hint/help will be greatly appreciated. Thank you in advance.
LAYOUT:-
<?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:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/txtFar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/editText1">
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/txtCel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/editText2"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnFar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/btnFar" />
<Button
android:id="#+id/btnCel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/btnCel" />
</LinearLayout>
<Button
android:id="#+id/btnClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btnClear" />
</LinearLayout>
CODE:-
package com.webservice;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service_demo);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnCel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
//Use this to add parameters
request.addProperty("Celsius",txtCel.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION2, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtFar.setText(result.getProperty(0).toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
}
STRINGS RESOURCE:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Using SOAP Test 2</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name= "textView1">Fahrenheit</string>
<string name="editText1">0</string>
<string name= "textView2">Celsius</string>
<string name="editText2">0</string>
<string name="btnFar">Convert to Celsius</string>
<string name="btnCel">Convert to Fahrenheit</string>
<string name="btnClear">Clear</string>
</resources>
MANIFEST FILE:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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="com.webservice.WebServiceDemoActivity"
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>
This is the exception you are getting:
java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
To resolve this problem, you need to copy the ksoap2-android-assembly-2.6.2-jar-with-dependencies.jar to the /libs folder of your project then rebuild the project. Then Eclipse ADT will automatically add this jar to the buildpath of your project.
I have followed the same tutorial.
This worked for me: i have changed
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE = "http://tempuri.org/";
with
private static String SOAP_ACTION1 = "http://www.w3schools.com/webservices/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private static String NAMESPACE = "http://www.w3schools.com/webservices/";
For finding the correct name space, you have to browse the web service URL. In this case: http://www.w3schools.com/webservices/tempconvert.asmx?WSDL. Then, you can find the correct name space at targetNamespace="........"
Related
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"
I'm trying here to make a project, that can scan a barcode (that is done), and after that it's supposed to show some values from a database based on that barcode (product name, address).
I manage to copy the value from the barcode to the clipboard, but then I cannot manage to copy it to the activity_second.xml's EditText.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="ScannerBucatarie"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="ScannerBucatarie"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.zxing.client.android.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:label="ZXing ScanBar"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/title_activity_second"></activity>
</application>
</manifest>
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}` AndroidManifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
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=".SecondActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/txResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}
In your main activity, set your data into Intent as below:
Intent intent = getIntent();
intent.putExtra("Param_name", txtNumOfCards.getText().toString());
intent.setClass(this, SecondActivity.class);
startActivity(intent);
In the second activity, you can retrieve it as below:
Intent intent = getIntent();
String value = intent.getStringExtra("Param_name");
Checkout the following exmaple:
http://www.startandroid.ru/en/lessons/complete-list/241-lesson-28-extras-passing-data-using-intent.html
As #Mohammed Kharma explained, you must send the id as an Intent extra (no need to copy it to the clipboard). I believe you already created this Intent, but I'm recreating it. Have in mind that I don't know the name you chose for your intent, so I'll just call it 'i'.
On your MainActivity.java:
Intent i= new Intent(MainActivity.class,SecondActivity.java);
i.putExtra("barcode",txtResult.getText().toString());
startActivity(i);
On your SecondActivity.java:
textViewResult = (TextView) findViewById(R.id.textViewResult);
String barcode=getIntent().getStringExtra("barcode");
textViewResult.setText(barcode);
I've looked at a bunch of posts on this subject, but nothing seems to be working and I've been stuck on this problem for 2 days now. these lines of code are getting red underline on the "R" saying it cannot be resolved as a variable
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
Also this line of code at the bottom of the java file has the same error
getMenuInflater().inflate(R.menu.activity_main, menu);
I created a menu folder under res and a menu.xml file as well.
Here's all the code and a screenshot of my environment. I'm not sure which file you need to see so I provided them all just in case.
Screenshot of Environment
http://postimg.org/image/6d1l0909r/
MainActivity.Java
package com.example.stocks;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.net.MalformedURLException;
import android.os.Handler;
public class MainActivity extends Activity implements Runnable {
String symbolsStr = "";
String resultsStr = "";
EditText symbols = null;
TextView results = null;
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
results.setText(resultsStr);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
symbolsStr = symbols.getText().toString();
Thread thread = new Thread(MainActivity.this);
thread.start();
}
});
}
#Override
public void run() {
try {
resultsStr = GetQuotes(symbolsStr);
mHandler.post(mUpdateResults);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String GetQuotes(String symbols) throws MalformedURLException,
IOException {
StringBuilder response = new StringBuilder();
// call web service to get results
String urlStr = "http://download.finance.yahoo.com/d/quotes.csv?s="
+ symbols + "&f=nsl1op";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
response.append("\n");
}
input.close();
}
return response.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="44dp"
android:text="Enter Symbols separated by commas:" />
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="16dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="44dp"
android:text="Look Up" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="33dp"
android:text="Results" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">StockQuotes</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
menu.xml
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/item1"></item>
<item android:id="#+id/item2"></item>
<item android:id="#+id/item3"></item>
</menu>
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stockquotes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<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="com.example.stockquotes.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>
Your packages mismatch:
In Activity: package com.example.stocks;
In Manifest:
package="com.example.stockquotes"
Use 1 of them and rebuild your project.
can someone help me plsss, the error message comes in the textbox on the login form, the error is when i submit my information on the first form it won't go to database instead showing error "error java.net.socketException: permission denied" here's my code:
tambah_user.java
package com.wilis.hellomysql;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class tambah_user extends Activity {
EditText un,pw,rpw,nl,al,nt,nh;
RadioGroup jk;
TextView error;
Button simpan,keluar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah_user);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
rpw=(EditText)findViewById(R.id.et_rpw);
nl=(EditText) findViewById(R.id.et_nama);
jk=(RadioGroup) findViewById(R.id.jekel);
al=(EditText) findViewById(R.id.et_alamat);
nt=(EditText) findViewById(R.id.et_notel);
nh=(EditText) findViewById(R.id.et_nohp);
simpan=(Button)findViewById(R.id.btn_simpan);
keluar=(Button)findViewById(R.id.btn_keluar);
error=(TextView)findViewById(R.id.error);
simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//atur variabel utk menampung pilihan jenis kelamin
String type=null;
switch (jk.getCheckedRadioButtonId()) {
case R.id.pria:
type="Pria";
break;
case R.id.perempuan:
type="Perempuan";
break;
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
postParameters.add(new BasicNameValuePair("repassword", rpw.getText().toString()));
postParameters.add(new BasicNameValuePair("nama", nl.getText().toString()));
postParameters.add(new BasicNameValuePair("jekel", type));
postParameters.add(new BasicNameValuePair("alamat", al.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_tlp", nt.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_hp", nh.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/simpan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Data Tersimpan");
else error.setText("Data Tersimpan Ke server");
}
catch (Exception e) {
un.setText(e.toString());
}
}
});
}
public void keluar (View theButton)
{
}
}
CustomHttpClient.java
package com.wilis.hellomysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
tambah_user.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Silakan Masukkan Data Pengguna"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000ff"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Username:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_un"
android:maxWidth="140sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_pw"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="retype-Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_rpw"
android:layout_width="match_parent"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nama Lengkap:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nama"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView android:text="Jekel:"
android:textColor="#ff0000ff"/>
<RadioGroup android:id="#+id/jekel">
<RadioButton android:id="#+id/pria"
android:text="Pria"
/>
<RadioButton android:id="#+id/perempuan"
android:text="Perempuan"
/>
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:text="Alamat:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_alamat"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor Tlp:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_notel"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor HP:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nohp"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow >
<Button android:text="S I M P A N"
android:id="#+id/btn_simpan"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button android:text="K E L U A R"
android:id="#+id/btn_keluar"
android:onClick="keluar"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:id="#+id/error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
</TableLayout>
</ScrollView>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wilis.hellomysql"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".tambah_user"
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=".CustomHttpClient" android:label="#string/app_name">
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
You have to add the internet permission to you manifiest file:
<uses-permission android:name="android.permission.INTERNET" />
And also Android wont let you do http connections in the main thread, for more info look up:
http://developer.android.com/reference/android/os/AsyncTask.html
You have forgotten the internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
After that you will get an networkonmainthreadexception because you are doing web request in the main thread.
Use another AsyncTask or another thread for that.
You did forget too add
<uses-permission android:name="android.permission.INTERNET" />
in your manifest.xml.
But after that you will receive a networkmainthreadexception, to avoid this you need to use AsyncTask or an extra thread. If you get problems to use this things you read this post which may helps you.
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>