2013-05-23 3 views
2

Я довольно новый Android-программист, и после работы с несколькими учебниками я начал расширять учебник по BMI Calculator, который я завершил. Во время этого процесса мне стало необходимо удалить и переустановить Eclipse. Мне также пришлось переключать рабочие области. Из-за ошибки с моей стороны я смог сохранить только файлы .java для приложения. Я воссоздал .xml и манифест, только теперь я получаю исключение IllegalStateException, когда пытаюсь щелкнуть кнопку расчета. Перед переходом и воссозданием все прошло отлично. Я использую эмулятор Nexus Galaxy, работающий 4.2.2 Вот код:java.lang.IllegalStateException: Не удалось выполнить метод активности с Android

package com.example.bmicalculator;

import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView;

public class MainActivity extends Activity { ImageDownloader downloader;

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

} 

public void calculateClickHandler(View view) { 
    if(view.getId() == R.id.calculateButton) { 
     EditText weightText = (EditText)findViewById(R.id.weightLabel); 
     EditText heightText = (EditText)findViewById(R.id.heightText); 
     TextView resultText = (TextView)findViewById(R.id.resultLabel); 
     TextView suggestText= (TextView)findViewById(R.id.suggestedFix); 
     ImageView image = (ImageView)findViewById(R.id.relatedPicture); 
     float weight = Float.parseFloat(weightText.getText().toString()); 
     float height = Float.parseFloat(heightText.getText().toString()); 

     float bmiValue = calculateBMI(weight, height); 

     String bmiInterpretation = interpretBMI(bmiValue); 

     String suggest = "We suggest " + interpretBMIInterpretation(bmiInterpretation); 

     resultText.setText(bmiValue + "-" + bmiInterpretation); 
     suggestText.setText(suggest); 
     setUpImage(image, bmiInterpretation); 
    } 
} 

private float calculateBMI(float weight, float height) { 
    return (float) (weight * 4.88/(height * height)); 
} 

private String interpretBMI(float bmiValue) { 
    if(bmiValue < 16) { 
     return "Severely underweight"; 
    } else if (bmiValue < 18.5) { 
     return "Underweight"; 
    } else if(bmiValue < 25) { 
     return "Normal"; 
    } 
    else if(bmiValue < 30) { 
     return "Overweight"; 
    } 
    else { 
     return "Obese"; 
    } 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

private String interpretBMIInterpretation(String interp) { 
    if(interp.equals("Severely underweight")) { 
     return "eating more. You can still work out and stay thin, but you need more weight."; 
    } 
    else if(interp.equals("Underweight")) { 
     return "eating a little more, alongside working out to gain muscle weight."; 
    } 
    else if(interp.equals("Normal")) { 
     return "continuing to do whatever it is you're doing."; 
    } 
    else if(interp.equals("Overweight")) { 
     return "working out a little. Lose a few fat poinds and put on some muscle pounds, and you'll be a healthy weight."; 
    } 
    else { 
     return "cutting back on your food intake and working out. A little goes a long way."; 
    } 
} 

private void setUpImage(ImageView image, String interp) { 
    if(interp.equals("Severely underweight")) { 
     image.setVisibility(View.INVISIBLE); 
     downloader = new ImageDownloader(image); 
     String url = "http://www.wendys.com/cs/Satellite?blobcol=urldata&blobheader=image%2Fpng&blobkey=id&blobtable=MungoBlobs&blobwhere=1365660287009&ssbinary=true"; 
     downloader.execute(url); 
    } 
    else if(interp.equals("Underweight")) { 
     image.setVisibility(View.INVISIBLE); 
     downloader = new ImageDownloader(image); 
     String url = "http://www.livestrongfitness.com/blog/wp-content/uploads/barbell.jpg"; 
     downloader.execute(url); 
    } 
    else if(interp.equals("Normal")) { 
     image.setVisibility(View.INVISIBLE); 
     downloader = new ImageDownloader(image); 
     String url = "http://primary3.tv/blog/wp-content/uploads/2011/03/thumbsup.jpg"; 
     downloader.execute(url); 
    } 
    else if(interp.equals("Overweight")) { 
     image.setVisibility(View.INVISIBLE); 
     downloader = new ImageDownloader(image); 
     String url = "http://www.livestrongfitness.com/blog/wp-content/uploads/barbell.jpg"; 
     downloader.execute(url); 
    } 
    else { 
     image.setVisibility(View.INVISIBLE); 
     downloader = new ImageDownloader(image); 
     String url = "http://wisefitnesstips.com/wp-content/uploads/2013/02/salad-nutrients-facts.jpg"; 
     downloader.execute(url); 
    } 
} 
} 

И в ImageDownload Класс:

package com.example.bmicalculator;

import java.io.InputStream; import java.net.URL;

import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.view.View; import android.widget.ImageView; public class ImageDownloader extends AsyncTask { ImageView image; public ImageDownloader(ImageView image) { this.image = image; } protected Bitmap doInBackground(String... strings) { try { Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(strings[0]).getContent()); return bitmap; } catch (Exception e) { System.out.println("Error: " + e); return null; } }

protected void onProgressUpdate(Integer... progress) { 

} 

protected void onPostExecute(Bitmap result) { 
    image.setImageBitmap(result); 
    image.setVisibility(View.VISIBLE); 
} } 

