Problemas com NullPointerException em uma classe

eu tenho esse código abaixo que me lança a exceção de NullPointerException.Alem disso,estranhamente ele nao está “printando” nada,alguém sabe como eu posso resolver?

”””””’Codigo comeca aqui”””’

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

public class SMAReader {

public static void main(String[] args) throws IOException {      URL oracle = new URL("https://www.alphavantage.co/query?function=SMA&symbol=MSFT&interval=30min&time_period=10&series_type=open&apikey=1DZO65QEO50KA0XG");     URL close = new URL("https://www.alphavantage.co/query?function=SMA&symbol=MSFT&interval=30min&time_period=10&series_type=close&apikey=1DZO65QEO50KA0XG");     int i;     Double[] mediaDouble = new Double[10000];//cria o array que vai armazenar as medias em double     Double[] mediaDoubleClose = new Double[10000];       try (         /*BufferedReader, lê o arquivo com mais eficiência          InputStreamReader, ele converte bytes p caracteres q seria o fluxo"Stream" q entra         openStream(), abre o acesso do fluxo pela url, ou seja, ele conecta e recupera a informação da página            */         BufferedReader in = new BufferedReader(         new InputStreamReader(oracle.openStream()))) {         String inputLine;//do buffered         String[] media = new String[10000]; //cria o array que vai armazenar as medias         String[] mediaClose = new String[10000];//cria o array que vai armazenar as medias do close         int indiceMedia = 0;//indice do media         int indiceClose = 0; //indice do close           while ((inputLine = in.readLine()) != null) {//enquanto a linha nao estiver vazia             if (inputLine.contains("SMA")) {//se a linha contiver sma                  for (i = 0; i < inputLine.length(); i++ ) {//percorre ela                     if (inputLine.charAt(i) == ':') { //se na linha tbm houver :                         for (int j = i; j < inputLine.length()-1; j++) { //para j comecando no valor de i,j menor doq inputline-1                             if (inputLine.substring(13, 16).equals("SMA")) { //se oq estiver nas posicoes de 13 a 16 corresponder a sema                                 media[indiceMedia++] = inputLine.substring(20, inputLine.length()-1);//vai armazenar esse valor pro array                             }                         }                         break;                     }//fim if 2                 }//fim for             }//fim if1         }//fim while            while ((inputLine = in.readLine()) != null) {//enquanto houver linhas             if (inputLine.contains("close")) {//se a linha contiver close                 for (i = 0; i < inputLine.length(); i++ ) { //percorre o inputline ate -1 do tamanho dele                     if (inputLine.charAt(i) == ':') { //se na linha houver :                         for (int j = i; j < inputLine.length()-1; j++) {//para j = i,j menor doq o tamanho -1 do inputLine                             if (inputLine.substring(13, 17).equals("close")) {//se oq estiver nas linhas 13 a 17 for igual a close                                 mediaClose[indiceMedia++] = inputLine.substring(20, inputLine.length()-1);//cria um array que recebe esses valores                             }//fim if                         }//fim for                         break;                     }//fim if                 }//fim for             }//fim if         }//fim while            //cria o array que vai armazenar as medias do close em double tambem          for (i = 0; i < indiceMedia-1; i++) { //percorre o array             for(int j = 0;j < indiceClose;j++) //percorre o array             mediaDouble[i] = Double.parseDouble(media[i]); //e transforma em double             mediaDoubleClose[i] = Double.parseDouble(mediaClose[i]);         }//fim do for          System.out.println("teste");     }      System.out.println("teste");  } 

}

NullPointerException при отправке запроса к бд

Подскажите пожалуйста, при попытке отправки запроса:

 public List<Answer> findAllAnswersForQuestion(int id) {             Session session = HibernateSessionFactoryUtil.getSessionFactory().openSession();             String hql = "FROM Answer WHERE Answer.question.id = :id";             Query<Answer> query = session.createQuery(hql, Answer.class).setParameter("id", id);             return query.list(); } 

Получаю ошибку в строке Query query = session.createQuery(hql, Answer.class).setParameter(“id”, id);

Exception in thread "main" java.lang.NullPointerException     at java.lang.String$  CaseInsensitiveComparator.compare(String.java:1192)     at java.lang.String$  CaseInsensitiveComparator.compare(String.java:1186)     at java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376)     at java.util.TreeMap.getEntry(TreeMap.java:345)     at java.util.TreeMap.get(TreeMap.java:278)     at org.hibernate.dialect.function.SQLFunctionRegistry.findSQLFunction(SQLFunctionRegistry.java:45)     at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.findSQLFunction(SessionFactoryHelper.java:385)     at org.hibernate.hql.internal.ast.tree.IdentNode.getDataType(IdentNode.java:366)     at org.hibernate.hql.internal.ast.HqlSqlWalker.lookupProperty(HqlSqlWalker.java:659)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:5002)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExprLhs(HqlSqlBaseWalker.java:5614)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4987)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1286)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4706)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4174)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2138)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:815)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:609)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)     at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)     at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272)     at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192)     at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)     at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)     at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)     at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:158)     at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:611)     at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:720)     at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)     at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:104)     at com.quiz2.services.UserService.findAllAnswersForQuestion(UserService.java:73)     at com.quiz2.services.Service.findAllAnswersForQuestion(Service.java:44)     at com.quiz2.Main.main(Main.java:25) 

Класс вопросов

package com.quiz2.models;  import javax.persistence.*; import java.util.ArrayList; import java.util.List;  @Entity @Table(name = "questions") public class Question {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id;     @Column(name = "text_question")     private String text_question;     @Column(name = "score")     private int score;     @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true)     private List<Answer> answers;      public Question() {     }      public Question(String text_question, int score) {         this.text_question = text_question;         this.score = score;         this.answers = new ArrayList<Answer>();     }      public void addAnswer(Answer answer, boolean correct) {         answer.setCorrect(correct);         answer.setQuestion(this);         answers.add(answer);     }      public void removeAnswer(Answer answer) {         answers.remove(answer);     }      public int getId() {         return id;     }      public String getText_question() {         return text_question;     }      public void setText_question(String text_question) {         this.text_question = text_question;     }      public int getScore() {         return score;     }      public void setScore(int score) {         this.score = score;     }      public List<Answer> getAnswers() {         return answers;     }      public void setAnswers(List<Answer> answers) {         this.answers = answers;     }      @Override     public String toString() {         return "Question: " + getText_question();     } } 

Класс ответов

package com.quiz2.models;  import javax.persistence.*;  @Entity @Table(name = "answers") public class Answer {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id;     @Column(name = "text_answer")     private String text_answer;     @Column(name = "correct")     private boolean correct;      @ManyToOne(fetch = FetchType.LAZY)     @JoinColumn(name = "question_id")     private Question question;      public Answer() {     }      public Answer(String text_answer) {         this.text_answer = text_answer;     }      public int getId() {         return id;     }      public String getText_answer() {         return text_answer;     }      public void setText_answer(String text_answer) {         this.text_answer = text_answer;     }      public boolean isCorrect() {         return correct;     }      public void setCorrect(boolean correct) {         this.correct = correct;     }      public Question getQuestion() {         return question;     }      public void setQuestion(Question question) {         this.question = question;     }      @Override     public String toString() {         return "ID " + getId() + " Answer " + getText_answer() + " correct: " + isCorrect();     } } 

Безнадёга и депрессия.

Java ImageIcon NullPointerException

estoy intentando crear un icono en Java con ImageIcon, pero no consigo que encuentre la ruta que le estoy pasando. Os pongo el fragmento de código y el árbol de directorios del proyecto.

El Fragmento de código lo estoy ejecutando en Casilla.java, que está dentro del directorio

./src/main/java/smma/juegosTablero/gui

Fragmento de código:

    private final ImageIcon water = new ImageIcon(getClass().getResource("/contents/water.jpg")); 

Árbol de directorios (lo más importante):

Directorio principal: data/ src/ target/  Directorios secundarios: ./src: main/ test/  ./src/main: java/ resources/  ./src/main/java: smma/  ./src/main/java/smma: juegosTablero/  ./src/main/java/smma/juegosTablero: agentes/ contents/ gui/ util/  ./src/main/java/smma/juegosTablero/contents: acorazado1_3.jpeg acorazado2_3.jpg acorazado3_3.jpg destructor1_2.jpg destructor2_2.jpeg fragata1_1.jpg portaaviones1_4.jpeg portaaviones2_4.jpeg portaaviones3_4.jpg portaaviones4_4.jpeg t_acorazado1_3.jpg t_acorazado2_3.jpg t_acorazado3_3.jpg t_destructor1_2.jpg t_destructor2_2.jpg t_fragata1_1.jpg t_portaaviones1_4.jpg t_portaaviones2_4.jpg t_portaaviones3_4.jpg t_portaaviones4_4.jpg water.jpg  ./src/main/java/smma/juegosTablero/gui: Advertencia.form Advertencia.java AgentesJuegoJFrame.form* AgentesJuegoJFrame.java* Casilla.java ClasificacionJuegoJFrame.form* ClasificacionJuegoJFrame.java* Consola.form* Consola.java* Final.form Final.java JuegosTableroJFrame.form* JuegosTableroJFrame.java* OkCancelDialog.form* OkCancelDialog.java* PanelFicha.java PoolDeFichas.java Tablero.form Tablero.java Tablerom.java 

¿Dónde tendría que colocar la carpeta “contents” dentro del árbol anterior para que me reconozca la ruta? Es que me estoy volviendo loco.

Un saludo y muchas gracias.

getWritableDatabase devuelve nullPointerException

No puedo lanzar los metodos de SQLiteOpenHelper porque salta el error NullPointerException. Tengo una clase que se encarga de la base de datos SQLite y una clase Fragment que es el que tiene los datos que quiero que se escriban en el archivo sqlite.

public class Mydatabase extends SQLiteOpenHelper {      private static String DATABASE_NAME = "dbshoppingcart";     private static String TABLE_NAME = "shoppingcart";     private static String NAME="name";     private static String DESCRIPTION="description";     private static String COMPANY="company";     private static String PRICE="price";     private static String CITY ="city";       public Mydatabase(Context context) {         super(context, DATABASE_NAME, null, 1);       }      @Override     public void onCreate(SQLiteDatabase db) {          String myquery = "CREATE TABLE "+ TABLE_NAME+"("+NAME+" VARCHAR ,"+COMPANY+" VARCHAR , "+DESCRIPTION+ " VARCHAR , "+ PRICE +" VARCHAR, "+ CITY +" VARCHAR)";         db.execSQL(myquery);      }        public boolean insertdata(String name,String description,String company,String price, String city){         if(this!=null){             SQLiteDatabase db = this.getWritableDatabase();              ContentValues contentValues = new ContentValues();             contentValues.put(NAME,name);             contentValues.put(DESCRIPTION,description);             contentValues.put(COMPANY,company);             contentValues.put(PRICE, price);             contentValues.put(CITY, city);             long result =db.insert(TABLE_NAME,null,contentValues);              if (result== -1){                 return false;             }             else {                  return true;             }         }         return true;      }  } 

El error salta en la siguiente linea:

SQLiteDatabase db = this.getWritableDatabase(); 

Y aquí esta el fragmento desde donde llamo el metodo insertdata() para añadir los datos del fragmento al archivo SQLite (tiene muchas mas lineas de codigo pero no las he puesto porque diria que no son relevantes en este problema) Para ponernos en contexto, el metodo metodoclick() se llama cuando estoy pulsando un boton con las caracteristicas de una oferta y quiero que se almacenen en un SQLite.

public class OffersFragment extends Fragment {      private ArrayList<Offers> listaOfertas = null;     private Mydatabase mydatabase = new Mydatabase(getActivity());      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         View view = inflater.inflate(R.layout.offerslist_layout, container, false);          return view;     }        public void metodoclick(){         ArrayList<Offers> lstOfertas = GrouponData.getLstOfertas();         Offers offers = lstOfertas.get(1);         titulo = offers.getName();         descripcion = offers.getDescription();         empresa = offers.getSeller();         ciudad = offers.getCity();         precio = offers.getPrice();         mydatabase.insertdata(titulo,descripcion,empresa,precio,ciudad);     } 

Y el error que salta es el siguiente:

E/AndroidRuntime: FATAL EXCEPTION: main     Process: proyectofinal.maps.storemap, PID: 5402     java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$  CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference         at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:235)         at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:175)         at proyectofinal.maps.storemap.SQLite.Mydatabase.insertdata(Mydatabase.java:52)         at proyectofinal.maps.storemap.Fragments.OffersFragment.metodoclick(OffersFragment.java:85)         at proyectofinal.maps.storemap.adapter.OfferAdapterRecycleView$  OfferViewHolder$  1.onClick(OfferAdapterRecycleView.java:78)         at android.view.View.performClick(View.java:5338)         at android.view.View$  PerformClick.run(View.java:21539)         at android.os.Handler.handleCallback(Handler.java:819)         at android.os.Handler.dispatchMessage(Handler.java:104)         at android.os.Looper.loop(Looper.java:210)         at android.app.ActivityThread.main(ActivityThread.java:5982)         at java.lang.reflect.Method.invoke(Native Method)         at com.android.internal.os.ZygoteInit$  MethodAndArgsCaller.run(ZygoteInit.java:852)         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742) 

He visto varias personas con problemas similares que lo solucionaban pero he estado intentandolo todo y no se si es porque me estoy dejando algo que no veo o que pasa… Espero que alguien pueda ayudarme. Pasen una buena tarde.

I don’t understand why my code is throwing a nullpointerexception in java?

As far as I can see both the fileName and Input objects are no longer null before they are used, so why am I getting the exception?

                if(option == 2)     {         System.out.println("Processing order from file.");         System.out.println("Please enter the filename:");         String fileName =  scan.next();         File inputFile = null;         Scanner input = null;         try         {             inputFile = new File(fileName);             input = new Scanner(inputFile);         }          catch(FileNotFoundException e)         {             e.printStackTrace();             System.out.println("File not found.");         }         int length = Integer.parseInt(input.nextLine());          for(int i=0;i<length; i++)         {             orderArray[i]= input.nextLine();             System.out.println("Read "+ orderArray[i]);         }     } 

Multiple null Checks or try/catch NullPointerException

There is A LOT of information online stating that you should NEVER catch a NullPointerException. Generally I agree, but I am wondering about this one case.

I have inherited code that requires me to access data that I need in the following way

context.getGrandParent().getParent().getChild().isRequired() 

There is no guarantee that any of the objects in this hierarchy will not be null. I have to enter a block if isRequired() returns true. First, and what I initially wrote, with null checks:

if(context != null    && context.getGrandParent() != null    && context.getGrandParent().getParent() != null    && context.getGrandParent().getParent().getChild() != null     && context.getGrandParent().getParent().getChild().isRequired() ){    // continue with business logic } else {    LOG.error("Unable to determine if processing is required."); }     // continue with other inherited code 

Setting aside that I could refactor this, perhaps for readability, wouldn’t it make more sense to do the following?

boolean isRequired = false; try {    isRequired = context.getGrandParent().getParent().getChild().isRequired(); } catch (NullPointerException npe) {    LOG.error("Unable to determine if processing is required."); }  if(isRequired){    // continue with business logic } // continue with other inherited code 

Why Android Studio AsyncTask give me a Nullpointerexception, WHEN I use ListView?

I’m trying to do my Jsoup Project, Crawling the some webtoon Page. and I successfully got my links from webtoon page. BUT my ListView is not working throwing ERROR message(NullPointerException)

When I used ListView using AsyncTask, Android Studio keep give me a NullPointerException.

as below file “JsoupAsyncTask.java” I’ve tried to check using Log.e.

In the MainActivity.java, a listview is not null, however In the JsoupAsyncTask, a listview is null.

I don’t understand this problem

MainActivity.Java

public class MainActivity extends AppCompatActivity {      public ListView listView;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          listView = findViewById(R.id.list_view); // NOT NULL here          JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();         jsoupAsyncTask.execute();      } } 

JsoupAsyncTask.java

class JsoupAsyncTask extends AsyncTask {      MainActivity mainActivity = new MainActivity();     ArrayList<WebtoonVO> list;      ListView AsyncListView = mainActivity.listView; // NULL here! why?       @Override     protected void onPreExecute() {         super.onPreExecute();         list = new ArrayList<>();  // Check NULL         AsyncListView = mainActivity.listView;         if (AsyncListView == null) {             Log.e("AsyncListView" , "AsyncListView is NULL");         }          if (mainActivity.listView == null) {             Log.e("mainActivity.listView" , "mainActivity.listView is NULL");         }     }  // WebToon Crawling     @Override     protected ArrayList<WebtoonVO> doInBackground(Object[] objects) {         try {             String url = "https://comic.naver.com/webtoon/list.nhn?titleId=675554&weekday=mon";             Document gaus = Jsoup.connect(url).get();             Elements els = gaus.select("tr td:nth-child(odd)").select("a");             for (int i = 0; i < els.size(); i++) {                 Element el = els.get(i);                 String iLink = el.select("img").attr("src");                 String title = el.select("img").attr("title");                 String href = el.attr("href");                 WebtoonVO vo = new WebtoonVO(iLink, title, href);                 list.add(vo);             }         } catch (IOException e) {             e.printStackTrace();         }         return list;     }   // AsyncListView is NULL     @Override     protected void onPostExecute(Object o) {         super.onPostExecute(list);         ListViewAdapter adapter = new ListViewAdapter(mainActivity, R.layout.cutom, list);         AsyncListView.setAdapter(adapter);      } } 
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">      <ListView         android:id="@+id/list_view"         android:layout_width="match_parent"         android:layout_height="match_parent" />   </LinearLayout> 
2019-05-26 01:18:24.472 11116-11116/org.techtown.samplewebtoon E/AsyncListView: AsyncListView is NULL 2019-05-26 01:18:24.472 11116-11116/org.techtown.samplewebtoon E/mainActivity.listView: mainActivity.listView is NULL  2019-05-26 01:18:25.062 11116-11116/org.techtown.samplewebtoon E/AndroidRuntime: FATAL EXCEPTION: main     Process: org.techtown.samplewebtoon, PID: 11116     java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference         at org.techtown.samplewebtoon.JsoupAsyncTask.onPostExecute(JsoupAsyncTask.java:79)         at android.os.AsyncTask.finish(AsyncTask.java:695)         at android.os.AsyncTask.access$  600(AsyncTask.java:180)         at android.os.AsyncTask$  InternalHandler.handleMessage(AsyncTask.java:712)         at android.os.Handler.dispatchMessage(Handler.java:106)         at android.os.Looper.loop(Looper.java:193)         at android.app.ActivityThread.main(ActivityThread.java:6669)         at java.lang.reflect.Method.invoke(Native Method)         at com.android.internal.os.RuntimeInit$  MethodAndArgsCaller.run(RuntimeInit.java:493)         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 2019-05-26 01:18:25.071 11116-11116/org.techtown.samplewebtoon I/Process: Sending signal. PID: 11116 SIG: 9 

Spinner getSelectedItem() method returning NullPointerException

There is an array of spinners that do not have adapters to them until they are touched. However, when they have been touched and an item has been selected, the getItemSelected() method for the spinners returns a null value!

I have tried implementing if else statements that check whether the spinner is null, but that does not work.

if(spinners[i-1][j]!=null){                         if(spinners[i-1][j].getSelectedItemPosition()==0){ //if nothing selected                             combined[i][j] = " ";                         }                         else{                             combined[i][j] = spinners[i-1 [j].getSelectedItem().toString();                         }                     }                     else{                         combined[i][j] = "print Null";                     } 

I simply want to extract the item that is selected on the spinner!

Mi aplicacion me lanza un error NullPointerException

Mi aplicacion de marca un error pero no lo puedo encontrar,mi aplicacion contiene tabs y paginas web se supone que una pestaña me muestra una portada  y la siguiente me muestra las paginas web usando un spinner   Esto me dice mi logCat:   04-25 15:12:01.973: E/AndroidRuntime(1136): FATAL EXCEPTION: main 

04-25 15:12:01.973: E/AndroidRuntime(1136): Process: com.example.ecologia, PID: 1136 04-25 15:12:01.973: E/AndroidRuntime(1136): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ecologia/com.example.ecologia.MainActivity}: java.lang.NullPointerException 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread.access$ 800(ActivityThread.java:135) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread$ H.handleMessage(ActivityThread.java:1196) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.os.Handler.dispatchMessage(Handler.java:102) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.os.Looper.loop(Looper.java:136) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-25 15:12:01.973: E/AndroidRuntime(1136): at java.lang.reflect.Method.invokeNative(Native Method) 04-25 15:12:01.973: E/AndroidRuntime(1136): at java.lang.reflect.Method.invoke(Method.java:515) 04-25 15:12:01.973: E/AndroidRuntime(1136): at com.android.internal.os.ZygoteInit$ MethodAndArgsCaller.run(ZygoteInit.java:779) 04-25 15:12:01.973: E/AndroidRuntime(1136): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-25 15:12:01.973: E/AndroidRuntime(1136): at dalvik.system.NativeStart.main(Native Method) 04-25 15:12:01.973: E/AndroidRuntime(1136): Caused by: java.lang.NullPointerException 04-25 15:12:01.973: E/AndroidRuntime(1136): at com.example.ecologia.MainActivity.onCreate(MainActivity.java:57) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.Activity.performCreate(Activity.java:5231) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 04-25 15:12:01.973: E/AndroidRuntime(1136): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 04-25 15:12:01.973: E/AndroidRuntime(1136): … 11 more

aqui dejo algo del codigo            activity main:     <RelativeLayout          xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:tools="http://schemas.android.com/tools"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:paddingBottom="@dimen/activity_vertical_margin"         android:paddingLeft="@dimen/activity_horizontal_margin"         android:paddingRight="@dimen/activity_horizontal_margin"         android:paddingTop="@dimen/activity_vertical_margin"         tools:context="com.example.ecologia.MainActivity" >             <TabHost             android:id="@android:id/tabhost"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:layout_alignParentLeft="true"             android:layout_alignParentTop="true" >               <LinearLayout                 android:layout_width="match_parent"                 android:layout_height="match_parent"                 android:orientation="vertical" >                  <TabWidget                     android:id="@android:id/tabs"                     android:layout_width="match_parent"                     android:layout_height="wrap_content" >                 </TabWidget>                  <FrameLayout                     android:id="@android:id/tabcontent"                     android:layout_width="match_parent"                     android:layout_height="match_parent" >                      <LinearLayout                         android:id="@+id/Inicio"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         android:orientation="vertical"                           >                          <ImageView                             android:id="@+id/imageView1"                             android:layout_width="wrap_content"                             android:layout_height="wrap_content"                             android:src="@drawable/portada" />                      </LinearLayout>                      <LinearLayout                         android:id="@+id/Ecosistemas"                         android:orientation="vertical"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                         >                      </LinearLayout>                      <LinearLayout                         android:id="@+id/Desarrollo"                         android:orientation="vertical"                         android:layout_width="match_parent"                         android:layout_height="match_parent"                           >                     </LinearLayout>                 </FrameLayout>             </LinearLayout>         </TabHost>      </RelativeLayout>    Main Activity: package com.example.ecologia;     import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebView;     import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TabHost; import android.widget.AdapterView.OnItemSelectedListener;     public class MainActivity extends Activity implements OnItemSelectedListener {      public TabHost tabs;     public Spinner SpinTipo,SpinEco;      public WebView webEcosistemas;          public ArrayAdapter<CharSequence>adaTipoEcosistema;       public ArrayAdapter<CharSequence> adaTerrestre;       public ArrayAdapter<CharSequence> adaAcuatico;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          SpinTipo = (Spinner)findViewById(R.id.SpinTipo);         SpinEco = (Spinner)findViewById(R.id.SpinEco);         webEcosistemas = (WebView)findViewById(R.id.webEcosistemas);           adaTipoEcosistema= ArrayAdapter.createFromResource(this,               R.array.Ecosistema,               android.R.layout.simple_spinner_item);         adaTerrestre = ArrayAdapter.createFromResource(this,                   R.array.Terrestre,                   android.R.layout.simple_spinner_item);         adaAcuatico  =  ArrayAdapter.createFromResource(this,                   R.array.Acuatico,                   android.R.layout.simple_spinner_item);    adaTipoEcosistema.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   adaTerrestre.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   adaAcuatico.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    SpinTipo.setAdapter(adaTerrestre);   SpinEco.setAdapter(adaAcuatico);    SpinTipo.setOnItemSelectedListener(this);   SpinEco.setOnItemSelectedListener(this);    webEcosistemas.loadUrl("file:///android_assets/desierto.html");    tabs = (TabHost)findViewById(android.R.id.tabhost);         tabs.setup();    TabHost.TabSpec spec;     spec = tabs.newTabSpec("Inicio");    spec.setIndicator("",getResources().getDrawable(R.drawable.inicio));   spec.setIndicator(getString(R.string.tabInicio));   spec.setContent(R.id.Inicio);   tabs.addTab(spec);    spec = tabs.newTabSpec("Ecosistemas");    spec .setIndicator("",getResources().getDrawable(R.drawable.ecosistema));   spec.setIndicator(getString(R.string.tabEcosistema));   spec .setContent(R.id.Ecosistemas);   tabs.addTab(spec);    spec = tabs.newTabSpec("Desarrollo Sustentable");    spec .setIndicator("",getResources().getDrawable(R.drawable.desarrollo));   spec.setIndicator(getString(R.string.tabDesarrollo));   spec .setContent(R.id.Desarrollo);   tabs.addTab(spec);    tabs.setCurrentTab(0); }        @Override     public boolean onCreateOptionsMenu(Menu menu) {         // Inflate the menu; this adds items to the action bar if it is present.         getMenuInflater().inflate(R.menu.main, menu);         return true;     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         switch (item.getItemId()) {         case R.id.action_settings:             finish();             break;         }         return true;       }      @Override     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,             long arg3)  {         // TODO Auto-generated method stub         if (arg0.getId()==R.id.SpinTipo){             switch(SpinTipo.getSelectedItemPosition()){             case 0:                    SpinTipo.setAdapter(adaTerrestre);                    webEcosistemas.loadUrl("file:///android_asset/desierto.html");                     break;             case 1:                    SpinTipo.setAdapter(adaAcuatico);                    webEcosistemas.loadUrl("file:///android_asset/oceano.html");                     break;             }           }               if (arg0.getId()==R.id.SpinEco){                 switch(SpinTipo.getSelectedItemPosition()){                 case 0:                     switch(SpinEco.getSelectedItemPosition()){                     case 0:                         webEcosistemas.loadUrl("file:///android_asset/tundra.html");                          break;                     case 1:                         webEcosistemas.loadUrl("file:///android_asset/taiga.html");                          break;                     case 2:                         webEcosistemas.loadUrl("file:///android_asset/bosque.html");                          break;                     case 3:                         webEcosistemas.loadUrl("file:///android_asset/selva.html");                          break;                      case 4:                         webEcosistemas.loadUrl("file:///android_asset/desierto.html");                          break;                      }                     break;                 case 1:                     switch (SpinEco.getSelectedItemPosition()){                     case 0:                         webEcosistemas.loadUrl("file:///android_asset/oceano.html");                          break;                     case 1:                         webEcosistemas.loadUrl("file:///android_asset/rio.html");                       }                     break;                 }               }     }      @Override     public void onNothingSelected(AdapterView<?> arg0) {         // TODO Auto-generated method stub      } }   contenido1: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >      <TableLayout         android:layout_width="match_parent"         android:layout_height="wrap_content" >          <TableRow             android:id="@+id/tableRow1"             android:layout_width="wrap_content"             android:layout_height="wrap_content" >              <TextView                 android:id="@+id/textView1"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="@string/TEcosistemas" />              <Spinner                 android:id="@+id/SpinTipo"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content" />          </TableRow>          <TableRow             android:id="@+id/tableRow2"             android:layout_width="wrap_content"             android:layout_height="wrap_content" >              <TextView                 android:id="@+id/textView2"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:text="@string/Ecosistemas" />              <Spinner                 android:id="@+id/SpinEco"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content" />          </TableRow>     </TableLayout>      <WebView         android:id="@+id/webEcosistemas"         android:layout_width="match_parent"         android:layout_height="match_parent" />  </LinearLayout> 

Erro NullPointerException na linguagem Java utilizando o Android Studio

Estou usando o android studio para programar apps e recentemente todos os apps que eu tento programar, ao tentar rodar no emulador e no dispositivo real, recebem o mesmo erro.

04/23 00:21:55: Launching app $   adb shell am start -n "com.lucasrodrigues.gasolinaoualcool/com.lucasrodrigues.gasolinaoualcool.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Client not ready yet..Waiting for process to come online Connected to process 4121 on device motorola-moto_g_6__plus-0046152726 Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main     Process: com.lucasrodrigues.gasolinaoualcool, PID: 4121     java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.lucasrodrigues.gasolinaoualcool/com.lucasrodrigues.gasolinaoualcool.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$  Callback android.view.Window.getCallback()' on a null object reference         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)         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.NullPointerException: Attempt to invoke virtual method 'android.view.Window$  Callback android.view.Window.getCallback()' on a null object reference         at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)         at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)         at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)         at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)         at com.lucasrodrigues.gasolinaoualcool.MainActivity.<init>(MainActivity.java:13)         at java.lang.Class.newInstance(Native Method)         at android.app.Instrumentation.newActivity(Instrumentation.java:1195)         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2721)         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)  

Ja mudei as Id’s e já refiz o código mas nada muda. O meu mainActivity é esse:

package com.lucasrodrigues.gasolinaoualcool;  import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;  public class MainActivity extends AppCompatActivity {      //Recuperar os widgets     private Button botao = (Button) findViewById(R.id.botaoVerificaId);     private EditText valorAlcool = (EditText) findViewById(R.id.numeroAlcoolId);     private EditText valorGasolina = (EditText) findViewById(R.id.numeroGasolinaId);     private TextView caixaTextoResultado = (TextView) findViewById(R.id.resultadoId);     private double resultado = 0;   //Método principal     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          //Evento de botão - Clicar         botao.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  //Recuperar os valores digitados convertendo para String                 String textoGasolina = valorGasolina.getText().toString();                 String textoAlcool   = valorAlcool.getText().toString();                  //Converter de String para número                 Double precoGasolina = Double.parseDouble( textoGasolina );                 Double precoAlcool = Double.parseDouble( textoAlcool );                  //Calculo                 resultado = precoAlcool/precoGasolina;                  //Condicional                 if(resultado > 0.7){                      caixaTextoResultado.setText("Melhor utilizar a Gasolina");                  }else{                      caixaTextoResultado.setText("Melhor utilizar o Alcool");                 }                }         });       } } 

Não consigo resolver por nada e está acontecendo em qualquer código que eu escreva. Qualquer projeto, é o mesmo erro.