-1

I have two activities-
1. MainActivity
2. Display_Activity

The main activity has an inner class "check". I am trying to access the code written in the inner class "check", by creating its object in the Display_Activity.
According to me I am able to run the code inside the inner class but the Sharedpreference is getting null from somewhere
When I swipe to refresh, the application produces a null object exception. I am not able to get where I am supplying the null. I tried to debug but couldn't find it. Please help if you can.

I have provided with both the activities and the logcat.

Main_Activity.java

public class MainActivity extends Activity {
String value;
String orientation="false";
EditText edtUrl;
String tknnumber;

SharedPreferences sharedpreferences;
String URL="http://192.168.1.101:8080/DoctorApp/newjsp2.jsp?token=";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edtUrl = (EditText) findViewById(R.id.edtURL);
    orientation="true";
}

public void CallURL(View view) {
    check check1 = new check();
    tknnumber = edtUrl.getText().toString();
    boolean result = isNetworkAvailable();
    if (!result) {
        Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
    } else {
        check1.Checking_network(tknnumber);
    }
}
public class check{
public void Checking_network(String tkn){
        URL = URL.concat(tkn);
     (new ParseURL()).execute(new String[]{URL});

    }

private class ParseURL extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {
        StringBuffer buffer = new StringBuffer();

        try {
            //Log.d("JSwa", "Connecting to [" + strings[0] + "]");
            Document doc = Jsoup.connect(strings[0]).get();
            String token = doc.getElementById("token").ownText();
            String p_name = doc.getElementById("pname").ownText();
            String gender = doc.getElementById("gender").ownText();
            String city = doc.getElementById("city").ownText();
            String date = doc.getElementById("date").ownText();
            String doctor=doc.getElementById("doctor").ownText();
            String time_left=doc.getElementById("time").ownText();

            buffer.append(token+"\n"+p_name+"\n"+gender+"\n"+city+"\n"+date+"\n"+doctor+"\n"+time_left);


        } catch (Exception t) {

            buffer.delete(0,buffer.length());
            buffer.append("Error");
            t.printStackTrace();
        }

        return buffer.toString();

    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s.equalsIgnoreCase("Error")){
            Toast.makeText(MainActivity.this, "Sorry! Something went wrong. Make sure you have entered the correct token number", Toast.LENGTH_LONG).show();
        }
        else{
            try{
        callIntent(s);
    }
        catch(Exception e){
            refreshCall(s);}
    }}}
}
public boolean isNetworkAvailable(){

    ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo=cm.getActiveNetworkInfo();
    if(networkInfo!=null && networkInfo.isConnected()){
        return true;
    }
    return false;
}
Context context=this;
void callIntent(String s){
    Intent intent;
    intent = new Intent(context, display_activity.class);
    intent.putExtra("info",s);
    intent.putExtra("token_number",tknnumber);
    startActivity(intent);}

void refreshCall(String s){

    SharedPreferences pref=getSharedPreferences("mydata",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString("key", s);
    editor.commit();
}}

Display_activity

public class display_activity extends Activity {
TextView token_name,patient,gender,location,date,doctor,token_null,time_left;
String token_received;
SwipeRefreshLayout mSwipeRefreshLayout;
MainActivity mainActivity=new MainActivity();
MainActivity.check abc=mainActivity.new check();
String URL="http://192.168.1.101:8080/DoctorApp/newjsp2.jsp?token=";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_activity);
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_swipe_refresh_layout);
    token_name=(TextView) findViewById(R.id.tkn);
    patient=(TextView) findViewById(R.id.patient);
    gender = (TextView) findViewById(R.id.gender);
    location=(TextView) findViewById(R.id.location);
    date=(TextView) findViewById(R.id.date1);
    doctor=(TextView) findViewById(R.id.doctor1);
    token_null=(TextView)findViewById(R.id.token);
    time_left=(TextView)findViewById(R.id.time_left);

    Intent intent=getIntent();
    String infor=intent.getStringExtra("info");
    token_received=intent.getStringExtra("token_number");
        breaking(infor);
   mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
                refreshContent();
            }});}

public void breaking(String a){
    String delimiter = "\n";
    String[] temp;
    temp = a.split(delimiter);
    try{
        token_name.setText(temp[0]);
        patient.setText(temp[1]);
        gender.setText(temp[2]);
        location.setText(temp[3]);
        date.setText(temp[4]);
        doctor.setText(temp[5]);
        time_left.setText(temp[6]+" mins (approx)");
    }
    catch (ArrayIndexOutOfBoundsException e){

        token_name.setText(a);
        e.printStackTrace();
    }
}

