No se puede crear una instancia de la clase com.ejemplo.architectureexample.NoteViewModel

cada vez que ejecuto mi aplicación muestra este error en el título y he buscado el problema de algunos dijeron hacer el ViewModel constructor público y la mía es público otro dijo:

Retire el Contexto contexto y LifecycleOwner lifecycleOwner los parámetros del constructor de su HomeViewModel, o

Crear un ViewModelProvider.La fábrica que se puede construir su HomeViewModel de los casos, y el uso que de fábrica con ViewModelProviders.de()

y he hecho de las dos soluciones y sigue apareciendo el mismo error

MainActivity

package com.example.architectureexample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
//    5th video
    private NoteViewModel noteViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
        noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
            @Override
            public void onChanged(List<Note> notes) {
//                update recycleView
                Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Clase ViewModel

package com.example.architectureexample;
// 5th video
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import java.util.List;

public class NoteViewModel extends AndroidViewModel {

    private NoteRep rep;
    private LiveData<List<Note>> allNotes;

    public NoteViewModel(@NonNull Application application) {
        super(application);
        rep = new NoteRep(application);
        allNotes = rep.getAllNotes();
    }

    public void insert(Note note){
        rep.insert(note);
    }

    public void update(Note note){
        rep.update(note);
    }

    public void delete(Note note){
        rep.delete(note);
    }

    public void deleteAll(){
        rep.deleteAll();
    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }
}

Repositorio de la clase

package com.example.architectureexample;

// 4th video

import android.app.Application;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class NoteRep {

    private NoteDao noteDao;
    private LiveData<List<Note>> allNotes;

    public NoteRep(Application application){
        NoteDatabase database = NoteDatabase.getInstance(application);
        noteDao = database.noteDao();
        allNotes = noteDao.getAllNotes();
    }

//    these methods works as API the the Repository Exports to the out side
    public void insert(Note note){
        new InsertNoteAsyncTask(noteDao).execute(note);
    }

    public void update(Note note){
        new UpdateNoteAsyncTask(noteDao).execute(note);
    }

    public void delete(Note note){
        new DeleteNoteAsyncTask(noteDao).execute(note);
    }

    public void deleteAll(){
        new DeleteAllNotesAsyncTask(noteDao).execute();
    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }

    private static class InsertNoteAsyncTask extends AsyncTask<Note ,Void,Void>{
        //        we need it to do database operations
        private NoteDao noteDao;

        //        because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
        public InsertNoteAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }


        @Override
        protected Void doInBackground(Note... notes) {
            noteDao.insert(notes[0]);
            return null;
        }
    }

    private static class UpdateNoteAsyncTask extends AsyncTask<Note ,Void,Void>{
        //        we need it to do database operations
        private NoteDao noteDao;

        //        because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
        public UpdateNoteAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }


        @Override
        protected Void doInBackground(Note... notes) {
            noteDao.update(notes[0]);
            return null;
        }
    }

    private static class DeleteNoteAsyncTask extends AsyncTask<Note ,Void,Void>{
        //        we need it to do database operations
        private NoteDao noteDao;

        //        because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
        public DeleteNoteAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }


        @Override
        protected Void doInBackground(Note... notes) {
            noteDao.delete(notes[0]);
            return null;
        }
    }

    private static class DeleteAllNotesAsyncTask extends AsyncTask<Void ,Void,Void>{
        //        we need it to do database operations
        private NoteDao noteDao;

        //        because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
        public DeleteAllNotesAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }


        @Override
        protected Void doInBackground(Void... voids) {
            noteDao.deleteAllNotes();
            return null;
        }

    }

}

base de datos de la clase

package com.example.architectureexample;

// 3rd video
// this is a class where we connect the database table with the dao to get the to communicate with each other
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 NoteDatabase extends RoomDatabase {
    private static NoteDatabase instance;

//    this will access our Dao
    public abstract NoteDao noteDao();

    public static synchronized NoteDatabase getInstance(Context context){
        if(instance!=null){
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    NoteDatabase.class,"note_database")
                    .fallbackToDestructiveMigration()
//                    added call back 4th video
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }

//    4th video
    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);

            new PopulateDbAsyncTask(instance).execute();

        }
    };

    private static class PopulateDbAsyncTask extends AsyncTask<Void,Void,Void>{

        private NoteDao noteDao;

        private PopulateDbAsyncTask(NoteDatabase database){
            noteDao = database.noteDao();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            noteDao.insert(new Note("Title1","des1",1));
            noteDao.insert(new Note("Title2","des2",2));
            noteDao.insert(new Note("Title3","des3",3));
            return null;
        }
    }
}

la tabla de la clase

package com.example.architectureexample;
// 2nd video
// this is the database table
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName = "note_table")
public class Note {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String title ;
    private String description;
    private int priorty;