И в LogCat:

05-23 14:45:52.447: E/AndroidRuntime(1083): FATAL EXCEPTION: main 05-23 14:45:52.447: E/AndroidRuntime(1083): java.lang.IllegalStateException: Could not execute method of the activity 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.view.View$1.onClick(View.java:3599) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.view.View.performClick(View.java:4204) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.view.View$PerformClick.run(View.java:17355) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.os.Handler.handleCallback(Handler.java:725) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.os.Handler.dispatchMessage(Handler.java:92) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.os.Looper.loop(Looper.java:137) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-23 14:45:52.447: E/AndroidRuntime(1083): at java.lang.reflect.Method.invokeNative(Native Method) 05-23 14:45:52.447: E/AndroidRuntime(1083): at java.lang.reflect.Method.invoke(Method.java:511) 05-23 14:45:52.447: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-23 14:45:52.447: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-23 14:45:52.447: E/AndroidRuntime(1083): at dalvik.system.NativeStart.main(Native Method) 05-23 14:45:52.447: E/AndroidRuntime(1083): Caused by: java.lang.reflect.InvocationTargetException 05-23 14:45:52.447: E/AndroidRuntime(1083): at java.lang.reflect.Method.invokeNative(Native Method) 05-23 14:45:52.447: E/AndroidRuntime(1083): at java.lang.reflect.Method.invoke(Method.java:511) 05-23 14:45:52.447: E/AndroidRuntime(1083): at android.view.View$1.onClick(View.java:3594) 05-23 14:45:52.447: E/AndroidRuntime(1083): ... 11 more 05-23 14:45:52.447: E/AndroidRuntime(1083): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText 05-23 14:45:52.447: E/AndroidRuntime(1083): at com.example.bmicalculator.MainActivity.calculateClickHandler(MainActivity.java:23) 05-23 14:45:52.447: E/AndroidRuntime(1083): ... 14 more 05-23 14:47:48.527: D/dalvikvm(1158): GC_CONCURRENT freed 55K, 7% free 2770K/2948K, paused 6ms+14ms, total 96ms 05-23 14:47:48.877: D/gralloc_goldfish(1158): Emulator without GPU emulation detected. 05-23 14:47:53.837: D/InputEventConsistencyVerifier(1158): KeyEvent: ACTION_UP but key was not down. 05-23 14:47:53.837: D/InputEventConsistencyVerifier(1158): in android.widget.EditText{40d2d8e8 VFED..CL .F....I. 32,209-452,288

7f080003 app:id/heightText} 05-23 14:47:53.837: D/InputEventConsistencyVerifier(1158): 0: sent at 922301000000,

KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=922301, downTime=922168, deviceId=0, source=0x101 } 05-23 14:47:55.097: D/AndroidRuntime(1158): Shutting down VM 05-23 14:47:55.097: W/dalvikvm(1158): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 05-23 14:47:55.187: E/AndroidRuntime(1158): FATAL EXCEPTION: main 05-23 14:47:55.187: E/AndroidRuntime(1158): java.lang.IllegalStateException: Could not execute method of the activity 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.view.View$1.onClick(View.java:3599) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.view.View.performClick(View.java:4204) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.view.View$PerformClick.run(View.java:17355) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.os.Handler.handleCallback(Handler.java:725) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.os.Handler.dispatchMessage(Handler.java:92) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.os.Looper.loop(Looper.java:137) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-23 14:47:55.187: E/AndroidRuntime(1158): at java.lang.reflect.Method.invokeNative(Native Method) 05-23 14:47:55.187: E/AndroidRuntime(1158): at java.lang.reflect.Method.invoke(Method.java:511) 05-23 14:47:55.187: E/AndroidRuntime(1158): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-23 14:47:55.187: E/AndroidRuntime(1158): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-23 14:47:55.187: E/AndroidRuntime(1158): at dalvik.system.NativeStart.main(Native Method) 05-23 14:47:55.187: E/AndroidRuntime(1158): Caused by: java.lang.reflect.InvocationTargetException 05-23 14:47:55.187: E/AndroidRuntime(1158): at java.lang.reflect.Method.invokeNative(Native Method) 05-23 14:47:55.187: E/AndroidRuntime(1158): at java.lang.reflect.Method.invoke(Method.java:511) 05-23 14:47:55.187: E/AndroidRuntime(1158): at android.view.View$1.onClick(View.java:3594) 05-23 14:47:55.187: E/AndroidRuntime(1158): ... 11 more 05-23 14:47:55.187: E/AndroidRuntime(1158): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText 05-23 14:47:55.187: E/AndroidRuntime(1158): at com.example.bmicalculator.MainActivity.calculateClickHandler(MainActivity.java:23) 05-23 14:47:55.187: E/AndroidRuntime(1158): ... 14 more 05-23 14:47:57.797: I/Process(1158): Sending signal. PID: 1158 SIG: 9

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

ответ

1
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText 05-23 14:45:52.447: E/AndroidRuntime(1083): at 

EditText weightText = (EditText)findViewById(R.id.weightLabel); 
EditText heightText = (EditText)findViewById(R.id.heightText); 

один из weightText и heightText является TextView.

+0

Это было ... Я случайно переключил, какой идентификатор был weightLabel и weightText в файле XML. Спасибо! – HopeProgrammer1994

Смежные вопросы