public void refreshContent(){
    boolean result=isNetworkAvailable();
    if(!result){
        Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
    }
    else {

        abc.Checking_network(token_received);
        SharedPreferences pref = getSharedPreferences("mydata", Context.MODE_PRIVATE);
        String information=pref.getString("key","NA");
        breaking(information);
        mSwipeRefreshLayout.setRefreshing(false);
}}


public void Callprevious(View view){
    Intent intent;
    intent = new Intent(this , MainActivity.class);
    startActivity(intent);
}
}

logcat On swipe refresh

  06-10 20:00:24.399  12012-12012/com.example.nmn.ajsouptry E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nmn.ajsouptry, PID: 12012
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:169)
        at com.example.nmn.ajsouptry.MainActivity.refreshCall(MainActivity.java:144)
        at com.example.nmn.ajsouptry.MainActivity$check$ParseURL.onPostExecute(MainActivity.java:115)
        at com.example.nmn.ajsouptry.MainActivity$check$ParseURL.onPostExecute(MainActivity.java:56)

I am a new to this website, please give me time to improve. Kindly see my error and if it seems weird , you can simply ignore it. Thank you.

AnshX
  • 71
  • 1
  • 1
  • 7
  • Amazing question you have asked. ` intent = new Intent(?????, A2.class); ` `???` needs context. Put your `MYACTIVITY.this`P.S. MYACTIVITY is the name of your activity – Murtaza Khursheed Hussain Jun 09 '15 at 13:46
  • Questions seeking debugging help (**"why isn't this code working?"**) must include the desired behavior, a _specific problem or error_ and _the shortest code necessary_ to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – Dalija Prasnikar Jun 09 '15 at 13:51
  • ok. Thanks. @MurtazaKhursheedHussain of course it isn't working that's why posted here. – AnshX Jun 09 '15 at 13:57
  • You should be using `Activity Context` for `Toast` (`MainActivity.this`). Also, your `context` variable is `null` because you try to initialize it before `onCreate()`. – codeMagic Jun 09 '15 at 16:58
  • @codeMagic Thanks for your kind suggestion. I have edited the question again and made it more clear. Please have a look. – AnshX Jun 10 '15 at 15:46
  • 1
    You **never** want to instantiate an Activity with `MainActivity mainActivity=new MainActivity();`. If you need the other class in multiple activities then you should make it a separate class. You don't even need the `check` class. Make the AsyncTask it's own class and create a constructor to accept the url (or any params you may need) – codeMagic Jun 10 '15 at 15:53
  • Thank you for the reply. You are totally correct , its not a good idea to instantiate mainActivity. but how will I access getSysytemService() in non activity class? @codeMagic – AnshX Jun 10 '15 at 16:20
  • Pass the Activity Context to the constructor. Something like `Display_Activity.this` – codeMagic Jun 10 '15 at 16:23
  • Thank you. Now i'll try this. @codeMagic – AnshX Jun 10 '15 at 16:28
  • Like this http://stackoverflow.com/questions/15409912/should-i-use-asynctask-class-inside-the-mainactivity-extending-activity/15409989#15409989 – codeMagic Jun 10 '15 at 16:31
  • That's what i wanted. Thank you so much. And I have so much of confusion in this Context thing. Can you provide me with some link where context is explained with easy examples. I'll be grateful to you. :) @codeMagic – AnshX Jun 10 '15 at 16:40
  • `Context` is certainly confusing at first and takes time to wrap your head around so don't get frustrated. But [this answer](http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context/7298955#7298955) helped me in the past along with the [linked article in it](http://possiblemobile.com/2013/06/context/) – codeMagic Jun 10 '15 at 16:43
  • The linked article seems good. Will read it. Amazing, you solved all my problems for today. Thank you. @codeMagic – AnshX Jun 10 '15 at 16:49
  • I've reopened now that you've made edits to make it more clear (though you should keep the original code) because this type of question is not a good candidate for the NPE canoncial. The NPE comes from inside the framework instead of simply a variable not initialized. – codeMagic Jun 10 '15 at 18:17

1 Answers1

1

There are quite a few issues going on here and most related to Context.

This answer discusses Context and a linked post in the comments explains it very well also.

There are different types of Contexts being used here when each should just be using the Activity Context (i.e. ActivityName.this, this, or any other way you want to go about getting a hold of the Activity's Context.

The underlying problem is that you are trying to reference the AsyncTask inner class of one Activity from another. You are trying to instantiate the Activity with new MainActivity() which you should never do.

Since the task is needed in multiple activities, simply take it out and make it its own class. You can create a constructor to pass in a url variable or whatever params you need including the Activity Context.

Also, you use Context context = this; before onCreate() runs (you have it outside of a method). This will result in null because the Context isn't available before onCreate().

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93