    public Note(String title, String description, int priorty) {
        this.title = title;
        this.description = description;
        this.priorty = priorty;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public int getPriorty() {
        return priorty;
    }
}

la interfaz DAO

package com.example.architectureexample;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

// 3rd video
// this is the dao that will interact with the databse to get the data

import java.util.List;

@Dao
public interface NoteDao {
    @Insert
    void insert(Note note);

    @Update
    void update(Note note);

    @Delete
    void delete(Note note);

    //    sql code delete from (table name)
    @Query("DELETE FROM note_table")
    void deleteAllNotes();

    @Query("SELECT * FROM note_table ORDER BY priorty DESC")
    LiveData<List<Note>> getAllNotes();

}

el logcat de Error

2019-09-18 17:38:07.042 15476-15476/com.example.architectureexample E/Minikin: Could not get cmap table size!
2019-09-18 17:38:07.088 15476-15497/com.example.architectureexample E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
2019-09-18 17:38:07.373 15476-15476/com.example.architectureexample E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.architectureexample, PID: 15476
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.architectureexample/com.example.architectureexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.architectureexample.NoteViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3303)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411)
        at android.app.ActivityThread.-wrap12(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7529)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.architectureexample.NoteViewModel
        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.architectureexample.MainActivity.onCreate(MainActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:7383)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
        at android.app.ActivityThread.-wrap12(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
        at android.os.Handler.dispatchMessage(Handler.java:108) 
        at android.os.Looper.loop(Looper.java:166) 
        at android.app.ActivityThread.main(ActivityThread.java:7529) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
        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.architectureexample.MainActivity.onCreate(MainActivity.java:22) 
        at android.app.Activity.performCreate(Activity.java:7383) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
        at android.app.ActivityThread.-wrap12(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
        at android.os.Handler.dispatchMessage(Handler.java:108) 
        at android.os.Looper.loop(Looper.java:166) 
        at android.app.ActivityThread.main(ActivityThread.java:7529) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.architectureexample.NoteDao com.example.architectureexample.NoteDatabase.noteDao()' on a null object reference
        at com.example.architectureexample.NoteRep.<init>(NoteRep.java:19)
        at com.example.architectureexample.NoteViewModel.<init>(NoteViewModel.java:18)
        at java.lang.reflect.Constructor.newInstance0(Native Method) 
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
        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.architectureexample.MainActivity.onCreate(MainActivity.java:22) 
        at android.app.Activity.performCreate(Activity.java:7383) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
        at android.app.ActivityThread.-wrap12(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
        at android.os.Handler.dispatchMessage(Handler.java:108) 
        at android.os.Looper.loop(Looper.java:166) 
        at android.app.ActivityThread.main(ActivityThread.java:7529) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 

0
2019-09-17 23:04:13
fuente
4 respuestas

Hola por Favor marque a continuación el código de referencia

$(document).ready(function() {
  var string_to_slipt = $('#Price').html();
  //console.log(string_to_slipt);
  var ret = string_to_slipt.split("Price");
  var str1 = ret[0];
  var str2 = ret[1];
  $('#Price').html(str1 + 'Price <span>' + str2 + '</span>');
});
span {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="Price">T-shirt Price in Canada</h2>

+0
2019-09-18 17:49:02

Usted necesita usar .html para agregar abarca

$('#Price').html(function() {
  return this.innerText.replace(/(.*)Price(.*)/,'$1 Price <span>$2</span>')
});
span { background-color:yellow }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="Price">T-shirt Price in Canada</h2>

Más genéricas - añadir una clase y cada uno de ellos será cambiado en uno:

$(function() {
  $('.price').html(function() {
    return this.innerText.replace(/(.*)Price(.*)/, '$1 Price <span>$2</span>')
  });
});
#PriceCAD span {
  background-color: yellow
}

#PriceMXN span {
  background-color: orange
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="price" id="PriceCAD">T-shirt Price in Canada</h2>
CAD 12
<h2 class="price" id="PriceMXN">T-shirt Price in Mexico</h2>
MXN 175

+0
2019-09-18 17:49:02

document.getElementById('price').innerHTML = 'T-shirt Price in <span>Canada</span>';
span { background-color:yellow }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="price">T-shirt Price in Canadaa</h2>

Toma esto, probablemente algún tipo de error tiene en su código, ahora me he fijado que el. Usted nos dijo que usted sabe poco de js y que no es un problema. Si se empieza con lo basico, que definitivamente va a aprender. Acabo de cambiar el innerHTML(las cosas dentro de las etiquetas). Espero que esto ayude!

+0
2019-09-18 17:49:02

var text = 'Price in 12312412';        
text = text.replace(/(.*Price)(.+)/, '$1 <span>$2</span>');
console.log(text);

+0
2019-09-18 17:49:02