last night I was working on my app, initially I already reached my 64k limit so have had multidex for sometime now, sometimes it does fail and gives me a ClassNotFoundException but all I do is recompile my code and it works, if it fails I restart my computer but this time it is a different case, MultiDex seems to be excluding one of my classes which is funny because it was working until it suddenly stop, what it is doing it is excluding my EnhancedGallery.class which am using as my start activity, if I change to some other activity as start activity in manifest the App works until I try to run EnhancedGallery below are my Gradle Configurations
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "aubry.chromio.com.dressup"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
sourceSets { main { res.srcDirs = ['src/main/res', ' src/main/res/layout_land'] } }
dexOptions {
preDexLibraries = false
javaMaxHeapSize "2g"
}
afterEvaluate {
tasks.matching {
it.name.startsWith('dex')
}.each { dx ->
if (dx.additionalParameters == null) {
dx.additionalParameters = []
}
dx.additionalParameters += '--multi-dex'
// dx.additionalParameters += "--main-dex- list=$projectDir/dexFiles".toString()
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile('com.twitter.sdk.android:twitter:1.6.0#aar') {
transitive = true;
}
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.commit451:PhotoView:1.2.4'
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.wang.avi:library:1.0.0'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.google.android.gms:play-services-gcm:8.1.0'
compile 'com.facebook.android:facebook-android-sdk:4.5.0'
compile 'com.commonsware.cwac:camera:0.6.+'
compile project(':android-support-multidex')
compile 'com.android.support:support-v13:23.1.0'
compile 'com.android.support:palette-v7:23.1.0'
compile 'com.android.support:cardview-v7:23.1.0'
compile 'com.github.ozodrukh:CircularReveal:1.1.0'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
}
My App.class where I give gradle my app Context
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
public class App extends Application {
private static App instance;
#Override public void onCreate() {
super.onCreate();
instance = this;
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
public static App get() {
return instance;
}
}
My Middle level Gradle file:
configurations.create("default")
artifacts.add("default", file('android-support-multidex.jar'))
And My top Level Gradle File:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// The Fabric Gradle plugin uses an open ended version to
// react quickly to Android tooling updates
classpath 'io.fabric.tools:gradle:1.+'
}
}
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.fabric.io/public'
}
maven {
url "https://s3.amazonaws.com/repo.commonsware.com"
}
maven {
url 'http://dl.bintray.com/amulyakhare/maven'
}
maven {
url "https://jitpack.io"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
My error Report:
1-14 09:25:49.430 30154-30154/aubry.chromio.com.dressup E/dalvikvm:
Could not find class 'android.support.v4.app.
NotificationCompat$Builder', referenced from method
com.google.android.gms.common.GooglePlayServicesUtil.zza
11-14 09:25:49.431 30154-30154/aubry.chromio.com.dressup
E/dalvikvm: Could not find class 'android.support.v4.app.FragmentActivity',
referenced from method
com.google.android.gms.common.GooglePlayServicesUtil.zza
11-14 09:25:49.432 30154-30154/aubry.chromio.com.dressup E/dalvikvm: Could not
find class 'android.support.v4.app.FragmentActivity', referenced from method
com.google.android.gms.common.GooglePlayServicesUtil.zza
11-14 09:25:49.442 30154-30154/aubry.chromio.com.dressup E/dalvikvm: Could not
find class 'android.app.AppOpsManager', referenced from method
com.google.android.gms.common.GooglePlayServicesUtil.zzb
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
FATAL EXCEPTION: main
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{aubry.chromio.com.dressup/aubry.chromio.com.dressup.activities.Enhan cedGallery}: java.lang.ClassNotFoundException: Didn't find class
"aubry.chromio.com.dressup.activities.EnhancedGallery" on path:
DexPathList[[zip file "/data/app/aubry.chromio.com.dressup-
1.apk"],nativeLibraryDirectories=[/data/app-lib/aubry.chromio.com.dressup-1,
/vendor/lib, /system/lib]]
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.app.ActivityThread.access$600(ActivityThread.java:162)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.os.Handler.dispatchMessage(Handler.java:107)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.os.Looper.loop(Looper.java:194)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at android.app.ActivityThread.main(ActivityThread.java:5371)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at java.lang.reflect.Method.invokeNative(Native Method)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at java.lang.reflect.Method.invoke(Method.java:525)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at dalvik.system.NativeStart.main(Native Method)
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
Caused by: java.lang.ClassNotFoundException: Didn't find class
"aubry.chromio.com.dressup.activities.EnhancedGallery" on path:
DexPathList[[zip file "/data/app/aubry.chromio.com.dressup-
1.apk"],nativeLibraryDirectories=[/data/app-lib/aubry.chromio.com.dressup-1,
/vendor/lib, /system/lib]]
11-14 09:25:49.518 30154-30154/aubry.chromio.com.dressup E/AndroidRuntime:
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
And lastly my EnhancedGallery Class
import android.content.Context;
import android.database.Cursor;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import java.util.HashSet;
import java.util.Set;
import #####.chromio.com.#####.R;
import #####.chromio.com.#####.polypicker.model.Image;
import #####.chromio.com.#####.polypicker.utils.ImageInternalFetcher;
public class EnhancedGallery extends AppCompatActivity implements
View.OnScrollChangeListener{
public ImageInternalFetcher mImageFetcher;
private ImageGalleryAdapter mGalleryAdapter;
private Set<Image> mSelectedImages;
Display display;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enhanced_gallery);
toolbar = (Toolbar) findViewById(R.id.toolbar_transparent);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mGalleryAdapter = new ImageGalleryAdapter(this);
GridView galleryGridView = (GridView)findViewById(R.id.pp__gallery_grid);
mSelectedImages = new HashSet<Image>();
mImageFetcher = new ImageInternalFetcher(this, 500);
Cursor imageCursor = null;
try {
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION};
final String orderBy = MediaStore.Images.Media.DATE_ADDED + " DESC";
imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
while (imageCursor.moveToNext()) {
Uri uri = Uri.parse(imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
int orientation = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION));
mGalleryAdapter.add(new Image(uri, orientation));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(imageCursor != null && !imageCursor.isClosed()) {
imageCursor.close();
}
}
galleryGridView.setAdapter(mGalleryAdapter);
galleryGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Image image = mGalleryAdapter.getItem(i);
if (!containsImage(image)) {
//addImage(image);
} else {
//removeImage(image);
}
// refresh the view to
// mGalleryAdapter.getView(i, view, adapterView);
mGalleryAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onScrollChange(View view, int i, int i1, int i2, int i3) {
toolbar.setAlpha(getAlphaforActionBar(view.getScrollY()));
}
private int getAlphaforActionBar(int scrollY) {
int minDist = 0,maxDist = 650;
if(scrollY>maxDist){
return 255;
}
else if(scrollY<minDist){
return 0;
}
else {
int alpha = 0;
alpha = (int) ((255.0/maxDist)*scrollY);
return alpha;
}
}
class ViewHolder {
ImageView mThumbnail;
// This is like storing too much data in memory.
// find a better way to handle this
Image mImage;
}
public class ImageGalleryAdapter extends ArrayAdapter<Image> {
public ImageGalleryAdapter(Context context) {
super(context, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.enhanced_gallery_adapter, null);
holder = new ViewHolder();
holder.mThumbnail = (ImageView) convertView.findViewById(R.id.pp__thumbnail_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Image image = getItem(position);
boolean isSelected = containsImage(image);
convertView.setForeground(isSelected ? getResources().getDrawable(R.drawable.gallery_photo_selected) : null);
if (holder.mImage == null || !holder.mImage.equals(image)) {
mImageFetcher.loadImage(image.mUri, holder.mThumbnail);
holder.mImage = image;
}
return convertView;
}
}
public boolean containsImage(Image image) {
return mSelectedImages.contains(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
It has been a hustle, I finally fix it, or should I say found a way of bypassing it, since other classes were working I just created another class and copy pasted all my lines of code to the new class and it worked, I do not know the attachment between MultiDex and my EnhancedGallery class yet.
Related
I'm following this tutorial from CodeLab Google https://codelabs.developers.google.com/codelabs/android-training-livedata-viewmodel/index.html?index=..%2F..android-training
However, after following all the details, at the end I got this error:
2019-10-04 07:05:11.310 10476-10476/com.example.roomwordssample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.roomwordssample, PID: 10476
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roomwordssample/com.example.roomwordssample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.roomwordssample.WordViewModel
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: java.lang.RuntimeException: Cannot create an instance of class com.example.roomwordssample.WordViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:208)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36)
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)
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.roomwordssample.WordRoomDatabase. WordRoomDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:94)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:667)
at com.example.roomwordssample.WordRoomDatabase.getDatabase(WordRoomDatabase.java:26)
at com.example.roomwordssample.WordRepository.<init>(WordRepository.java:14)
at com.example.roomwordssample.WordViewModel.<init>(WordViewModel.java:16)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36)
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)
I've tried to look for solutions from these links:
https://stackoverflow.com/questions/49224539/roomdatabase-impl-does-not-exist
https://stackoverflow.com/questions/47274677/room-cannot-find-implementation?noredirect=1&lq=1
https://stackoverflow.com/questions/55679940/database-impl-doesnt-exist-android-app-with-room
https://stackoverflow.com/questions/50453822/room-cannot-find-implementation-db-db-impl-does-not-exist
But none is working because I'm using Java not Kotlin. Many of the solutions above suggested change the annotationProcessor to kapt then add apply plugin: 'kotlin-kapt' but it'll only give another error
build.grade (Module:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.roomwordssample"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.room:room-runtime:2.0.0'
annotationProcessor 'androidx.room:room-compiler:2.0.0'
androidTestImplementation 'androidx.room:room-testing:2.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.0.0'
}
WordRoomDatabase.java
package com.example.roomwordssample;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
public abstract class WordRoomDatabase extends RoomDatabase {
public abstract WordDao wordDao();
private static WordRoomDatabase INSTANCE;
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (WordRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
// Wipes and rebuilds instead of migrating
// if no Migration object.
// Migration is not part of this practical.
.fallbackToDestructiveMigration()
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){
#Override
public void onOpen (#NonNull SupportSQLiteDatabase db){
super.onOpen(db);
new PopulateDbAsync(INSTANCE).execute();
}
};
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private final WordDao mDao;
String[] words = {"dolphin", "crocodile", "cobra"};
PopulateDbAsync(WordRoomDatabase db) {
mDao = db.wordDao();
}
#Override
protected Void doInBackground(final Void... params) {
// Start the app with a clean database every time.
// Not needed if you only populate the database
// when it is first created
mDao.deleteAll();
for (int i = 0; i <= words.length - 1; i++) {
Word word = new Word(words[i]);
mDao.insert(word);
}
return null;
}
}
}
WordViewModel.java
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
public WordViewModel (Application application) {
super(application);
mRepository = new WordRepository(application);
mAllWords = mRepository.getAllWords();
}
LiveData<List<Word>> getAllWords() { return mAllWords; }
public void insert(Word word) { mRepository.insert(word); }
}
MainActivity.java
package com.example.roomwordssample;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private WordViewModel mWordViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final WordListAdapter adapter = new WordListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
#Override
public void onChanged(#Nullable final List<Word> words) {
// Update the cached copy of the words in the adapter.
adapter.setWords(words);
}
});
FloatingActionButton fab = findViewById(R.id.fab);
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();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I missed the #Database annotation right before the abstract class WordRoomDatabase. After adding #Database(entities = {Word.class}, version = 1, exportSchema = false), everything works fine.
In my case, annotations were fine but I had issue with Gradle dependencies. So make sure that you have at lease these too:
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
And also you should have id 'kotlin-kapt' in your plugins brackets.
my app does not have any errors when it builds, however, it stops working when I run it on my phone, and when I open the app it stopped working and then I decided to run it in the debug and see the errors that have in it through logcat
My build.gradle
apply plugin: 'com.android.application'
android {
configurations.all {exclude group: 'com.android.support', module: 'support-v4'}
compileSdkVersion 28
defaultConfig {
applicationId "tdl.com.dindim"
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true
versionCode 2
versionName "1.1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
multiDexEnabled true
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:design:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.adefruandta.spinningwheel:spinningwheel:0.1.0'
implementation 'com.google.firebase:firebase-core:10.0.1'
implementation 'com.google.firebase:firebase-database:10.0.1'
implementation 'org.immutables:gson:2.6.1'
implementation 'com.google.android.gms:play-services:10.0.1'
implementation 'com.google.android.gms:play-services-maps:10.0.1'
implementation 'com.google.android.gms:play-services-ads:10.0.1'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'gun0912.ted:tedpermission:2.1.0'
}
apply plugin: 'com.google.gms.google-services'
Logcat error (I just took the words that were in red)
2019-07-19 03:33:43.960 7572-7572/? E/FirebaseInstanceId: binding to the service failed
at android.os.HandlerThread.run(HandlerThread.java:65)
2019-07-19 04:23:16.863 15686-15704/? E/DIAL:SsdpWriter: Error sending M-SEARCH request
java.net.SocketException: Socket is closed
at java.net.DatagramSocket.send(DatagramSocket.java:686)
at com.google.android.music.dial.SsdpWriter.sendSearch(SsdpWriter.java:67)
at com.google.android.music.dial.SsdpScanner.run(SsdpScanner.java:45)
at com.google.android.music.utils.async.TraceableRunnable.runLogged(TraceableRunnable.java:21)
at com.google.android.music.utils.async.LoggedRunnable.run(LoggedRunnable.java:30)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at com.google.android.music.utils.LoggableHandler.dispatchMessage(LoggableHandler.java:74)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)
Debug error (I just took the words that were in red)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tdl.com.dindim, PID: 11596
java.lang.RuntimeException: Unable to start activity ComponentInfo{tdl.com.dindim/com.gun0912.tedpermission.TedPermissionActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.Activity.onCreate(Activity.java:991)
at android.support.v4.app.SupportActivity.onCreate(ComponentActivity.java:75)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:335)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.gun0912.tedpermission.TedPermissionActivity.onCreate(TedPermissionActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{tdl.com.dindim/com.gun0912.tedpermission.TedPermissionActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.Activity.onCreate(Activity.java:991)
at android.support.v4.app.SupportActivity.onCreate(ComponentActivity.java:75)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:335)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.gun0912.tedpermission.TedPermissionActivity.onCreate(TedPermissionActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
E/FirebaseCrash: Unable to parse Json response string to get message: No value for crashes
My MainActivity
package tdl.com.dindim.activities;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.util.List;
import tdl.com.dindim.R;
import tdl.com.dindim.managers.SpinManager;
import tdl.com.dindim.managers.WithdrawManager;
import tdl.com.dindim.models.Score;
import tdl.com.dindim.models.Withdraw;
import tdl.com.dindim.utils.ApplicationMode;
import tdl.com.dindim.utils.ConnectionChecker;
import tdl.com.dindim.utils.SharedPreferenceValue;
public class MainActivity extends AppCompatActivity implements WithdrawManager.WithdrawFeedbackListener {
private TextView tvTotalEarn, tvLastWithdraw;
private AdView adView, adView2, adView3;
private InterstitialAd mInterstitialAd;
private WithdrawManager withdrawManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
}
private void initUI() {
tvTotalEarn = findViewById(R.id.tvTotalEarn);
tvLastWithdraw = findViewById(R.id.tvLastWithdraw);
adView = findViewById(R.id.adViewD);
adView2 = findViewById(R.id.adView2D);
adView3 = findViewById(R.id.adView3D);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.dashboard_interstitial_ads));
loadAds();
showInterstitialAdds();
if (ConnectionChecker.isOnline(MainActivity.this)) {
new SpinManager(MainActivity.this, false, new SpinManager.SpinFeedbackListener() {
#Override
public void pointSaveSuccess() {
}
#Override
public void pointSaveFailed() {
}
#Override
public void noLastPointFound() {
tvTotalEarn.setText("My Total Earn Points: 0");
}
#Override
public void userLastScore(Score score) {
tvTotalEarn.setText("My Total Earn Points: " + score.getPoints());
}
#Override
public void updateScoreSuccess() {
}
#Override
public void updateScoreFailed() {
}
#Override
public void noScoreForTodayUpdateScoreOnly(Score score) {
tvTotalEarn.setText("My Total Earn Points: " + score.getPoints());
}
}).getUserLastScore(SharedPreferenceValue.getLoggedinUser(MainActivity.this));
withdrawManager = new WithdrawManager(MainActivity.this, false, this);
withdrawManager.getUserLastWithdraw(SharedPreferenceValue.getLoggedinUser(MainActivity.this));
} else {
Toast.makeText(this, "No internet . try to connect with internet", Toast.LENGTH_SHORT).show();
}
}
private void loadAds() {
// ads:adUnitId="ca-app-pub-4836336224499913/6703144349"></com.google.android.gms.ads.AdView>
//mAdViewTop.setAdUnitId("ca-app-pub-4836336224499913/6703144349");
if (ApplicationMode.devMode) {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView.loadAd(adRequest);
} else {
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView.loadAd(adRequest);
}
if (ApplicationMode.devMode) {
AdRequest adRequest2 = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView2.loadAd(adRequest2);
} else {
AdRequest adRequest2 = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView2.loadAd(adRequest2);
}
if (ApplicationMode.devMode) {
AdRequest adRequest3 = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView3.loadAd(adRequest3);
} else {
AdRequest adRequest3 = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView3.loadAd(adRequest3);
}
}
private void showInterstitialAdds() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
//mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showAdsFinal();
}
}, 5000);
}
void showAdsFinal() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
#Override
public void withdrawSaveSuccess() {
}
#Override
public void withdrawSaveFailed() {
}
#Override
public void noLastWithdrawFound() {
tvLastWithdraw.setText("My Last Withdraw: 0");
}
#Override
public void userLastWithdraw(Withdraw withdraw) {
tvLastWithdraw.setText("My Last Withdraw: " + withdraw.getWithdrawPoints());
}
#Override
public void withDrawRequests(List<Withdraw> withdrawList) {
}
#Override
public void noRequestsAvailable() {
}
}
are u using Android 8.0?
Try delete android:screenOrientation='portrait' in manifest
In style, <item name="android:windowIsTranslucent">true</item> set True to false
If not work, test with another phone
I am Trying to Create a RecyclerView with PopUp Menu but whenever I try to access popup menu it crushes and says : Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 1: TypedValue{t=0x2/d=0x7f01005e a=-1}
My menu.xml is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menu1"
android:title="Menu 1" />
<item
android:id="#+id/menu2"
android:title="Menu 2" />
<item
android:id="#+id/menu3"
android:title="Menu 3" />
</menu>
style.xml:
<resources>
<!-- Base application theme. -->
<!-- your theme inherits from the material theme -->
<style name="AppTheme" parent="android:Theme.Material">
<!-- theme customizations -->
<!-- Customize your theme here. -->
<item name="colorPrimary">#000</item>
<item name="colorPrimaryDark">#c21d1111</item>
<item name="colorAccent">#c6897929</item>
</style>
</resources>
Adapter Class:
/**
* Created by User on 21-Apr-17.
*/
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<MyList> list;
private Context mCtx;
public CustomAdapter(List<MyList> list, Context mCtx) {
this.list = list;
this.mCtx = mCtx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, int position) {
MyList myList = list.get(position);
holder.textViewHead.setText(myList.getHead());
holder.textViewDesc.setText(myList.getDesc());
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.option_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
break;
case R.id.menu2:
//handle menu2 click
break;
case R.id.menu3:
//handle menu3 click
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewDesc;
public TextView buttonViewOption;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
}
}
}
Log:
04-20 17:36:06.311 10660-10660/com.hridoy.user.ieee_aust D/MediaPlayer: setSubtitleAnchor in MediaPlayer
04-20 17:36:32.171 10660-10675/com.hridoy.user.ieee_aust E/EGL_emulation: tid 10675: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
04-20 17:36:32.171 10660-10675/com.hridoy.user.ieee_aust W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf13f21e0, error=EGL_BAD_MATCH
04-20 17:36:33.147 10660-10660/com.hridoy.user.ieee_aust D/ViewRootImpl[MyOtherActivity]: changeCanvasOpacity: opaque=true
04-20 17:36:33.944 10660-10660/com.hridoy.user.ieee_aust D/ViewRootImpl[MyOtherActivity]: changeCanvasOpacity: opaque=false
04-20 17:36:49.733 10660-10660/com.hridoy.user.ieee_aust D/AndroidRuntime: Shutting down VM
04-20 17:36:49.733 10660-10660/com.hridoy.user.ieee_aust E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hridoy.user.ieee_aust, PID: 10660
android.view.InflateException: Binary XML file line #17: Failed to resolve attribute at index 1: TypedValue{t=0x2/d=0x7f01005e a=-1}
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 1: TypedValue{t=0x2/d=0x7f01005e a=-1}
at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:761)
at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:7035)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:7216)
at android.widget.FrameLayout$LayoutParams.<init>(FrameLayout.java:439)
at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:370)
at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:369)
at android.view.LayoutInflater.inflate(LayoutInflater.java:505)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:93)
at android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
at android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
at android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
at android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
at android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
at android.support.v7.view.menu.MenuPopupHelper.show(MenuPopupHelper.java:141)
at android.support.v7.widget.PopupMenu.show(PopupMenu.java:233)
at com.hridoy.user.ieee_aust.CustomAdapter$1.onClick(CustomAdapter.java:71)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
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:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.hridoy.user.ieee_aust"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.0'
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:+'
compile 'com.android.support:recyclerview-v7:+'
compile 'com.android.support:design:22.2.0'
testCompile 'junit:junit:4.12'
}
I solved this problem by pass instance the activity instead of the context to PopupMenu();
I'm trying to implement ActionBarSherlock swipe menu as I like how this animation slides over the slide menu. Unfortunately I keep getting this error and haven't been able to solve it.
This guy is getting the same error but none of the answers on this solves my problem. Android: java.land.NoSuchFieldError after update to SDK 23
Here is my Gradle file.
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.myegotest.ego_17012016"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
//compile 'com.android.support:appcompat-v7:23.1.1'
//compile 'com.android.support:design:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.facebook.android:facebook-android-sdk:4.9.0'
compile('com.twitter.sdk.android:twitter:1.12.0#aar') {
transitive = true;
}
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
//compile 'com.android.support:multidex:1.0.1'
compile "com.android.support:support-v4:23.1.1"
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.google.android.gms:play-services-auth:8.3.0'
compile project(':SlidingMenuLib-master')
}
Here is the activity trying to implement the SlidingMenu.
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Toast;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.myegotest.ego_17012016.ProfileFragments.InterestsPageFragment;
import com.myegotest.ego_17012016.ProfileFragments.ProfilePageFragment;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.MalformedInputException;
import Library.LocalDataBase;
import Library.User;
public class MainActivity extends SlidingFragmentActivity {
//View item variables
ViewPager mPager;
//Other variables
private String firstName;
private String lastName;
private String username;
String profilepic;
LocalDataBase mLocalDataBase;
//The pager adapter, which provides the pages to the view pager widget.
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
MainActivity.this.finish();
}
setBehindContentView(R.layout.menu_frame);
//Get loggedIn user values from the LocalDataBase .
firstName = user.mFirstName;
lastName = user.mLastName;
username = user.mUsername;
//Capitalize 1st letter of the following variable.
firstName = capitalizeFirstCharacter(firstName);
lastName = capitalizeFirstCharacter(lastName);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.myViewPager);
mPager.setPageTransformer(true, new ZoomOutPageTransformer());
netAsync();
}
//Method to capitalize 1st letter of the String thats using this method.
private String capitalizeFirstCharacter(String textInput){
String input = textInput.toLowerCase();
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
return output;
}
/**
* A simple pager adapter that represents 2 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 1:
return new InterestsPageFragment();
default: break;
}
return ProfilePageFragment.newInstance(firstName, lastName, profilepic);
}
#Override
public int getCount() {
return 2;
}
}
//Animation for swiping between page views
public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.85f;
private static final float MIN_ALPHA = 0.5f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
view.setTranslationX(horzMargin - vertMargin / 2);
} else {
view.setTranslationX(-horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
// Fade the page relative to its size.
view.setAlpha(MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}
Finally, here is the error I am getting.
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.myegotest.ego_17012016, PID: 8545
E/AndroidRuntime: java.lang.NoSuchFieldError: android.support.v4.app.Watson.mFragments
E/AndroidRuntime: at android.support.v4.app.Watson.onCreatePanelMenu(Watson.java:50)
E/AndroidRuntime: at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:560)
E/AndroidRuntime: at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchCreateOptionsMenu(ActionBarSherlockNative.java:64)
E/AndroidRuntime: at com.actionbarsherlock.app.SherlockFragmentActivity.onCreatePanelMenu(SherlockFragmentActivity.java:164)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:486)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:855)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:271)
E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:603)
E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:572)
E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:157)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5293)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 8545 SIG: 9
I was able to solve the problem by removing the facebook sdk from my gradle file. Since i need the facebook sdk, i was able to get around this by making MainActivity just extend FragmentActivity instead of SlidingFragmentActivty. I made this inner class inside of MainActivty to extend SlidingActivity, that way i can still use the methods i need.
private class SlidingMenuClass extends SlidingActivity {
private SlidingMenu sm;
public SlidingMenuClass(Context ctx){
sm = new SlidingMenu(ctx);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sm = getSlidingMenu();
sm.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
sm.setShadowWidthRes(R.dimen.shadow_width);
//sm.setShadowDrawable(R.drawable.shadow);
sm.setFadeDegree(1f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindOffsetRes(R.dimen.behindoffsetRes);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception