Google Places Autocomplete Api in Tab layout Fragment - android

I'm trying to use Google Places Autocomplete API in a tab layout fragment. But I'm not able to because of this. What can I do?
The error appearing is:
Error:(51, 54) error: incompatible types: Fragment cannot be converted to PlaceAutocompleteFragment
The XML file is:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/place_autocomplete_fragment"
android:name=
"com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
The Fragment Code:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.Places;
import
com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import
com.google.android.gms.location.places.ui.PlaceSelectionListener;
import butterknife.ButterKnife;
public class LocationSearchFragment extends Fragment implements
GoogleApiClient.OnConnectionFailedListener {
ViewGroup rootView;
String TAG="Location Search:";
private FragmentActivity myContext;
private Context context; private GoogleApiClient mGoogleApiClient;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater
.inflate(R.layout.place_search, container, false);
mGoogleApiClient = new GoogleApiClient
.Builder(rootView.getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
PlaceAutocompleteFragment places= (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
places.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Toast.makeText(getContext(),place.getName(),Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Status status) {
Toast.makeText(getContext(),status.toString(),Toast.LENGTH_SHORT).show();
}
});
ButterKnife.bind(this, rootView);
return rootView;
}
public void cleanUp(){
getFragmentManager().beginTransaction().remove().commit();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// An unresolvable error has occurred and a connection to Google APIs
// could not be established. Display an error message, or handle
// the failure silently
// ...
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
}
The whole log:
05-07 10:38:23.452 27969-27969/com.example.apple.project2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apple.project2, PID: 27969
android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
at com.example.apple.project2.LocationSearchFragment.onCreateView(LocationSearchFragment.java:38)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:753)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:273)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:794)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.example.apple.project2.LocationSearchFragment.onCreateView(LocationSearchFragment.java:38) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299) 
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) 
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:753) 
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363) 
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149) 
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103) 
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984) 
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626) 
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1116) 
at android.support.v4.view.ViewPager$3.run(ViewPager.java:273) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) 
at android.view.Choreographer.doCallbacks(Choreographer.java:686) 
at android.view.Choreographer.doFrame(Choreographer.java:619) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7331) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f0d0165, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2227)
at android.app.FragmentController.onCreateView(FragmentController.java:99)
at android.app.Activity.onCreateView(Activity.java:6085)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:847) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:527) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.example.apple.project2.LocationSearchFragment.onCreateView(LocationSearchFragment.java:38) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299) 
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) 
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:753) 
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363) 
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149) 
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103) 
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984) 
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626) 
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268) 
at android.support.v4.view.ViewPager.populate(ViewPager.java:1116) 
at android.support.v4.view.ViewPager$3.run(ViewPager.java:273) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) 
at android.view.Choreographer.doCallbacks(Choreographer.java:686) 
at android.view.Choreographer.doFrame(Choreographer.java:619) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7331) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
05-07 10:38:25.192 27969-27969/com.example.apple.project2 I/Process: Sending signal. PID: 27969 SIG: 9

First error, you import the wrong Fragment.
import android.support.v4.app.Fragment
Instead of
import android.app.Fragment
Second error, you're making an unnecessary xml file and putting an additional Fragment within another Fragment.
Try to start over with this
public class LocationSearchFragment extends PlaceAutocompleteFragment implements
GoogleApiClient.OnConnectionFailedListener,
PlaceSelectionListener {
public static final String TAG="Location Search:";
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setOnPlaceSelectedListener(this);
}
#Override
public void onPlaceSelected(Place place) {
Toast.makeText(getActivity(),
place.getName(),Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Status status) {
Toast.makeText(getActivity() ,
status.toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onAttach(Activity activity) {
mGoogleApiClient = new GoogleApiClient
.Builder(activity)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
}

Related

how to resolve app has stopped in android studio simulator (fragment pager adapter)

I am a beginner in android development and I have encountered some difficulty in running my app in the simulator. I am following chapter 12 of the head first textbook to design an app with tab navigation. It has four fragments and I am using the fragment pager adapter to navigate through the app. When I run the app in the simulator it is crashed with the error message "app has stopped working". My code for the main activity is as follows:
package com.hfad.bitsandpizzas;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class MainActivity extends AppCompatActivity {
private ShareActionProvider shareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SectionsPagerAdapter pagerAdapter =
new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
shareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
setShareActionIntent("Want to join me for pizza?");
return super.onCreateOptionsMenu(menu);
}
private void setShareActionIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
shareActionProvider.setShareIntent(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, OrderActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TopFragment();
case 1:
return new PizzaFragment();
case 2:
return new PastaFragment();
case 3:
return new StoresFragment();
}
return null;
}
}
}
the error message from the logcat is this
2020-06-04 15:10:08.263 11458-11458/com.hfad.bitsandpizzas E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hfad.bitsandpizzas, PID: 11458
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hfad.bitsandpizzas/com.hfad.bitsandpizzas.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.v4.view.ViewPager
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.v4.view.ViewPager
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class android.support.v4.view.ViewPager
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.view.ViewPager" on path: DexPathList[[zip file "/data/app/com.hfad.bitsandpizzas-1/base.apk"],nativeLibraryDirectories=[/data/app/com.hfad.bitsandpizzas-1/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:609)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.hfad.bitsandpizzas.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
You are useing the Androidx support Library ,but in your xml layout ,you are useing the android.support.v4.view.ViewPager , you must change the ViewPager to Androidx support Library,use: androidx.viewpager.widget.ViewPager instead.

