2011-09-24 2 views
2

Мне нужна помощь в моем настраиваемом диалоговом окне. Это первый раз, когда я создал пользовательское диалоговое окно и по какой-то причине он продолжает сбой. Ниже приведен код, который у меня есть в моем методе onCreate(). Я хочу щелкнуть по окну edittext, открыть диалоговое окно, затем ввести символ тикера или цену акций, нажать ОК, и он заполнит блок edittext. Пожалуйста, помогитеПроблемы с пользовательским диалоговым окном

public void test() { 
    // Click on Stock Price to bring up dialog box 
    myStockPrice.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      // Create the dialog 
      final Dialog dialog = new Dialog(
        OptionsPricingCalculatorActivity.this); 

      // Set the content view to our xml layout 
      dialog.setContentView(R.layout.enterstocksym); 

      // Set the title of the dialog. this space is always drawn even 
      // if blank so might as well use it 
      dialog.setTitle("Ticker Symbol"); 

      dialog.setCancelable(true); 
      // dialog.setMessage("Enter Company Ticker Symbol"); 

      // Here we add functionality to our dialog box's content. In 
      // this example it's the two buttons 

      // Set an EditText view to get user input 
      input = (EditText) findViewById(R.id.StockSymbol); 
      input2 = (EditText) findViewById(R.id.StockPrice); 

      Button okButton = (Button) dialog.findViewById(R.id.BtnOk); 

      okButton.setOnClickListener(new OnClickListener() { 
       public void onClick(View v) { 
        Tickervalue = input.getEditableText().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; 
         } 
        } 
       } 
      }); 

      Button cancelButton = (Button) dialog 
        .findViewById(R.id.BtnCancel); 
      cancelButton.setOnClickListener(new OnClickListener() { 
       public void onClick(View v) { 
        dialog.dismiss(); 
       } 
      }); 
      dialog.show(); 

     } 
    }); 

Logcat

09-24 04:10:51.252: ERROR/AndroidRuntime(428): FATAL EXCEPTION: main 
09-24 04:10:51.252: ERROR/AndroidRuntime(428): java.lang.NullPointerException 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at com.CSV.Buescher.OptionsPricingCalculatorActivity$2$1.onClick(OptionsPricingCalculatorActivity.java:186) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.view.View.performClick(View.java:2408) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.view.View$PerformClick.run(View.java:8816) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.os.Handler.handleCallback(Handler.java:587) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.os.Handler.dispatchMessage(Handler.java:92) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.os.Looper.loop(Looper.java:123) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at android.app.ActivityThread.main(ActivityThread.java:4627) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at java.lang.reflect.Method.invoke(Method.java:521) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
09-24 04:10:51.252: ERROR/AndroidRuntime(428):  at dalvik.system.NativeStart.main(Native Method) 
09-24 04:10:51.282: WARN/ActivityManager(59): Force finishing activity com.CSV.Buescher/.OptionsPricingCalculatorActivity 
09-24 04:10:51.865: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{44ece368 com.CSV.Buescher/.OptionsPricingCalculatorActivity} 
+2

Что такое ошибка в LogCat, показать LogCat. –

+0

com.CSV.Buescher.OptionsPricingCalculatorActivity $ 2 $ 1.onClick (OptionsPricingCalculatorActivity.java:186) - какая строка - номер строки 186? – kingori

+0

//Toast.makeText (getApplicationContext(), значение, –

ответ

0

Трудно сказать, с вложенными анонимными внутренними классами, но я думаю, что ваши виджеты с идентификаторами StockSymbol и StockPrice находятся в диалоге. Когда вы найдете их, тем не менее, вы сделаете так:

input = (EditText)findViewById(R.id.StockSymbol);  
input2 = (EditText)findViewById(R.id.StockPrice); 

Что ищет в деятельности, а не в диалоге. Они не обнаруживаются, поэтому при нажатии кнопки вводится значение null. Попробуйте вместо этого:

input = (EditText)dialog.findViewById(R.id.StockSymbol);  
input2 = (EditText)dialog.findViewById(R.id.StockPrice); 

Вы можете разбить внутренние классы, чтобы сделать все это проще читать и отлаживать.

+0

Вышеприведенный имеет смысл. Однако я все еще получаю ту же ошибку. У меня тяжелая отладка :( –

0

Приведенный ниже код работал понравившийся шарм, однако я хотел бы, чтобы пользовательский макет работал.

Благодаря

LinearLayout lila1= new LinearLayout(this); 
lila1.setOrientation(1); //1 is for vertical orientation 
final EditText input = new EditText(this); 
final EditText input1 = new EditText(this); 
lila1.addView(input); 
lila1.addView(input1); 
alert.setView(lila1); 
Смежные вопросы