?
Solved

Having Issues with Running web service from Dialog Box

Posted on 2011-09-20
3
Medium Priority
?
408 Views
Last Modified: 2012-08-13
Hello,

I'm having issues imbedding my java code into a dialog box. I have a dialog box that opens when an EDitText is clicked. I have code that request data from a web service (Stock Quote) and returns StockPrice to a text box. Now I need to implement this to work when I enter the Stock Sym in the dialog box to populate my edit Text box. Please see code.

Thanks
Main.XML

<?xml version="1.1" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_height="50dp" android:weightSum="1" android:layout_width="531dp">
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Stock Price" 
       			android:lines="2" 
       			android:layout_width="57dp" 
       			android:gravity="center" 
       			android:id="@+id/lblStockPrice">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Exercise or Strike Price" 
       			android:lines="2" 
       			android:layout_width="70dp" 
       			android:gravity="center" 
       			android:id="@+id/lblExercise">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Days to Expiration" 
       			android:lines="2" 
       			android:layout_width="70dp" 
       			android:gravity="center" 
       			android:id="@+id/lblDaysToExp">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Treasury Return" 
       			android:lines="2" 
       			android:layout_width="70dp" 
       			android:gravity="center" 
       			android:id="@+id/lblTreasuryReturn">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Volatility (Std Dev)" 
       			android:lines="2" 
       			android:layout_width="70dp" 
       			android:gravity="center" 
       			android:id="@+id/lblVolatility">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Call Value" 
       			android:lines="2" 
       			android:gravity="center"
       			android:layout_width="57dp" 
       			android:id="@+id/lblCallValue">
       </TextView>
       <TextView android:textAppearance="?android:attr/textAppearanceSmall" 
       			android:layout_height="wrap_content" 
       			android:text="Put Value" 
       			android:lines="2" 
       			android:gravity="center"
       			android:layout_width="57dp" 
       			android:id="@+id/lblPutValue">
       </TextView>
       <TextView android:layout_width="40dp" android:lines="2" android:layout_height="wrap_content" android:visibility="invisible" android:id="@+id/lbld1" android:text="d1" android:textAppearance="?android:attr/textAppearanceSmall" android:gravity="center"></TextView>
       <TextView android:layout_width="40dp" android:lines="2" android:layout_height="wrap_content" android:visibility="invisible" android:id="@+id/lbld2" android:text="d2" android:textAppearance="?android:attr/textAppearanceSmall" android:gravity="center"></TextView>
    </LinearLayout>
    <LinearLayout android:id="@+id/linearLayout2" android:layout_width="531dp" android:layout_height="wrap_content">
        <EditText android:text="32.61" android:layout_width="57dp" android:layout_height="30dp" android:inputType="numberDecimal" android:id="@+id/txtStockPrice" android:textSize="12dp"></EditText>
        <EditText android:text="32" android:layout_width="70dp" android:layout_height="30dp" android:inputType="numberDecimal" android:id="@+id/txtExercise" android:textSize="12dp"></EditText>
        <EditText android:text="25" android:layout_width="70dp" android:layout_height="30dp" android:inputType="numberDecimal" android:id="@+id/txtDaysToExp" android:textSize="12dp"></EditText>
        <EditText android:text="2" android:layout_width="70dp" android:layout_height="30dp" android:inputType="numberDecimal" android:id="@+id/txtTreasuryReturn" android:textSize="12dp"></EditText>
        <EditText android:text="41.7" android:layout_width="70dp" android:layout_height="30dp" android:inputType="numberDecimal" android:id="@+id/txtVolatility" android:textSize="12dp"></EditText>
        <TextView android:text="0.00" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_width="57dp" android:gravity="center" android:id="@+id/txtCallValue"></TextView>
        <TextView android:text="0.00" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_width="57dp" android:gravity="center" android:id="@+id/txtPutValue"></TextView>
        <TextView android:layout_width="40dp" android:layout_height="wrap_content" android:visibility="invisible" android:id="@+id/txtD1" android:text="0.00" android:textAppearance="?android:attr/textAppearanceSmall" android:gravity="center"></TextView>
        <TextView android:layout_width="40dp" android:layout_height="wrap_content" android:visibility="invisible" android:id="@+id/txtD2" android:text="0.00" android:textAppearance="?android:attr/textAppearanceSmall" android:gravity="center"></TextView>
    </LinearLayout>
    <GridView android:id="@+id/gridView1" android:numColumns="7" android:layout_height="140dp" android:layout_width="448dp" android:verticalSpacing="1dp" android:horizontalSpacing="10dp" android:columnWidth="64dp"></GridView>
    <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_width="match_parent">
        <Button android:id="@+id/btnCalculate" android:text="Calculate" android:textSize="10dp" android:layout_height="30dp" android:gravity="center" android:layout_width="wrap_content"></Button>
        <Button android:id="@+id/btnNextActivity" android:text="GoToNextActivity" android:textSize="10dp" android:layout_marginRight="38dp" android:layout_height="30dp" android:layout_width="wrap_content"></Button>
    </LinearLayout>

