android.media.MediaPlayer.start () 'для пустой ссылки на объект - PullRequest
0 голосов
/ 22 мая 2018

Я пытаюсь добавить рингтон к этому макету, и я не могу знать, почему на нулевом объекте даже думал, что у меня есть 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 CustommerCall 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_custommer_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(CustommerCall.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(CustommerCall.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(CustommerCall.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();
    }
}

и это logcat

   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
                      at com.saoutimohamed.tewsilaclone.CustommerCall.onCreate(CustommerCall.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) 

этот рингтон должен быть звонком от гонщика к водителю

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

MediaPlayer - тяжелый процесс.Разработчики Android сказали, что не следует использовать в потоке пользовательского интерфейса, но если вы хотите его использовать, этот код работает просто отлично:

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

Вы можете написать этот код как угодно (onCreate, onStart, onResume).

0 голосов
/ 22 мая 2018

mediaPlayer.start ();удалить из onResume ()

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