我尝试在android中制作从字符串到二进制的转换器
这是我的主要活动
public class MainActivity extends Activity {
Converter converter;
static EditText str;
TextView hasil;
Button convert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
str = (EditText)findViewById(R.id.et_string);
hasil = (TextView)findViewById(R.id.txt_hasil);
final String kata =str.toString();
convert = (Button)findViewById(R.id.btn_conv);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
converter = new Converter();
converter.aksi1();
}
});
}
@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;
}
}
这是我的转换器类
public class Converter extends MainActivity {
EditText str;
TextView hasil;
String kata = str.getText().toString();
public void aksi1(){
if (kata != null){
byte[] bytes = kata.getBytes();
StringBuilder binary = new StringBuilder();
for(byte b : bytes){
int val = b;
for (int i = 0; i < 8; i++){
binary.append((val & 128) == 0 ? 0 : 1);// i dont know what this mean
val <<= 1;
}
}
hasil.setText(binary);
}
else{
convert.setEnabled(false);
}
}
}
这是我运行该代码时遇到的错误
07-30 15:17:39.798: E/AndroidRuntime(495): FATAL EXCEPTION: main
07-30 15:17:39.798: E/AndroidRuntime(495): java.lang.NullPointerException
07-30 15:17:39.798: E/AndroidRuntime(495): at com.example.strtobin.Converter.<init>(Converter.java:11)
07-30 15:17:39.798: E/AndroidRuntime(495): at com.example.strtobin.MainActivity$1.onClick(MainActivity.java:34)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.view.View.performClick(View.java:2408)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.view.View$PerformClick.run(View.java:8816)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.os.Handler.handleCallback(Handler.java:587)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.os.Handler.dispatchMessage(Handler.java:92)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.os.Looper.loop(Looper.java:123)
07-30 15:17:39.798: E/AndroidRuntime(495): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-30 15:17:39.798: E/AndroidRuntime(495): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 15:17:39.798: E/AndroidRuntime(495): at java.lang.reflect.Method.invoke(Method.java:521)
07-30 15:17:39.798: E/AndroidRuntime(495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-30 15:17:39.798: E/AndroidRuntime(495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-30 15:17:39.798: E/AndroidRuntime(495): at dalvik.system.NativeStart.main(Native Method)
第 11 行会发生什么?请告诉我这段代码是什么意思 binary.append((val & 128) == 0 ? 0 : 1)
非常感谢您的帮助... :)