LogCat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at ye.ansarallah.al_ansar.HomeActivity.onCreate(HomeActivity.java:37)
HomeActivity:
public class HomeActivity extends AppCompatActivity {
Integer[] MyImageArray = {
R.drawable.w1, R.drawable.w2, R.drawable.w3
};
GridView MyGridView;
ImageView MyCurrentWallpaper;
Drawable MyDrawable;
WallpaperManager MyWallmanger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyGridView = findViewById(R.id.mygridview);
MyCurrentWallpaper = findViewById(R.id.myImageView);
MyGridView.setAdapter(new ImageAdapter(getApplicationContext()));
UpdateMyWallpaper();
}
private void UpdateMyWallpaper() {
MyWallmanger = WallpaperManager.getInstance(getApplicationContext());
MyDrawable = MyWallmanger.getDrawable();
MyCurrentWallpaper.setImageDrawable(MyDrawable);
}
public class ImageAdapter extends BaseAdapter {
Context myContext;
ImageAdapter(Context applicationContext) {
myContext = applicationContext;
}
@Override
public int getCount() {
return MyImageArray.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ImageView GridImageView;
if (view == null) {
GridImageView = new ImageView(myContext);
GridImageView.setLayoutParams(new GridView.LayoutParams(512, 512));
GridImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
GridImageView = (ImageView) view;
}
GridImageView.setImageResource(MyImageArray[i]);
GridImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
MyWallmanger.setResource(MyImageArray[i]);
} catch (IOException e) {
e.printStackTrace();
}
UpdateMyWallpaper();
}
});
return GridImageView;
}
}
}
activity_home.XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HomeActivity">
<ImageView
android:id="@+id/myImageView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="centerCrop"
android:src="@drawable/w1" />
<GridView
android:id="@+id/mygridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidth"
android:verticalSpacing="1dp" />
</LinearLayout>