我正在学习如何用Java编写Android程序,我的程序一直在崩溃。它被认为是从摄氏温度转换为华氏温度。
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener
{
public static final int MY_CODE=2;
EditText temp;
RadioButton converttoF,converttoC,selectedtype;
RadioGroup conversion;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conversion = (RadioGroup)findViewById(R.id.conversion);
conversion.setOnCheckedChangeListener(this);
converttoF = (RadioButton)findViewById(R.id.converttoF);
converttoC = (RadioButton)findViewById(R.id.converttoC);
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
selectedtype = (RadioButton) findViewById(checkedId);
Intent i = new Intent(this, Activity4Result.class);
i.putExtra("temper", temp.getText().toString());
if(selectedtype.equals(converttoC))
{
Toast.makeText(this,"C chosen", Toast.LENGTH_SHORT).show();
i.putExtra("type", 'c');
startActivityForResult(i, MY_CODE);
}
else
{
Toast.makeText(this,"F chosen", Toast.LENGTH_SHORT).show();
i.putExtra("type", 'f');
startActivityForResult(i, MY_CODE);
}
}
}
我的猜测是问题出现在“onCheckedChanged”中,因为当我推送任何RadioButton时它会崩溃。
答案 0 :(得分:1)
我假设(如果你发布崩溃日志和你的问题会更好,这样我们可以帮助你更好地停止假设)你得到一个空指针异常< / em>在以下代码中:
i.putExtra("temper", temp.getText().toString());
在您的代码中,您声明了temp
,但它从未初始化。在使用之前需要初始化temp。