【发布时间】:2014-11-01 09:35:44
【问题描述】:
我正在尝试调用一个名为GetText(); 的方法,该方法将布局上的TextView 从MainActivity 更改为。我正在使用服务类调用此方法,每次调用此方法时,我的程序都会完全崩溃并出现FATAL EXCEPTION 错误。
//主活动
package com.example.modulefour;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button BtnStart, BtnStop;
EditText Edt;
TextView one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BtnStart = (Button)findViewById(R.id.button1);
BtnStop = (Button) findViewById(R.id.button2);
Edt = (EditText) findViewById(R.id.editText1);
one = (TextView) findViewById(R.id.textView1);
}
public void GetText()
{
String Text = this.Edt.getText().toString();
this.one.setText(Text);
}
public void StartService(View v){
//start Service
startService(new Intent(getBaseContext(), ServiceAdapter.class));
}
public void StopService(View v){
//stop service
GetText();
}
@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);
}
}
//服务适配器
package com.example.modulefour;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class ServiceAdapter extends Service {
MainActivity main;
FileWriter fw;
BufferedWriter bw;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
this.main.GetText();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//write EditText to text file
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
【问题讨论】: