Error Inflating New Fragment - java

Summary: MainActivityFragment passes passes an intent to DetailedActivity when an item is clicked to display detailed data. Since I want to display these within a Two-Pane interface, I needed to make the DetailedActivity a fragment.
Problem : Whenever clicking on the item in MainActivityFragment to launch the intent for DetailedActivityFragment, I get an error saying its unable to start or inflate the activity. The detailedActivity for sake here is named "test" and "testFragment". It appears as though it points to line 25 of the activity_test.xml which is the line of include layout="#...".
I have left the fragment_test.xml out due to its length but i will provide a github link to anyone whom may want to see it or the manifest.
Im currently a novice to the android world so any help is appriciated =)! This branch of my project is a huge mess right now experimenting with things right now so pardon the mess...
Github Link:https://github.com/Rykuno/Flix-Viewer/tree/tablet/app/src/main/java/com/rykuno/movietestapp/Activities
FATAL EXCEPTION: main
Process: com.rykuno.movietestapp, PID: 14281
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rykuno.movietestapp/com.rykuno.movietestapp.Activities.test}: android.view.InflateException: Binary XML file line #25: Binary XML file line #1: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #25: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2172)
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:941)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393) 
at android.app.Activity.setContentView(Activity.java:2172) 
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
at com.rykuno.movietestapp.Activities.testFragment.setViewData(testFragment.java:100)
at com.rykuno.movietestapp.Activities.testFragment.onCreateView(testFragment.java:87)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:941) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393) 
at android.app.Activity.setContentView(Activity.java:2172) 
at com.rykuno.movietestapp.Activities.test.onCreate(test.java:14) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Here is the code to the Activity Files vvv
package com.rykuno.movietestapp.Activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.rykuno.movietestapp.R;
public class test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
And the fragment
package com.rykuno.movietestapp.Activities;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.rykuno.movietestapp.Adapter.TrailerAdapter;
import com.rykuno.movietestapp.BuildConfig;
import com.rykuno.movietestapp.Data.DatabaseHelper;
import com.rykuno.movietestapp.R;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* A placeholder fragment containing a simple view.
*/
public class testFragment extends Fragment {
private static final String MOVIEKEYS = "videoKeys";
private String movieVideoUrl;
private List<String> movieKeys = new ArrayList<>();
private String mPoster;
private String mOriginalTitle;
private String mPlot;
private String mReleaseDate;
private String mBackDrop;
private String mRating;
private boolean mFavorited = false;
private int mId;
private DatabaseHelper db;
private TrailerAdapter mTrailerAdapter;
#Bind(R.id.title_textView)
TextView mTitleTextView;
#Bind(R.id.rating_textView)
TextView mRatingTextView;
#Bind(R.id.plot_textView)
TextView mPlotTextView;
#Bind(R.id.backdrop_image)
ImageView mBackdropImageView;
#Bind(R.id.poster_imageView)
ImageView mPosterImageView;
#Bind(R.id.released_textView)
TextView mReleaseDateTextView;
#Bind(R.id.comments_button)
Button mCommentsButton;
#Bind(R.id.favorite_imageView)
ImageView mFavoritesImageView;
#Bind(R.id.trailer_gridview)
GridView mGridView;
public testFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_test, container, false);
db = new DatabaseHelper(getActivity());
ButterKnife.bind(getActivity());
extractExtras();
setViewData();
getMovieYoutubeHandle();
setClickItems();
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setViewData() {
Picasso.with(getActivity()).load("http://image.tmdb.org/t/p/w780/" + mBackDrop).into(mBackdropImageView);
Picasso.with(getActivity()).load("http://image.tmdb.org/t/p/w342/" + mPoster).into(mPosterImageView);
mTitleTextView.setText(mOriginalTitle);
mRatingTextView.setText(mRating + "/10");
mPlotTextView.setText(mPlot);
mReleaseDateTextView.setText(mReleaseDate);
}
private void extractExtras() {
mPoster = getActivity().getIntent().getStringExtra("poster");
mOriginalTitle = getActivity().getIntent().getStringExtra("title");
mPlot = getActivity().getIntent().getStringExtra("plot");
mReleaseDate = getActivity().getIntent().getStringExtra("releaseDate");
mBackDrop = getActivity().getIntent().getStringExtra("backdrop");
mRating = getActivity().getIntent().getStringExtra("rating");
mId = getActivity().getIntent().getIntExtra("id", 0);
mFavorited = getActivity().getIntent().getBooleanExtra("favorited", false);
}
private void getMovieYoutubeHandle(){
movieVideoUrl = "http://api.themoviedb.org/3/movie/"+mId+"/videos?api_key="+ BuildConfig.MY_MOVIE_DB_API_KEY;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(movieVideoUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String jsonData = response.body().string();
try {
movieKeys = Arrays.asList(getTrailerData(jsonData));
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mTrailerAdapter.setListData(movieKeys);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private String[] getTrailerData(String jsonData) throws JSONException {
JSONObject trailerDetails = new JSONObject(jsonData);
JSONArray results = trailerDetails.getJSONArray("results");
String[] keyArray = new String[results.length()];
for(int i = 0; i<results.length(); i++){
JSONObject keyResults = results.getJSONObject(i);
String youtubeKey = keyResults.getString("key");
keyArray[i] = youtubeKey;
}
return keyArray;
}
private void setClickItems() {
//initializes gridview for trailers and onItemClicks
mTrailerAdapter = new TrailerAdapter(getActivity(), R.layout.trailer_item, movieKeys);
mGridView.setAdapter(mTrailerAdapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String keyPosition = movieKeys.get(position).toString();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=" + keyPosition)));
}
});
//onClick launches the CommentsActivity
mCommentsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), CommentsActivity.class);
intent.putExtra("id", mId);
startActivity(intent);
}
});
//onClick for favorites
mFavoritesImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db = new DatabaseHelper(getActivity());
boolean isInserted = db.insertData(getActivity(), mId, mOriginalTitle, mPlot, mBackDrop, mPoster, mRating, mReleaseDate);
if (isInserted = true) {
mFavoritesImageView.setImageResource(android.R.drawable.star_big_on);
Log.v(DetailedMovie.class.getSimpleName(), "entry worked");
} else if (isInserted = false) {
Log.v(DetailedMovie.class.getSimpleName(), "entry failed");
}
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
ArrayList<String> toSave = movieKeys instanceof ArrayList ?
(ArrayList<String>) movieKeys : new ArrayList<>(movieKeys);
outState.putStringArrayList(MOVIEKEYS, toSave);
super.onSaveInstanceState(outState);
}
}
As well as the layout files.
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.rykuno.movietestapp.Activities.test">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_test"/>
</android.support.design.widget.CoordinatorLayout>
content_test.xml
<fragment android:id="#+id/fragment1"
android:name="com.rykuno.movietestapp.Activities.testFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_test"/>

make sure to use:
import android.support.v4.app.Fragment;
And also make sure that the Activity that is using the fragment(s) extends FragmentActivity instead of the regular Activity,
import android.support.v4.app.FragmentActivity;
to get the FragmentActivity class.

One think I found is add app:layout_behaviour to include tag and not inside content_test.xml
<include layout="#layout/content_test"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
And your project got many NPE unable to test more.

Related

My app crashed when clicking new dependency question. I don't know what is the error and how to solved it [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6969
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login/com.example.login.NavigationDrawer}: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.navigation.NavigationView.getHeaderView(int)' on a null object reference
at com.example.login.ui.questionnaire.QuestionnaireFragment.onCreateView(QuestionnaireFragment.java:80)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2777)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3020)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:295)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:274)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:784)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:867)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:54)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:48)
E/AndroidRuntime: at com.example.login.NavigationDrawer.onCreate(NavigationDrawer.java:42)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873
Java Code
package com.example.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.login.databinding.ActivityNavigationDrawerBinding;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
public class NavigationDrawer extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationDrawerBinding binding;
private String username;
private EditText etUsername;
Pref pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = new Pref(getApplicationContext());
//get username from login page
username = pref.getUsername();
//System.out.println("username in 2nd "+username);
binding = ActivityNavigationDrawerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(binding.navView);
setSupportActionBar(binding.appBarNavigationDrawer.toolbar);
binding.appBarNavigationDrawer.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_questionnaire, R.id.nav_submitsurvey, R.id.nav_responses, R.id.nav_imagecapture, R.id.nav_dashboard)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
//display welcome username
etUsername = findViewById(R.id.welcomeUsername);
etUsername.setText(username);
Button button_log_out = findViewById(R.id.button_log_out);
button_log_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutDialog();
}
});
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void logoutDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("LogOut Alert!");
alertDialog.setMessage("Are you sure want to LogOut this Application?");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pref.setLogin("no");
dialog.dismiss();
Intent intent = new Intent(NavigationDrawer.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
you have a NullPointerException. You should check whether the data you receive is full. For example
if(data != null){
.
.
.
...
}

Nullable problem with Intents with extras

I am learning how to develop for Android (and development in general). I am trying to create a Quiz App, so I can learn the basics.
While trying to use an Intent to go to another class with an extra variable on it, I found this problem (which I think is pretty usual): My app crashes when I go to the next Activity.
This is the code in the activity that gets the username ("usuario and nomeUsuario"):
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class HomeActivity extends AppCompatActivity {
public EditText usuario;
public EditText senha;
public Button botaoLogin;
public String nomeUsuario;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
botaoLogin = findViewById(R.id.botaoLogin);
senha = findViewById(R.id.senha);
usuario = findViewById(R.id.usuario);
nomeUsuario = usuario.getText().toString();
Log.d("nome de usuario", nomeUsuario);
botaoLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(HomeActivity.this, FirstQuestionActivity.class);
i.putExtra("nome", nomeUsuario);
startActivity(i);
}});
}
}
And this is the code on the SecondQuestionActivity:
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class FirstQuestionActivity extends AppCompatActivity {
public Button prox1;
public Button respUm1;
public Button respUm2;
public TextView texto1;
public int pontuacao = 0;
Intent i = getIntent();
String nome = i.getStringExtra("nome");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstquestion);
prox1 = findViewById(R.id.prox1);
respUm1 = findViewById(R.id.botao1a);
respUm2 = findViewById(R.id.botao1b);
texto1 = findViewById(R.id.texto1);
respUm1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta errada!");
respUm1.setEnabled(false);
respUm2.setEnabled(false);
prox1.setEnabled(true);
}});
respUm2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta certa!");
respUm2.setEnabled(false);
respUm1.setEnabled(false);
pontuacao += 1;
prox1.setEnabled(true);
}});
prox1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(FirstQuestionActivity.this, SecondQuestionActivity.class);
i.putExtra("pontos", pontuacao);
i.putExtra("nome", nome);
startActivity(i);
}
});
}
}
What is wrong with it? How can I prevent it?
Thank you!
P.S.: I am not used to forum or development in general, so I might have done this wrongly. I'm sorry.
Edit: Also, if anyone wanna take a look at the whole project, it's here.
Edit2: This is the Logcat output:
2020-11-13 21:05:18.531 7517-7517/com.isa56.quiz2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isa56.quiz2, PID: 7517
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.isa56.quiz2/com.isa56.quiz2.FirstQuestionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at com.isa56.quiz2.FirstQuestionActivity.<init>(FirstQuestionActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Keep these lines inside onCreate() method.
Intent i = getIntent();
String nome = i.getStringExtra("nome");

MainActivity cannot be cast to Fragment

Im working on this project. When i run the program it have some runtime errors and app does not appears in emulator. it show the message app stopped. I think there is a error in OnAttach method. I tried many ways to solve the issue but nothing works.I'm new to Android development please help me to solve the issue.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.workout, PID: 26059
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.workout/com.example.user.workout.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.user.workout.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java:6100)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5643) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.ClassCastException: com.example.user.workout.MainActivity cannot be cast to com.example.user.workout.WorkoutListFragment$WorkoutListListener
at com.example.user.workout.WorkoutListFragment.onAttach(WorkoutListFragment.java:53)
at android.support.v4.app.Fragment.onAttach(Fragment.java:1340)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1372)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1659)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1905)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3715)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:114)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:68)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
at com.example.user.workout.MainActivity.onCreate(MainActivity.java:14) 
at android.app.Activity.performCreate(Activity.java:6100) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5643) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
package com.example.user.workout;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class WorkoutListFragment extends ListFragment {
static interface WorkoutListListener{
void itemClicked(long id);
};
private WorkoutListListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String [] names = new String[Workout.workouts.length];
for(int i =0; i < names.length;i++)
{
names[i] = Workout.workouts[i].getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
inflater.getContext(), android.R.layout.simple_list_item_1,names);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.listener = (WorkoutListListener)activity;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
if(listener!=null)
{
listener.itemClicked(id);
}
}
}
package com.example.user.workout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void itemClicked(long id)
{
WorkoutDetialFragment detials = new WorkoutDetialFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
detials.setWorkoutId(id);
ft.replace(R.id.fragment_container,detials);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
Your activity should implement *WorkoutListListener* interface and override its method itemClicked().
public class MainActivity extends AppCompatActivity implements WorkoutListListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void itemClicked(long id){
// handle your click here
}
}

Frustrating crash when opening specific activity [duplicate]

This question already has answers here:
java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)
(16 answers)
Closed 5 years ago.
Getting a constant crash on the emulator when running a specific activity in my android project. The main activity of the project, as well as the splash screen run perfectly. The activity I am trying to run is quite complex, with information being read from a phpMyAdmin database.
I have read through the LogCat, but cannot seem to pinpoint the error that is causing the crash. Any nods in the right direction would be much appreciated. Don't have too much experience with this type of stuff.
Many thanks and apologies for the messy LogCat.
Maintenance Activity
package com.example.bs.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Maintenance extends AppCompatActivity {
private static final String PRODUCT_URL = "http://192.XXXXXXX/MyApi/api.php";
RecyclerView recyclerView;
ProductAdapter adapter;
List<Product> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintenance);
productList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
loadProducts ();
}
private void loadProducts () {
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products =new JSONArray(response);
for (int i = 0; i<products.length(); i++){
JSONObject productObject = products.getJSONObject(i);
int maintenance_id = productObject.getInt("maintenance_id");
String type = productObject.getString("type");
String property = productObject.getString("property");
String more_info = productObject.getString("more_info");
Double date = productObject.getDouble("date");
Product product = new Product(maintenance_id, type, property, more_info, date);
productList.add(product);
}
adapter = new ProductAdapter(Maintenance.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Maintenance.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
activity_maintenance
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.benchalmers.myapplication.Maintenance">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
LogCat
02-06 12:11:42.195 4155-4155/? I/zygote: Not late-enabling -Xcheck:jni (already on)
02-06 12:11:42.409 4155-4155/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
02-06 12:11:43.494 4155-4155/com.example.bs.myapplication I/InstantRun: starting instant run server: is main process
02-06 12:11:43.665 4155-4155/com.example.bs.myapplication D/AndroidRuntime: Shutting down VM
02-06 12:11:43.671 4155-4155/com.example.bs.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bs.myapplication, PID: 4155
java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface; in class Landroid/support/v4/content/res/ResourcesCompat; or its super classes (declaration of 'android.support.v4.content.res.ResourcesCompat' appears in /data/app/com.example.bs.myapplication-EpCz2N67lH5I_Aiqfiskfg==/split_lib_dependencies_apk.apk)
at android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
at android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
at android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
at android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:81)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:67)
at android.support.v7.widget.Toolbar.setTitle(Toolbar.java:753)
at android.support.v7.widget.ToolbarWidgetWrapper.setTitleInt(ToolbarWidgetWrapper.java:261)
at android.support.v7.widget.ToolbarWidgetWrapper.setWindowTitle(ToolbarWidgetWrapper.java:243)
at android.support.v7.widget.ActionBarOverlayLayout.setWindowTitle(ActionBarOverlayLayout.java:621)
at android.support.v7.app.AppCompatDelegateImplV9.onTitleChanged(AppCompatDelegateImplV9.java:631)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.bs.myapplication.Maintenance.onCreate(Maintenance.java:34)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Adapter Class
package com.example.benchalmers.myapplication;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context mCtx;
private List<Product> productList;
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.list_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.textViewType.setText(product.getType());
holder.textViewProperty.setText(product.getProperty());
holder.textViewMoreInfo.setText(String.valueOf(product.getMoreInfo()));
holder.textViewDate.setText(String.valueOf(product.getDate()));
//holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textViewType, textViewProperty, textViewMoreInfo, textViewDate;
public ProductViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textViewType = itemView.findViewById(R.id.textViewType);
textViewProperty = itemView.findViewById(R.id.textViewProperty);
textViewMoreInfo = itemView.findViewById(R.id.textViewMoreInfo);
textViewDate = itemView.findViewById(R.id.textViewDate);
}
}
}
You should migrate to 26.0.0 or above version for your support v7 library.
This is issue in appcompat library and mentioned here
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0
ResourcesCompat.getFont() throws exception
You should use the same version across all Android-related dependencies,its a best practice
You can check appcompat dependencies using
./gradlew :app:dependencyInsight --dependency com.android.support:appcompat --configuration debugCompileClasspath
It will give you info from where appcompat version is bumped to 27.0.2 from 26.1.0

java.lang.NullPointerException: uriString

I am a newbie and trying to create a video player .I am getting a null pointer exception and have read all the questions on SO and searched google related to it and read it. thumbpath doesn't seem null to me although it maybe the only reason of this exception. Can anyone help me with it ? Thanks
SDVideos.java
package com.example.dell_1.myapp3;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class SDVideos extends Activity
{
private Cursor videoCursor;
private int videoColumnIndex;
ListView videolist;
int count;
String thumbPath;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sdvideos);
initialization();
}
private void initialization()
{
System.gc();
String[] videoProjection = { MediaStore.Video.Media._ID,MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
videoCursor =getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,videoProjection, null, null, null);
count = videoCursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoListAdapter(this.getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private AdapterView.OnItemClickListener videogridlistener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoCursor.moveToPosition(position);
String filename = videoCursor.getString(videoColumnIndex);
Log.i("FileName: ", filename);
//Intent intent = new Intent(VideoActivity.this, ViewVideo.class);
//intent.putExtra("videofilename", filename);
//startActivity(intent);
}};
public class VideoListAdapter extends BaseAdapter
{
private Context vContext;
public VideoListAdapter(Context c)
{
vContext = c;
}
public int getCount()
{
return videoCursor.getCount();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View listItemRow;
listItemRow = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
TextView txtTitle = (TextView)listItemRow.findViewById(R.id.txtTitle);
TextView txtSize = (TextView)listItemRow.findViewById(R.id.txtSize);
ImageView thumbImage = (ImageView)listItemRow.findViewById(R.id.imgIcon);
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoCursor.moveToPosition(position);
txtTitle.setText(videoCursor.getString(videoColumnIndex));
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoCursor.moveToPosition(position);
txtSize.setText(" Size(KB):" + videoCursor.getString(videoColumnIndex));
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Cursor videoThumbnailCursor =getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID+ "=" + videoId, null, null);
if (videoThumbnailCursor.moveToFirst())
{
thumbPath = videoThumbnailCursor.getString(videoThumbnailCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.i("ThumbPath: ",thumbPath);
}
thumbImage.setImageURI(Uri.parse(thumbPath));
return listItemRow;
}
}
}
XML File :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/PhoneVideoList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"/>
</LinearLayout>
LOGCAT :
08-05 17:29:17.109 17708-17708/com.example.dell_1.myapp3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell_1.myapp3, PID: 17708
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.example.dell_1.myapp3.SDVideos$VideoListAdapter.getView(SDVideos.java:112)
at android.widget.AbsListView.obtainView(AbsListView.java:2367)
at android.widget.ListView.makeAndAddView(ListView.java:1972)
at android.widget.ListView.fillDown(ListView.java:704)
at android.widget.ListView.fillFromTop(ListView.java:765)
at android.widget.ListView.layoutChildren(ListView.java:1744)
at android.widget.AbsListView.onLayout(AbsListView.java:2161)
at android.view.View.layout(View.java:17523)
at android.view.ViewGroup.layout(ViewGroup.java:5618)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
at android.view.View.layout(View.java:17523)
at android.view.ViewGroup.layout(ViewGroup.java:5618)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:17523)
at android.view.ViewGroup.layout(ViewGroup.java:5618)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
at android.view.View.layout(View.java:17523)
at android.view.ViewGroup.layout(ViewGroup.java:5618)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:724)
at android.view.View.layout(View.java:17523)
at android.view.ViewGroup.layout(ViewGroup.java:5618)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2374)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2101)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1278)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6357)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I don´t see any reason why thumbPath needs to be an field of SDVideos, it is only used inside VideoListAdapter.getView.
Your updated code of moving thumbPath as a variable would be the following:
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Cursor videoThumbnailCursor =getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID+ "=" + videoId, null, null);
if (videoThumbnailCursor.moveToFirst())
{
String thumbPath = videoThumbnailCursor.getString(videoThumbnailCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.i("ThumbPath: ",thumbPath);
thumbImage.setImageURI(Uri.parse(thumbPath));
}
return listItemRow;
Since the thumbPath will only be populated if the cursor have any data, you can move the setImageURI to inside your if.
This code will solve the NullPointerException, but probably you will not see any image in the thumbImage.
Now you need to find why your videoThumbnailCursor is returning no data. After you find why, please update your question.

Categories