Can't get an INSTANCE of a DB using the AndroidViewModel superclass and Room

In my MVVM app, I am extending AndroidViewModel and through a Repository class, I am trying to get an instance of a DB (in a separate abstract class that extends the RoomDatabase superclass). I call the ViewModel from the MainActivity class by the ViewModelProviders method. I get the following error:
Here is the whole stack trace of the exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.roomlistingapllicate, PID: 31766
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roomlistingapllicate/com.example.roomlistingapllicate.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.roomlistingapllicate.NOtesViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.roomlistingapllicate.NOtesViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:238)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6309)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
at android.app.ActivityThread.access$900(ActivityThread.java:175) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5728) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19) 
at android.app.Activity.performCreate(Activity.java:6309) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
at android.app.ActivityThread.access$900(ActivityThread.java:175) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5728) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.roomlistingapllicate.NotesDatabase. NotesDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:94)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:851)
at com.example.roomlistingapllicate.NotesDatabase.getInstance(NotesDatabase.java:23)
at com.example.roomlistingapllicate.NoteRepository.<init>(NoteRepository.java:15)
at com.example.roomlistingapllicate.NOtesViewModel.<init>(NOtesViewModel.java:15)
at java.lang.reflect.Constructor.newInstance(Native Method) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
at com.example.roomlistingapllicate.MainActivity.onCreate(MainActivity.java:19) 
at android.app.Activity.performCreate(Activity.java:6309) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
at android.app.ActivityThread.access$900(ActivityThread.java:175) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5728) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
I am working on the AndroidX arch. Here are some parts of the code I think the issue hides in:
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private NOtesViewModel nOtesViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nOtesViewModel = ViewModelProviders.of(this).get(NOtesViewModel.class);
}
}
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class NOtesViewModel extends AndroidViewModel {
private NoteRepository noteRepository;
private LiveData<List<Note>> allNotes;
public NOtesViewModel(#NonNull Application application) {
super(application);
noteRepository = new NoteRepository(application);
allNotes = noteRepository.getAllNotes();
}
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
public class NoteRepository {
private NoteDAO noteDAO;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application) {
NotesDatabase notesDatabase = NotesDatabase.getInstance(application.getApplicationContext());
noteDAO = notesDatabase.noteDAO();
allNotes = noteDAO.getAllNotes();
}
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
#Database(entities = {Note.class}, version = 1)
public abstract class NotesDatabase extends RoomDatabase {
private static NotesDatabase instance;
public abstract NoteDAO noteDAO();
public static synchronized NotesDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(), NotesDatabase.class,
"note_database").fallbackToDestructiveMigration()
.addCallback(roomCallback)
.build();
}
return instance;
}
The stacktrace says you're getting this error because Room can not find an implementation of your Notes Database abstract class.
Please make sure you have added the room annotation processor dependency in your app's build.gradle file.
annotationProcessor "androidx.room:room-compiler:$room_version"
Edit: If you are using Kotlin, use kapt instead of annotationProcessor, and make sure to add apply plugin: 'kotlin-kapt' at top of the app's build.gradle file.

Unable to open activity: cannot create instance of Android View Model

I am creating an app to scan a barcode and get that information into a Room Database using Android View Model and LiveData.
Here is the error message
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.davin.scoutingapp2019/com.example.davin.scoutingapp2019.DataDisplay}: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:207)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) 
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) 
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30) 
at android.app.Activity.performCreate(Activity.java:6672) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.davin.scoutingapp2019.TeamDAO com.example.davin.scoutingapp2019.TeamsDatabase.teamDAO()' on a null object reference
at com.example.davin.scoutingapp2019.TeamRepository.<init>(TeamRepository.java:15)
at com.example.davin.scoutingapp2019.TeamViewModel.<init>(TeamViewModel.java:15)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:430) 
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199) 
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) 
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) 
at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30) 
at android.app.Activity.performCreate(Activity.java:6672) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
This is the AndroidViewModel class
package com.example.davin.scoutingapp2019;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import java.util.List;
public class TeamViewModel extends AndroidViewModel {
private TeamRepository mRepository;
private LiveData<List<Team>> mAllData;
public TeamViewModel(Application application) {
super(application);
mRepository = new TeamRepository(application);
mAllData = mRepository.getAllWords();
}
public LiveData<List<Team>> getAllTeams() {
return mAllData;
}
public void insert(Team team) {
mRepository.insert(team);
}
}
Here is the class/activity DataDisplay which has an instance of TeamViewModel
package com.example.davin.scoutingapp2019;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.annotation.Nullable;
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 java.util.List;
public class DataDisplay extends AppCompatActivity {
private TeamViewModel teamViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_display);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final TeamListAdapter adapter = new TeamListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
teamViewModel = ViewModelProviders.of(this).get(TeamViewModel.class);
teamViewModel.getAllTeams().observe(this, new Observer<List<Team>>() {
#Override
public void onChanged(#Nullable final List<Team> teams) {
// Update the cached copy of the words in the adapter.
adapter.setTeams(teams);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Destring destring=new Destring(data.getStringExtra("str"));
Team newTeam= new Team(destring.getTeamNumber(),destring.getPosition(),destring.getSandstorm("hab line"),destring.getSandstorm("cargo balls"),destring.getSandstorm("cargo hatches"),destring.getSandstorm("rocket balls"),destring.getSandstorm("rocket hatches"),destring.getTeleop("cargo balls"),destring.getTeleop("cargo hatches"),destring.getTeleop("rocket balls"),destring.getTeleop("rocket hatches"),destring.getRocketRole(),destring.getClimberRole(),destring.getOverallRole(),destring.getOtherComments());
teamViewModel.insert(newTeam);
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
}
This question is similar to another question but I only have one parameter in my constructor for TeamViewModel.
The rest of the code is on github
Thank You
You need to have a factory class for your ViewModel.
public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
private String mParam;
public MyViewModelFactory(Application application, String param) {
mApplication = application;
mParam = param;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new MyViewModel(mApplication, mParam);
}
And when instantiating the view model, you do like this:
MyViewModel myViewModel = new ViewModelProvider(this, new MyViewModelFactory(this.getApplication(), "my awesome param")).get(MyViewModel.class);
orginal answer
Simply type
ViewModelProvider(
this#RecipeListActivity,
ViewModelProvider.AndroidViewModelFactory(this.application)
).get(RecipeListViewModel::class.java)
this problem maybe from other parts
like repository or Room
i just update dependencies
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
I agree with the accepted answer by #AyoubBenzahia in this post that you need a factory class for creating the AndroidViewModel object but you don't need to create a new java class for that.
You can do it in a simpler version as well.
ViewModelProvider.AndroidViewModelFactory factory = new ViewModelProvider.AndroidViewModelFactory(this.getApplication());
teamViewModel = ViewModelProviders.of(this, factory).get(TeamViewModel.class);

Can't inflate subclassed DialogPreference

Ok, so I'm trying to inflate a DialogPreference in a PreferenceFragment which is nested in an AppCompatActivity. Whenever I try to go to the Activity hosting said PreferenceFragment, this error occurs.
01-14 09:40:37.002 29689-29689/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.santinocampos.android.count, PID: 29689
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.santinocampos.android.count/com.myname.android.count.Settings.SettingsActivity}: android.view.InflateException: Binary XML file line #16: Binary XML file line #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
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 #16: Binary XML file line #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
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 android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.santinocampos.android.count.Settings.SettingsActivity.onCreate(SettingsActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6237)
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 #4: Error inflating class (not found)com.santinocampos.android.count.Settings.OptionDialogPreference
at android.support.v7.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:300)
at android.support.v7.preference.PreferenceInflater.rInflate(PreferenceInflater.java:358)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:167)
at android.support.v7.preference.PreferenceInflater.inflate(PreferenceInflater.java:117)
at android.support.v7.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:115)
at android.support.v7.preference.PreferenceFragmentCompat.addPreferencesFromResource(PreferenceFragmentCompat.java:366)
at com.santinocampos.android.count.Settings.SettingsFragment.onCreate(SettingsFragment.java:19)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
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.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
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 android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
at com.santinocampos.android.count.Settings.SettingsActivity.onCreate(SettingsActivity.java:20) 
at android.app.Activity.performCreate(Activity.java:6237) 
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.ClassNotFoundException: Didn't find class "com.myname
Here's my DialogPreferenceClass
import android.content.Context;
import android.preference.DialogPreference;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import com.myname.android.count.R;
import java.util.Set;
/**
* Created by thedr on 1/13/2017.
*/
public class MyDialogPreference extends DialogPreference {
public static final int KEY = R.string.preference_phoneNumber;
private EditText mPhoneNumberEditText;
public MyDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setKey(getContext().getString(KEY));
String summary = getSharedPreferences().getString(SettingsActivity.PHONE_NUMBER_KEY, "");
setSummary(summary);
}
public void onBindDialogView(View view) {
super.onBindDialogView(view);
mPhoneNumberEditText = ((EditText) view.findViewById(R.id.editText_changeNumber));
}
public void onDialogClosed(boolean positive) {
getSharedPreferences()
.edit()
.putString(SettingsActivity.PHONE_NUMBER_KEY, mPhoneNumberEditText.getText().toString())
.apply();
super.onDialogClosed(positive);
persistBoolean(positive);
}
}
Here's my Preference xml where the inflation fails
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.myname.android.count.Settings.OptionDialogPreference
android:key="#string/preference_phoneNo"
android:dialogIcon="#android:drawable/ic_dialog_alert"
android:title="Reset Quests"
android:summary="Reset all quest-progress."
android:dialogMessage="Are you sure you wish to reset your quest progress? This action cannot be undone!"
android:positiveButtonText="Clear Quests"
android:negativeButtonText="Cancel"
/>
</PreferenceScreen>
Here's my PreferenceFragment
package com.myname.android.count.Settings;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.preference.*;
import com.santinocampos.android.count.R;
/**
* Created by thedr on 1/13/2017.
*/
public class SettingsFragment extends PreferenceFragmentCompat {
private static final String TAG = "SettingsFragment";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
#Override
public void onDisplayPreferenceDialog(Preference preference) {
super.onDisplayPreferenceDialog(preference);
if (preference.getKey().equals(getContext().getString(MyDialogPreference.KEY))) {
}
}
#Override
public void onCreatePreferences(Bundle bundle, String s) {
}
public static String getTagString() {
return TAG;
}
}
And here's my host activity
public class SettingsActivity extends AppCompatActivity {
public static final String PHONE_NUMBER_KEY = "PHONE_NUMBER";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = ((Toolbar) findViewById(R.id.toolbar_settings));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.settings_title);
}
}

