【问题标题】:android.media.MediaPlayer.start()' on a null object referenceandroid.media.MediaPlayer.start()' 在空对象引用上
【发布时间】:2018-05-21 22:23:14
【问题描述】:

我正在尝试向此布局添加铃声,但我不知道为什么在一个空对象上,即使我在原始文件中有 mp3 铃声,我正在编写如下所示的代码。 任何人都可以提供帮助。

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.saoutimohamed.tewsilaclone.Common.Common;
import com.saoutimohamed.tewsilaclone.Mode.FCMResponse;
import com.saoutimohamed.tewsilaclone.Mode.Notification;
import com.saoutimohamed.tewsilaclone.Mode.Sender;
import com.saoutimohamed.tewsilaclone.Mode.Token;
import com.saoutimohamed.tewsilaclone.Remote.IFCMService;
import com.saoutimohamed.tewsilaclone.Remote.IGoogleAPI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CustomerCall extends AppCompatActivity {

    TextView txtTime, txtAddress, txtDistance;
    MediaPlayer mediaPlayer;

    IGoogleAPI mService;

    Button btnAccept, btnDecline;

    String customerId;
    IFCMService ifcmService;
    double lat,lng;


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

        mService = Common.getGoogleAPI();
        ifcmService = Common.getFCMService();

        txtAddress = findViewById(R.id.txtAddress);
        txtTime = findViewById(R.id.txtTime);
        txtDistance = findViewById(R.id.txtDistance);

        btnAccept = findViewById(R.id.btnAccept);
        btnDecline = findViewById(R.id.btnDecline);

        mediaPlayer = MediaPlayer.create(this,R.raw.ringtone);
        mediaPlayer.start();
        mediaPlayer.setLooping(true);

        if (getIntent() != null)
        {
             lat = getIntent().getDoubleExtra("lat",-1.0);
             lng = getIntent().getDoubleExtra("lng",-1.0);
            customerId = getIntent().getStringExtra("customer");


            getDirection(lat,lng);
        }
        btnDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(customerId))
                    cancelBooking(customerId);
            }
        });

        btnAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CustomerCall.this,DriverTracking.class);

                intent.putExtra("lat",lat);
                intent.putExtra("lng",lng);
                startActivity(intent);
                finish();

            }
        });

    }

    private void cancelBooking(String customerId) {
        Token token = new Token(customerId);
        Notification notification = new Notification("Notice!","Driver has cancelled your request");
        Sender sender = new Sender(token.getToken(),notification);
        ifcmService.sandMessage(sender)
                .enqueue(new Callback<FCMResponse>() {
                    @Override
                    public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
                        if (response.body().success ==1)
                        {
                            Toast.makeText(CustomerCall.this, "Cancelled", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<FCMResponse> call, Throwable t) {

                    }
                });
    }

    private void getDirection(double lat,double lng) {
        String requestApi;
        try {
            requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
                    "mode=driving&" +
                    "transit_routing_preference=less_driving&" +
                    "origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
                    "destination=" + lat+","+lng + "&" +
                    "key=" + getResources().getString(R.string.google_direction_api);
            Log.d("SAOUTI", requestApi);
            mService.getPath(requestApi)
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());

                                JSONArray routes = jsonObject.getJSONArray("routes");

                                JSONObject object = routes.getJSONObject(0);

                                JSONArray legs = object.getJSONArray("legs");

                                JSONObject legsObject = legs.getJSONObject(0);

                                JSONObject distance = legsObject.getJSONObject("distance");

                                txtDistance.setText(distance.getString("text"));

                                JSONObject time = legsObject.getJSONObject("duration");

                                txtTime.setText(time.getString("text"));

                                String address = legsObject.getString("end_address");

                                txtAddress.setText(address);



                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            Toast.makeText(CustomerCall.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        mediaPlayer.release();
        super.onStop();
    }

    @Override
    protected void onPause() {
        mediaPlayer.release();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mediaPlayer.start();
    }
}

这是日志猫

   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
                      at com.saoutimohamed.tewsilaclone.CustomerCall.onCreate(CustomerCall.java:60)
                      at android.app.Activity.performCreate(Activity.java:7174)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
                      at android.os.Handler.dispatchMessage(Handler.java:105) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6938) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

这个铃声应该是骑手打给司机的电话

【问题讨论】:

  • 我的猜测是MediaPlayer 实例需要一些时间来准备;这就是为什么你应该异步调用.create() 并且只有.start() 在准备完成时运行的回调中调用它:developer.android.com/guide/topics/media/…(也:javascript!= java)

标签: java android media-player ringtone


【解决方案1】:

mediaPlayer.start();从 onResume() 中删除

 @Override
protected void onResume() {
    super.onResume();   
}

【讨论】:

  • 谢谢你,我得到了问题,现在解决了
【解决方案2】:

MediaPlayer 是繁重的进程。 Android 开发者说不应该在 Ui 线程中使用,但如果你想使用它,这段代码就可以了:

mediaPlayer=MediaPlayer.create(this,R.raw.pota);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });

您可以随心所欲地编写此代码(onCreate、onStart、onResume)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-09
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多