</LinearLayout>

OLD Activity Code

package com.CSV.Buescher;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class StockQuoteLkup extends Activity {

	  private static final String NAMESPACE = "http://www.webserviceX.NET/";
	  private static final String SERVICE_URL = "http://www.webservicex.net/stockquote.asmx";
	  private static final String METHOD_NAME = "GetQuote";
	  private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

	  Button Request;
	  TextView myOutput;
	  EditText myStockSymbol;
	  String Data;
	  
	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	      super.onCreate(savedInstanceState);
	      setContentView(R.layout.stockquote);
			      // Link display objects to variables
		      Request = (Button)findViewById(R.id.btnRequest);
		      myOutput = (TextView)findViewById(R.id.txtOutput);
		      myStockSymbol = (EditText)findViewById(R.id.txtStockSym);      
		      
	      Request.setOnClickListener(new OnClickListener(){
	      	public void onClick(View v){
		      		// On click send data to from EditView to TextView
	            //Data = myStockSymbol.getText().toString();
	      		//final TextView mTextView = (TextView) findViewById(R.id.txtOutput);
	      		//mTextView.setText(Data);
	      		requestStock();
	      	}
	      	
	      });
	      
	  }
	  
	  public void requestStock() {
		    // Send Stock Symbol into Request
			EditText edSymbol = (EditText) findViewById( R.id.txtStockSym );
		    SoapObject request = new SoapObject( NAMESPACE, METHOD_NAME );
		    request.addProperty( "symbol", edSymbol.getText().toString() );
		    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
		    envelope.setOutputSoapObject( request );
		    envelope.dotNet = true;
		    HttpTransportSE httpTransport = new HttpTransportSE( SERVICE_URL );
		    //httpTransport.debug = true;
		    try {
		      httpTransport.call( SOAP_ACTION, envelope );
		      SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
		      parseResponse( result.toString() );
		    } catch ( Exception e ) {
		      Log.d( "STOCK", e.getClass().getName() + ": " + e.getMessage() );
		      Toast t = Toast.makeText( this, e.getClass().getName() + ": " + e.getMessage(), 10 );
		      t.show();
		    }
		  }
	  
	  public void parseResponse( String response ) throws Exception {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse( new InputSource( new InputStreamReader( new ByteArrayInputStream( response.getBytes() ), "UTF-8" ) ) );
			Element element = document.getDocumentElement();
			NodeList stocks = element.getElementsByTagName( "Stock" );
			if ( stocks.getLength() > 0 ) {
		      for ( int i = 0; i < stocks.getLength(); ) {
		        Element stock = (Element) stocks.item( i );
		        Element value = (Element) stock.getElementsByTagName( "Last" ).item( 0 );
		        // Send data from response to OUTPUT object
		        TextView tv = (TextView) findViewById( R.id.txtOutput );
		        tv.setText( value.getFirstChild().getNodeValue() );
		        break;
		      }
		    }
		  }  
	  
	}

Need to imbed the Request Code() into the Main Activity

package com.C.B;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;


public class OptionsPricingCalculatorActivity extends Activity {
    /** Called when the activity is first created. */


	
    Button myButton;
    
    Button NextActivity;
    
    EditText myStockPrice;
    EditText myExercise;


	
    String[] sSP = new String [9];
    Double[] dSP = new Double [9];
    String[] sEX = new String [9];
    Double[] dEX = new Double [9];
    String[] sDTE = new String [9];
    Double[] dDTE = new Double [9];
    String[] sTR = new String [9];
    Double[] dTR = new Double [9];
    String[] sVL = new String [9];
    Double[] dVL = new Double [9];
    String[] sD1 = new String [9];
    Double[] dD1 = new Double [9];
    String[] sD2 = new String [9];
    Double[] dD2 = new Double [9];
    String[] sCV = new String [9];
    Double[] dCV = new Double [9];
    String[] sPV = new String [9];
    Double[] dPV = new Double [9];    
    String[] sGA = new String [56];
	
