-1

I have 2 modules in my application as follow app and interface. interface was an imported aar file. I am trying to launch an activity in the interface module but every time the application crashes. Launching activities on the app module works fine I had tried the other solutions available in this forum but was in vain. Find the codes below

QuestionAnalyser class

    package com.example.dell.bubblebot;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.example.dell.yandexapilanguagetranslator.Translator;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;


public class QuestionAnalyser extends AppCompatActivity {
    public static String question;
    public  static String[] words;
    String entityIdentified;
    static boolean identified = false;
    DatabaseReference entityRef;
    TranslatorServant t = new TranslatorServant();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interface);
        Translator.setKey ("trnsl.1.1.20181013T134643Z.debdb5811d6caba2.3a4daf18b25c9f4b97662d5e9ac45ed81b199c84");

    }

    public void analyse(String userQues) {
            TranslatorServant t = new TranslatorServant();
            question = userQues.replaceAll("\\p{Punct}|\\d", "");
          //  question = t.translateText(userQues).replaceAll("\\p{Punct}|\\d", "");
              words = question.split(" ");
            getEntity(words);
    }

    private void getEntity(final String[] words) {
                entityRef = FirebaseDatabase.getInstance().getReference().child("IRAdata").child("Entities");
                entityRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot entity : dataSnapshot.getChildren()) {
                            String[] synonyms = entity.child("syn").getValue().toString().split(",");
                            for (String syn : synonyms) {
                                for (String word : words) {
                                    if (word.equalsIgnoreCase(syn) || question.equalsIgnoreCase(syn)) {
                                        entityIdentified = entity.getKey();
                                        identified = true;

                                    }
                                }
                            }
                        }
                        check(words);
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                    }

                });
    }


    public void mimicOtherMessage(String message) {
        ChatMessage chatMessage = new ChatMessage(message, false);
        Interface.madapter.add(chatMessage);
    }

    public void mimicOtherMessage() {
        ChatMessage chatMessage = new ChatMessage(null, false);
        Interface.madapter.add(chatMessage);
    }

    public void check(String[] words) {
        if (identified == true) {
            initialiseEntityServant(entityIdentified, question, words);
        }
        if (identified == false) {
            for (String yes : YesNo.yes) {
                for (String w : words) {
                    if (w.equalsIgnoreCase(yes) || question.equalsIgnoreCase(yes)) {
                        identified = true;
                        entityIdentified = "basic";
                        initialiseEntityServant(entityIdentified, question, words);
                    }
                }
                for (String no : YesNo.no) {
                    for (String w : words) {
                        if (w.equalsIgnoreCase(no) || question.equalsIgnoreCase(no)) {
                            identified = true;
                            entityIdentified = "basic";
                            initialiseEntityServant(entityIdentified, question, words);
                        }
                    }
                }

            }
        }
        if (identified == false) {
            mimicOtherMessage("Sorry, I failed to understand your question.");
        }
    }

    private void initialiseEntityServant(String ent, final String userQues, final String[] words) {
        if (ent.equalsIgnoreCase("cuisine")) {
           cuisine c=new cuisine();
           c.analyse();
        }
        if(ent.equalsIgnoreCase("basic")){
            final List<String> urlsList = new ArrayList<String>();
            final List<String> descList = new ArrayList<String>();
            urlsList.add("https://media.timeout.com/images/103708802/image.jpg");
            urlsList.add("\"https://images.myguide-cdn.com/mauritius/companies/eighty-eight-chinese-restaurant/large/eighty-eight-chinese-restaurant-492783.png");

            descList.add("A Chinese dish of small steamed or fried savoury dumplings containing various fillings. Definitely worth a try");
            descList.add("Traditionally, this Chinese chicken dish is a dry-stir fry — not a lot of sauce is added into Kung Pao chicken. However, with the amount of flavour explosions happening in this dish, you don’t miss OR want any more sauce.");
            Intent i= new Intent(getApplicationContext(),gallery.class);
            i.putExtra("urls",urlsList.toArray());
            i.putExtra("desc",descList.toArray());
            startActivity(i);
        }

        // will need to initialise other classes
    }
    //add class to check if question and answer already exists

}
In this code i am calling the gallery activity 

gallery class:

package com.example.dell.bubblebot;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;


public class gallery extends AppCompatActivity {
    public static String[]desc;
    public static TextView descTextbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        descTextbox=(TextView)findViewById(R.id.desc);
        ViewPager viewPager=findViewById(R.id.view_pager);
        String[] imageUrls=getIntent().getStringArrayExtra("urls");
        String [] descArr=getIntent().getStringArrayExtra("desc");
        desc=descArr;
        ViewPagerAdapter adapter= new ViewPagerAdapter(this,imageUrls);
        viewPager.setAdapter(adapter);

    }

}

Error message:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.samples.chatbotsample1, PID: 14653
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                      at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:112)
                      at com.example.dell.bubblebot.QuestionAnalyser.initialiseEntityServant(QuestionAnalyser.java:126)
                      at com.example.dell.bubblebot.QuestionAnalyser.check(QuestionAnalyser.java:93)
                      at com.example.dell.bubblebot.QuestionAnalyser$1.onDataChange(QuestionAnalyser.java:61)
                      at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.3:75)
                      at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0.3:63)
                      at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.3:55)
                      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:7406)
                      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)
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • The `QuestionAnalyser` class appears to extend some `ContextWrapper` class – e.g., `Activity`, `Service`, etc. – and it likely shouldn't. You cannot instantiate those classes yourself. – Mike M. Nov 20 '18 at 08:52
  • No, the QuestionAnalyser class is extending only AppCompatActivity. – Samiirah Aujub Nov 20 '18 at 09:06
  • Same thing. Are you using it as an `Activity`? That is, does it actually show on-screen, or is it a utility class? Where and how is `initialiseEntityServant()` being called? – Mike M. Nov 20 '18 at 09:07
  • No it does not. This class is only used for processing. Then how should i call an activity within this class? – Samiirah Aujub Nov 20 '18 at 09:09
  • If it doesn't actually show on-screen, it should not extend any `Activity` class or subclass. If you need a `Context` in that class, or even just in that method, then pass a `Context` into it, either via a constructor, or by adding a `Context` parameter to the `initialiseEntityServant()` method. – Mike M. Nov 20 '18 at 09:11
  • I had been trying to solve this for 2 days. I have posted the full code for Question Analyser above. And i also tried to invoke the class constructor with a class but still this does not seem to work or just maybe i was doing it wrong. Can you please give me an example about how to resolve this? – Samiirah Aujub Nov 20 '18 at 09:14
  • Simply do `public class QuestionAnalyser { private Context context; public QuestionAnalyser(Context c) { context = c; } ... }`. Then wherever you get an error because of an unresolved method, call those methods on `context` – e.g., `context.startActivity(i);`. – Mike M. Nov 20 '18 at 09:24
  • Okay thank you very much for your quick answer. I will try this and let you know :) – Samiirah Aujub Nov 20 '18 at 09:28

1 Answers1

0

Notice:

Class A { ...
}

getApplicationContext belongs to abstract class Context, if you want to use this method in your custom class, the class should extends Context or any of its sub class, such as Application,Activity, etc.

navylover
  • 12,383
  • 5
  • 28
  • 41