我有2个活动让我们说A和B.在第一个(A)我选择我的列表视图,在第二个我列出这个列表视图(电台)并使用我从这个列表视图播放的媒体播放器。 我想要做的是,在第二个活动(B)中收听广播电台时,我想回到之前的活动并选择其他列表视图并更新活动B的列表视图。 我只是想从活动B回到A.但我不能。当我按下模拟器的后退按钮时,它给了我错误。我也试图让自己的后退按钮。相同的目的,但在应用程序中只有一个。
你能帮帮我吗,我做错了什么?因为在我之前的应用程序中,后退按钮和主页按钮功能正常而无需执在这一个中它们都不起作用。我使用的是2.2 SDK
logcat的:
02-13 02:42:52.106: E/AndroidRuntime(874): FATAL EXCEPTION: main
02-13 02:42:52.106: E/AndroidRuntime(874): java.lang.RuntimeException: Unable to pause activity {com.beanie.samples.streaming/com.beanie.samples.streaming.HomeActivity}: java.lang.NullPointerException
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3348)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3305)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3288)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.access$2500(ActivityThread.java:125)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.os.Handler.dispatchMessage(Handler.java:99)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.os.Looper.loop(Looper.java:123)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-13 02:42:52.106: E/AndroidRuntime(874): at java.lang.reflect.Method.invokeNative(Native Method)
02-13 02:42:52.106: E/AndroidRuntime(874): at java.lang.reflect.Method.invoke(Method.java:521)
02-13 02:42:52.106: E/AndroidRuntime(874): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-13 02:42:52.106: E/AndroidRuntime(874): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-13 02:42:52.106: E/AndroidRuntime(874): at dalvik.system.NativeStart.main(Native Method)
02-13 02:42:52.106: E/AndroidRuntime(874): Caused by: java.lang.NullPointerException
02-13 02:42:52.106: E/AndroidRuntime(874): at com.beanie.samples.streaming.HomeActivity.onPause(HomeActivity.java:439)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.Activity.performPause(Activity.java:3842)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1190)
02-13 02:42:52.106: E/AndroidRuntime(874): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3335)
我也试图实现onBackPressed,但它没有用。
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent info = new Intent(B_Activity.this,A_Activity.class);
moveTaskToBack(true);
info.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(info);
}
这是我的活动A
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class index extends Activity implements OnClickListener{
Button btnYerli,btnYabanci,btnFvrKanal,btnFvrSarki,btnRecs;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.index);
initializeUI();
if (AppStatus.getInstance(this).isOnline(this)) {
Toast t = Toast.makeText(this,"You are online!!!!",8000);
t.show();
} else{
Toast t = Toast.makeText(this,"You are not online!!!!",8000);
t.show();
Log.v("Home", "You are not online!!!!");
}
}
public void initializeUI(){
btnYerli = (Button) findViewById(R.id.btnYerli);
btnYerli.setOnClickListener(this);
btnYabanci = (Button) findViewById(R.id.btnYabanci);
btnYabanci.setOnClickListener(this);
btnFvrKanal = (Button) findViewById(R.id.btnKanalFvr);
btnFvrKanal.setOnClickListener(this);
btnFvrSarki = (Button) findViewById(R.id.btnSarkiFvr);
btnFvrSarki.setOnClickListener(this);
btnRecs = (Button) findViewById(R.id.btnRecs);
btnRecs.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
//String kanalList="yerli";
switch(arg0.getId()){
case R.id.btnYerli:
Intent openHomeActivityYerli = new Intent("com.beanie.samples.streaming.HOMEACTIVITY");
openHomeActivityYerli.putExtra("kanalList","yerli");
startActivity(openHomeActivityYerli);
break;
case R.id.btnYabanci:
Intent openHomeActivityYabanci = new Intent(index.this,HomeActivity.class);
openHomeActivityYabanci.putExtra("kanalList","yabanci");
startActivityForResult(openHomeActivityYabanci,0);
break;
case R.id.btnKanalFvr:
Intent openHomeActivityFavoriKanal = new Intent("com.beanie.samples.streaming.HOMEACTIVITY");
openHomeActivityFavoriKanal.putExtra("kanalList","favori");
startActivity(openHomeActivityFavoriKanal);
break;
}
}
}
这是我的Activiy B
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.spoledge.aacdecoder.AACPlayer;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends ListActivity implements OnClickListener, OnGesturePerformedListener{
private String[] radioNames;
private String[] radioUrls;
private String[] favoriteRadioNames;
private String[] favoriteRadioUrls;
private String selectedRadioUrl="http://46.20.4.58:8040/";
private String selectedRadioName="Select a radio station";
private String artist;
private String song;
private String stopMsg;
private String welcomeMsg;
private String noServerConnectionMsg;
private boolean favoriteButton=true;
private boolean metaDataThreadStop=false;
private int mediaType=1;
private int channelList=1;
private String JSONUrl;
private JSONObject JSONStations;
private ProgressBar playSeekBar;
private Button buttonChannelList;
private Button buttonStopPlay;
private Button buttonBack;
private TextView stationView,artistView,songView;
//private Button buttonRecord;
//private Button buttonStopRecord;
private MediaPlayer player;
private AACPlayer aacPlayer;
private Map<String, ?> favoriteChannelsMap;
private GestureLibrary mLibrary;
private Thread getMetaData;
//private InputStream recordingStream;
//private RecorderThread recorderThread;
//private boolean isRecording = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences favoriteChannels = getSharedPreferences("favorite_channels_list", 0);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
setChannelChoice();
JSONStations = getJSONfromURL(JSONUrl);
if(JSONStations == null){
Toast t = Toast.makeText(this,noServerConnectionMsg,8000);
t.show();
radioNames = getResources().getStringArray(R.array.radioName);
radioUrls = getResources().getStringArray(R.array.radioURL);
}else{
parseJSONtoArray(JSONStations);
}
mLibrary = GestureLibraries.fromRawResource(this, R.raw.radiogestures);
if (!mLibrary.load()) {
finish();
}
GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
gestures.setGestureColor(Color.TRANSPARENT);
initializeMediaPlayer();
stationView.setText(welcomeMsg);
chooseChannelList();
}
private void initializeUIElements() {
stopMsg = getResources().getString(R.string.stopMsg);
welcomeMsg=getResources().getString(R.string.welcomeMsg);
noServerConnectionMsg=getResources().getString(R.string.noServerConnection);
stationView = (TextView) findViewById(R.id.stationView);
artistView = (TextView) findViewById(R.id.artistView);
songView = (TextView) findViewById(R.id.songView);
//channelList = (TextView) findViewById(R.id.channelList);
//channelList.setOnClickListener(this);
//likeCheckBox =(CheckBox) findViewById(R.id.likeCheckBox);
//likeCheckBox.setOnClickListener(this);
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonChannelList = (Button) findViewById(R.id.buttonChannelList);
buttonChannelList.setOnClickListener(this);
buttonBack =(Button) findViewById(R.id.buttonBack);
buttonBack.setOnClickListener(this);
getFavoritChannels();
if (favoriteChannelsMap.isEmpty()){
buttonChannelList.setEnabled(false);
}else{
buttonChannelList.setEnabled(true);
}
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
/*buttonRecord = (Button) findViewById(R.id.buttonRecord);
buttonRecord.setOnClickListener(this);
buttonStopRecord = (Button) findViewById(R.id.buttonStopRecord);
buttonStopRecord.setOnClickListener(this);*/
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Toast t = Toast.makeText(this,"Back Button",8000);
t.show();
}
private void setChannelChoice(){
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String channels = extras.getString("kanalList");
if(channels.compareTo("yerli")==0){
JSONUrl = getResources().getString(R.string.JSONUrlYerli);
channelList = 1;
}
else if (channels.compareTo("yabanci")==0){
JSONUrl = getResources().getString(R.string.JSONUrlYabanci);
channelList = 1;
}
else if(channels.compareTo("favori")==0){
channelList = 2;
}
}else{
}
}
private void chooseChannelList(){
switch(channelList){
case 1:
showChannelsList();
break;
case 2:
showFavoriteChannelList();
break;
}
}
private void parseJSONtoArray(JSONObject JSONText){
List<String> radioNamesArrayList = new ArrayList<String>();
List<String> radioURLsArrayList = new ArrayList<String>();
try {
JSONObject KanallarObject = JSONText.getJSONObject("Kanallar");
//String versionString = KanallarObject.getString("Version");
JSONArray kanalArray = KanallarObject.getJSONArray("Kanal");
for(int i=0;i < kanalArray.length();i++){
radioNamesArrayList.add(kanalArray.getJSONObject(i).getString("Isim").toString());
radioURLsArrayList.add(kanalArray.getJSONObject(i).getString("Adres").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("log_tag", "Error parsing data "+e.toString());
}
radioNames = radioNamesArrayList.toArray(new String[radioNamesArrayList.size()]);
radioUrls = radioURLsArrayList.toArray(new String[radioURLsArrayList.size()]);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonBack:
Intent info = new Intent(HomeActivity.this,index.class);
Log.d("1","1");
moveTaskToBack(true);
Log.d("2","2");
info.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Log.d("3","3");
startActivityForResult(info,0);
break;
case R.id.buttonChannelList:
if (favoriteButton){
showFavoriteChannelList();
}else{
showChannelsList();
}
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
/*else if (v == buttonRecord) {
recorderThread = new RecorderThread();
recorderThread.start();
buttonRecord.setEnabled(false);
buttonStopRecord.setEnabled(true);
} else if (v == buttonStopRecord) {
stopRecording();
}*/
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d("onReStart","^^^^^^^^^RESTART^^^^^^");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("onResume","^^^^^^^^^RESUME^^^^^^");
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d("onStart","^^^^^^^^^START^^^^^^");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d("onStop","^^^^^^^^^STOP^^^^^^");
}
private void startPlaying() {
stationView.setText(selectedRadioName);
buttonStopPlay.setEnabled(true);
playSeekBar.setVisibility(View.VISIBLE);
initializeMediaPlayer();
switch(mediaType){
case 1:
aacPlayer.playAsync(selectedRadioUrl);
metaDataThreadStop=false;
getMetaData = new Thread(){
public void run(){
getMeta();
}
};
getMetaData.start();
break;
case 2:
player.setAudioStreamType(AudioManager.STREAM_RING);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
//buttonRecord.setEnabled(true);
}
});
break;
}
}
private void stopPlaying() {
int i=0;
stationView.setText(stopMsg);
switch(mediaType){
case 1:
aacPlayer.stop();
//aacPlayer.
metaDataThreadStop=true;
/*if (getMetaData!=null){
Log.d("Stop","threadNULL");
getMetaData.interrupt();
Log.d("threadInterrupted",String.valueOf(getMetaData.isInterrupted()));
try{
Log.d("Stop","threadJoin");
getMetaData.join();
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}*/
break;
case 2:
if (player.isPlaying()){
player.stop();
//aacPlayer.stop();
player.release();
}
break;
}
buttonChannelList.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
//buttonRecord.setEnabled(false);
//buttonStopRecord.setEnabled(false);
/*stopRecording();*/
}
private void initializeMediaPlayer() {
switch(mediaType){
case 1:
aacPlayer = new AACPlayer();
break;
case 2:
player = new MediaPlayer();
try {
player.setDataSource(selectedRadioUrl);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
break;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
artistView.setText("looking for artist info");
songView.setText("looking for song info");
if (favoriteButton){
selectedRadioUrl = radioUrls[position];
selectedRadioName = radioNames[position];
}else{
selectedRadioUrl = favoriteRadioUrls[position];
selectedRadioName = favoriteRadioNames[position];
}
switch(mediaType){
case 1:
stopPlaying();
startPlaying();
break;
case 2:
if (player.isPlaying()) {
stopPlaying();
startPlaying();
}
else{
startPlaying();
}
break;
}
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
public static JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8000);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
private void runLongClick(int clickId){
SharedPreferences favoriteChannels = getSharedPreferences("favorite_channels_list", 0);
SharedPreferences.Editor favoriteChannelsEditor = favoriteChannels.edit();
if (favoriteButton){
favoriteChannelsEditor.putString(radioNames[clickId], radioUrls[clickId]);
Toast.makeText(this, radioNames[clickId]+" added to favorites", Toast.LENGTH_LONG).show();
buttonChannelList.setEnabled(true);
favoriteChannelsEditor.commit();
}else{
Toast.makeText(this, favoriteRadioNames[clickId]+" removed From favorites", Toast.LENGTH_LONG).show();
favoriteChannelsEditor.remove(favoriteRadioNames[clickId]);
favoriteChannelsEditor.commit();
showFavoriteChannelList();
}
}
private void getFavoritChannels(){
SharedPreferences favoriteChannels = getSharedPreferences("favorite_channels_list", 0);
favoriteChannelsMap=favoriteChannels.getAll();
int i=0;
favoriteRadioNames = new String[favoriteChannelsMap.size()];
favoriteRadioUrls = new String[favoriteChannelsMap.size()];
Log.d("String Arrays",String.valueOf(favoriteRadioNames.length));
for(String s : favoriteChannelsMap.keySet()){
favoriteRadioNames[i]=s;
favoriteRadioUrls[i]=favoriteChannelsMap.get(s).toString();
i++;
}
}
private void showChannelsList(){
buttonChannelList.setText("Favorite Channels");
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this,R.layout.channels,R.id.channelList,radioNames);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
runLongClick(row);
return true;
}});
favoriteButton=!favoriteButton;
}
private void showFavoriteChannelList(){
buttonChannelList.setText("Channel List");
getFavoritChannels();
ArrayAdapter<String> adapterFavorits;
adapterFavorits = new ArrayAdapter<String>(this,R.layout.channels,R.id.channelList,favoriteRadioNames);
setListAdapter(adapterFavorits);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
runLongClick(row);
return true;
}});
favoriteButton=!favoriteButton;
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
Log.d("Gesture","Gesture Aldi");
// TODO Auto-generated method stub
ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
// We want at least one prediction
if (predictions.size() > 0) {
Prediction prediction = predictions.get(0);
// We want at least some confidence in the result
if (prediction.score > 1.0) {
// Show the spell
Toast.makeText(this, String.valueOf(prediction.score), Toast.LENGTH_SHORT).show();
stopPlaying();
}
}
}
public void getMeta(){
Timer timer;
timer = new Timer();
while(!metaDataThreadStop){
timer.schedule(new TimerTask() {
public void run() {
URL url;
//Message msg = handler.obtainMessage();
try {
Log.d("Metadatos","Dentro del try para obtener los metadatos");
url = new URL(selectedRadioUrl);
IcyStreamMeta icy = new IcyStreamMeta(url);
artist=icy.getArtist();
Log.d("artist",artist);
song=icy.getTitle();
Log.d("song",song);
handler.sendEmptyMessage(0);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 30000);}
timer.cancel();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(artist.compareTo("")==0 || artist.compareTo("-")==0)
artistView.setText("no artist info");
else{
artistView.setText(artist);
Log.d("handler_artist",artist);
}
if(song.compareTo("")==0 || song.compareTo("-")==0)
songView.setText("no song info");
else{
Log.d("handler_song",song);
songView.setText(song);
}
}
};
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// your stuff or nothing
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
答案 0 :(得分:1)
堆栈跟踪表明player
为空。
02-13 02:42:52.106: E/AndroidRuntime(874): Caused by: java.lang.NullPointerException
02-13 02:42:52.106: E/AndroidRuntime(874): at com.beanie.samples.streaming.HomeActivity.onPause(HomeActivity.java:439)
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
您显然仅针对player
为2的情况初始化mediaType
。否则,您正在初始化aacPlayer
。
private void initializeMediaPlayer() {
switch(mediaType){
case 1:
aacPlayer = new AACPlayer();
break;
case 2:
player = new MediaPlayer();
...
因此,您需要对player
进行空检查。或者,重构您的代码以封装两个不同媒体播放器的存在。