	SDCalculator SD = new SDCalculator();
	DecimalFormat df2 = new DecimalFormat("#0.00");
	DecimalFormat df3 = new DecimalFormat("#0.000");
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.add(0, 1, 0, "Exersice Price");
    	menu.add(0, 2, 0, "Days To Expiration");
    	menu.add(0, 3, 0, "TreasuryReturn");
    	menu.add(0, 4, 0, "Volatility");
    	return true;
    }
   
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        NextActivity = (Button)findViewById(R.id.btnNextActivity);
        myButton = (Button)findViewById(R.id.btnCalculate);
        myStockPrice = (EditText)findViewById(R.id.txtStockPrice);

        NextActivity.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Click button to Move to Next Activity
                Intent myIntent = new Intent(getApplicationContext(), StockQuoteLkup.class);
                startActivity(myIntent);				
			}
		});
        
        
        // Click on Stock Price to bring up dialog box
        myStockPrice.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Click button to Move to Next Activity
                //Intent myIntent = new Intent(getApplicationContext(), StockQuoteLkup.class);
                //startActivity(myIntent);
                
                final AlertDialog.Builder alert = new AlertDialog.Builder(OptionsPricingCalculatorActivity.this);
        		final EditText input = new EditText(OptionsPricingCalculatorActivity.this);
        		alert.setView(input);
        		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int whichButton) {
        				String value = input.getText().toString().trim();
        				
        				//Toast.makeText(getApplicationContext(), value,
        						//Toast.LENGTH_SHORT).show();
        			}
        		});

        		alert.setNegativeButton("Cancel",
        				new DialogInterface.OnClickListener() {
        					public void onClick(DialogInterface dialog, int whichButton) {
        						dialog.cancel();
        					}
        				});
        		alert.show();
                
			}
		});
 
	public static String getServiceUrl() {
		return SERVICE_URL;
	}

	public static String getSoapAction() {
		return SOAP_ACTION;
	}
}

Manifest

<?xml version="1.1" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.CSV.Buescher"
      android:versionName="1.1" android:versionCode="1">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".OptionsPricingCalculatorActivity"
                  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=".StockQuoteLkup"></activity>        
		<activity android:name=".DaysToExpriation" android:label="Days To Expiration"></activity>
		<activity android:name=".ExersicePrice" android:label="Exersice Price"></activity>
		<activity android:name=".TreasuryReturn" android:label="Treasury Return"></activity>
		<activity android:name=".Volatility" android:label="Volatility"></activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />	
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    
</manifest>

Open in new window

0
Comment
Question by:lulubell-b
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
3 Comments
 

Author Comment

by:lulubell-b
ID: 36580852
I finally got it.

0
 

Accepted Solution

by:
lulubell-b earned 0 total points
ID: 36580859
Closing issue
final EditText input = new EditText(OptionsPricingCalculatorActivity.this); 		
        		alert.setView(input);
        		
        		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int whichButton) {
        				Tickervalue = input.getText().toString().trim();
        				  // Do something with value!

        				//Toast.makeText(getApplicationContext(), value,
        						//Toast.LENGTH_SHORT).show();
        				// Send Stock Symbol into Request
        			    SoapObject request = new SoapObject( NAMESPACE, METHOD_NAME );
        			    request.addProperty( "symbol", Tickervalue );
        			    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
        			    envelope.setOutputSoapObject( request );
        			    envelope.dotNet = true;
        			    HttpTransportSE httpTransport = new HttpTransportSE( SERVICE_URL );
        			    //httpTransport.debug = true;
        			    try {
        			      httpTransport.call( SOAP_ACTION, envelope );
        			      SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
        			      parseResponse( result.toString() );
        			    } catch ( Exception e ) {
        			      Log.d( "STOCK", e.getClass().getName() + ": " + e.getMessage() );
        			      Toast t = Toast.makeText( OptionsPricingCalculatorActivity.this, e.getClass().getName() + ": " + e.getMessage(), 10 );
        			      t.show();
        			    }
        				
        			}

					private void parseResponse(String response) throws Exception {
						// TODO Auto-generated method stub
						
						DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
						DocumentBuilder db = dbf.newDocumentBuilder();
						Document document = db.parse( new InputSource( new InputStreamReader( new ByteArrayInputStream( response.getBytes() ), "UTF-8" ) ) );
						Element element = document.getDocumentElement();
						NodeList stocks = element.getElementsByTagName( "Stock" );
						if ( stocks.getLength() > 0 ) {
					      for ( int i = 0; i < stocks.getLength(); ) {
					        Element stock = (Element) stocks.item( i );
					        Element Tickervalue = (Element) stock.getElementsByTagName( "Last" ).item( 0 );
					        // Send data from response to OUTPUT object
					        EditText tv = (EditText) findViewById( R.id.txtStockPrice );
					        tv.setText( Tickervalue.getFirstChild().getNodeValue() );
					        break;

Open in new window

0
 

Author Closing Comment

by:lulubell-b
ID: 36580862
No One responded to my question.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
These days software publishers make it possible to move all the possible applications on smartphones, tablets, smartwatches, and more. Although behind every logic and decision is a gross doubt: how do they make it possible? In this blog post, we sha…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question