Adding a custom view to Android Wear for canvas

Im trying to add a custom View to Round Android Wear and am getting the following error from logcat:
12-31 19:27:27.211 2212-2212/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.crashoveride007.roundwatchcanvas, PID: 2212
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crashoveride007.roundwatchcanvas/com.example.crashoveride007.roundwatchcanvas.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.crashoveride007.roundwatchcanvas.MyView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.crashoveride007.roundwatchcanvas.MyView
at android.view.LayoutInflater.createView(LayoutInflater.java:616)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
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 com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at com.example.crashoveride007.roundwatchcanvas.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
at java.lang.Class.getConstructor(Class.java:531)
at java.lang.Class.getConstructor(Class.java:495)
at android.view.LayoutInflater.createView(LayoutInflater.java:580)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743) 
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 com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378) 
at android.app.Activity.setContentView(Activity.java:2145) 
at com.example.crashoveride007.roundwatchcanvas.MainActivity.onCreate(MainActivity.java:16) 
at android.app.Activity.performCreate(Activity.java:5990) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Here is the MyView Custom View Class:
package com.example.crashoveride007.roundwatchcanvas;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
/**
* Created by Crash.Overide.007 on 2/24/16.
*/
public class MyView extends View{
Paint myPaint;
Bitmap image;
public MyView(Context context) {
super(context);
image = BitmapFactory.decodeResource(getResources(),R.drawable.ok);
myPaint = new Paint();
myPaint.setColor(Color.WHITE);
myPaint.setStrokeWidth(10);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(image,137,0,null);
}
}
The MainActivity Class:
package com.example.crashoveride007.roundwatchcanvas;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.round_activity_main);
final RelativeLayout main = (RelativeLayout) findViewById(R.id.roundWatch);
}
}
And The XML for round_activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/roundWatch"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.crashoveride007.roundwatchcanvas.MainActivity"
tools:deviceIds="wear_round">
<com.example.crashoveride007.roundwatchcanvas.MyView
android:id="#+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Can anyone help me in removing this error and move over how to work with canvas in a wear activity?
Thank you.
You need to provide additional constructors for your view to inflate properly. At a minimum, you'll need one that takes both a Context and an AttributeSet as parameters, like this:
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
...
}
According to the View documentation, this "second form should parse and apply any attributes defined in the layout file."
You generally ought to override the other two standard View constructors as well:
http://developer.android.com/reference/android/view/View.html#pubctors

Categories

Resources