It seems to have done everything, as it is written in https://www.sitepoint.com/using-the-youtube-api-to-embed-video-in-an-android-app/ , but crashes when launched, how to fix it?

public class ContestsDetals extends AppCompatActivity implements YouTubePlayer.OnInitializedListener { private String url = "https://adftegcb.com/api/contestspets?id=9&token=$1$vLyWeNSm$tMhTzT5N7KKu4nznlCZ1Q.&number="; private String TAG = ContestsView.class.getSimpleName(); private ProgressDialog pDialog; private String idUrl = ""; private String title = "Contest view"; ArrayList<HashMap<String, String>> contactList; private ListView lv; private ListView lv2; public static final String YOUTUBE_API_KEY = "AIzaSyABW6E8tWmZvMgDspTHlOMdb6zmqETC4kk"; private static final int RECOVERY_REQUEST = 1; private YouTubePlayerView youTubeView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contests_detals); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); lv2 = (ListView) findViewById(R.id.list2); youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); youTubeView.initialize(YOUTUBE_API_KEY, this); new ContestsDetals.GetContacts().execute(); } @Override public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo } } @Override public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) { if (errorReason.isUserRecoverableError()) { errorReason.getErrorDialog(this, RECOVERY_REQUEST).show(); } else { String error = String.format(getString(R.string.player_error), errorReason.toString()); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RECOVERY_REQUEST) { // Retry initialization if user performed a recovery action getYouTubePlayerProvider().initialize(YOUTUBE_API_KEY, this); } } protected Provider getYouTubePlayerProvider() { return youTubeView; } public class MyAdapter extends SimpleAdapter { public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } public View getView(int position, View convertView, ViewGroup parent) { setTitle(title); // here you let SimpleAdapter built the view normally. View v = super.getView(position, convertView, parent); // Then we get reference for Picasso ImageView img = (ImageView) v.getTag(); if (img == null) { img = (ImageView) v.findViewById(R.id.ivBasicImage); v.setTag(img); // <<< THIS LINE !!!! } // get the url from the data you passed to the `Map` // do Picasso // maybe you could do that by using many ways to start String url = (String) ((Map)getItem(position)).get("photo"); boolean ifyoutube = url.contains("/vi/"); com.squareup.picasso.Transformation transformation = new RoundedTransformationBuilder() .borderColor(Color.BLACK) .borderWidthDp(0) .cornerRadiusDp(100) .oval(false) .build(); if (ifyoutube) { Picasso.with(getBaseContext()) .load(url) .fit() .centerCrop() .transform(transformation) .into(img); } else { url = url.replaceAll(".jpg", "_square.jpg"); Picasso.with(getBaseContext()) .load(url) .fit() .centerCrop() .transform(transformation) .into(img); } // return the view return v; } } public class GetContacts extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(ContestsDetals.this); pDialog.setMessage("Loading..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response Intent intent = getIntent(); String idUrl = intent.getStringExtra("EXTRA_ID"); String jsonStr = sh.makeServiceCall(url+idUrl); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { Log.e(TAG, "URL: " + url); JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contests = jsonObj.getJSONArray("contest"); //ContestsCount = jsonObj.getString("Count"); // looping through All Contacts for (int i = 0; i < contests.length(); i++) { JSONObject c = contests.getJSONObject(i); String id = c.getString("id"); String type = c.getString("type"); title = c.getString("title"); String text = c.getString("text"); String count = c.getString("count"); String photo = c.getString("img"); // Phone node is JSON Object JSONObject user_id = c.getJSONObject("user_id"); String id_user = user_id.getString("id"); String name = user_id.getString("name"); String username = user_id.getString("username"); // Phone node is JSON Object JSONObject time = c.getJSONObject("time"); String start = time.getString("start"); String finish = time.getString("finish"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("type", type); contact.put("title", title); contact.put("text", text); contact.put("count", count); contact.put("id_user", id_user); contact.put("name", name); contact.put("username", username); contact.put("start", start); contact.put("finish", finish); contact.put("photo", photo); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) { pDialog.dismiss(); } /** * Updating parsed JSON data into ListView * */ Log.e(TAG, "Response from url: 1"); ListAdapter adapter = new ContestsDetals.MyAdapter( ContestsDetals.this, contactList, R.layout.content_contests_detals, new String[]{"id", "type", "title", "text", "count", "id_user", "name", "username", "start", "finish"}, new int[]{R.id.id, R.id.type, R.id.title, R.id.text, R.id.count, R.id.id_user, R.id.name, R.id.username, R.id.start, R.id.finish}); ListAdapter adapter2 = new ContestsDetals.MyAdapter( ContestsDetals.this, contactList, R.layout.content_contests_detals, new String[]{"id", "type", "title", "text", "count", "id_user", "name", "username", "start", "finish"}, new int[]{R.id.id, R.id.type, R.id.title, R.id.text, R.id.count, R.id.id_user, R.id.name, R.id.username, R.id.start, R.id.finish}); lv.setAdapter(adapter); lv2.setAdapter(adapter2); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } } 

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_contests_detals" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.unkop.unkop.ContestsDetals"> <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_view" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="0dp" /> <ListView android:id="@+id/list2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center"/> </RelativeLayout> 

ERROR:

 E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.unkop.unkop/com.unkop.unkop.ContestsDetals}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2463) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) at android.app.ActivityThread.access$600(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:5751) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.unkop.unkop.ContestsDetals.onCreate(ContestsDetals.java:63) at android.app.Activity.performCreate(Activity.java:5165) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1103) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2419) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) at android.app.ActivityThread.access$600(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:5751) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850) at dalvik.system.NativeStart.main(Native Method) 
  • one
    Show the 63rd line from the ContestsDetals.java file. - post_zeew
  • one
    By the way, if the given xml is R.layout.activity_contests_detals , then there is not a single ListView , however you are trying to find them there. - post_zeew
  • Show the 63rd line of youTubeView.initialize (YOUTUBE_API_KEY, this); - Denysevych Illya
  • R.layout.activity_contests_detals - I did not show that there is a list, but because json is loading data from the server, I continue to display video in each sheet, but when I insert the code for the video, the application already crashes. - Denysevych Illya
  • In R.layout.activity_contests_detals is R.id.youtube_view ? - post_zeew

1 answer 1

Here's an easier way to play YouTube :

in import: import com.google.android.youtube.player.YouTubeStandalonePlayer;

 Intent intent = YouTubeStandalonePlayer.createVideoIntent( ContestsDetals.this, YOUTUBE_API_KEY, "ID видео из YouTube" ); PackageManager pm = getPackageManager(); if (intent.resolveActivity(pm) != null) { startActivity(intent); } else { Toast.makeText(ContestsDetals.this, "Установите приложение YouTube для просмотра видео", Toast.LENGTH_SHORT).show(); } 

if your import is not determined, then the file in Gradle not Gradle :

compile files('libs/YouTubeAndroidPlayerApi.jar')