-2

I am trying to call the outer class method from adaptor as

new MainActivity().openPainRecordDialog(context,dbHelper);

it is working fine.

But when I do like this

Boolean status=new MainActivity().openPainRecordDialog(context,dbHelper);

if(status)
   check();

check() is the method of the adaptor class.

and

openPainRecordDialog(final Context context, final DbHelper dbHelper)
{

  //some unrelated data.
  if (logged_in && isNetworkConnected()){

  }
}

public boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

error I am getting System services not available to Activities before onCreate() at this line of code ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Question

  1. Is this the right way to call the activity method. 2.Why I am getting this error.

EDIT

I have try to do it through interface. but end up getting the error.

'int self.anotherclassfunction.SimpleAdapter$AdapterCallback.onMethodCallback()' on a null object reference

Adaptor class

public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {

    String[] goals;
    Context context;
    private AdapterCallback mAdapterCallback;


    public  SimpleAdapter(Context context, String[] goals)
    {
        super();
        this.context=context;
        this.goals=goals;

    }

    public SimpleAdapter(Context context) {

        try {
            this.mAdapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.");
        }

    }

    @Override
    public SimpleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SimpleAdapter.ViewHolder holder, int position) {

      holder.textView.setText(goals[position]);

      holder.textView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {

              try {
                  **int result=mAdapterCallback.onMethodCallback();**  //this is the line where I am getting error

                  Toast.makeText(context,Integer.toString(result), Toast.LENGTH_SHORT).show();
              } catch (ClassCastException exception) {
                  // do something
                  Log.i("In the catch","Yes");
              }




          }
      });

    }

    @Override
    public int getItemCount() {
        return  goals.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        Button textView;

        public ViewHolder(View itemView) {
            super(itemView);

            textView=(Button) itemView.findViewById(R.id.text);
        }
    }

    public static interface AdapterCallback {
        int onMethodCallback();
    }


}

Adaptor calling class

public class OtherClass extends AppCompatActivity {

    RecyclerView recyclerView;
    SimpleAdapter simpleAdapter;
    String[]  action_name={"Swimming","Yoga","SWD","IFT","Follow Diet Plan", "Diagnostic Tests","Record Temperature","Record Blood Pressure"," Record Sugar Level","Record Weight"};

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

        recyclerView=(RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        simpleAdapter=new SimpleAdapter(this, action_name);

        recyclerView.setAdapter(simpleAdapter);

    }
}

Activity whose method I am trying to call:

public class MainActivity extends AppCompatActivity implements SimpleAdapter.AdapterCallback {

    private SimpleAdapter mAdapterCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        this.mAdapterCallback=new SimpleAdapter(MainActivity.this);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public int onMethodCallback() {
        // do something
        return 2;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public void test(View v)
    {
        startActivity(new Intent(MainActivity.this,OtherClass.class));
        finish();
    }

    public int sampleFunction()
    {
        return 2;
    }
}
Ankur Khandelwal
  • 1,042
  • 3
  • 19
  • 40
  • what exactly you want to do in adapter? – Divyesh Patel Dec 07 '16 at 13:36
  • 2
    `new MainActivity()` you should never call constructor of Activity derived class ... alsked bazillion times ... – Selvin Dec 07 '16 at 13:38
  • use like this in your adapter ` ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); ` – Adnan Bin Mustafa Dec 07 '16 at 13:41
  • there is checkbox in the adaptor class, when user click on this checkbox a dialog is appeared( it declaration is in the outer class activity), and its status is sent back to adaptor class. then it call another method (method is declared in the adaptor class)based on the status. @Divyesh – Ankur Khandelwal Dec 07 '16 at 13:42
  • then how should i called @Selvin – Ankur Khandelwal Dec 07 '16 at 13:43
  • u can create dialog inside of adapter class, or if you want your exixsting code then use Interface or EVentBus or LocalBroadcastManager for send status. – Divyesh Patel Dec 07 '16 at 13:44
  • isNetworkConnected() method is called by the activity method, then how can I declared in the adaptor class. @AdnanBinMustafa – Ankur Khandelwal Dec 07 '16 at 13:44

2 Answers2

0

Why not you create your isNetworkConnected in Utils class like this and call anywhere as required.

private boolean isNetworkConnected(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                   if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                }
            }
        }
    }
    return false;
}
R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
Adnan Bin Mustafa
  • 1,229
  • 10
  • 20
0

You need to pass the context to isNetworkConnected method,

openPainRecordDialog(final Context context, final DbHelper dbHelper)
{
  if (logged_in && isNetworkConnected(context))
{
  }
}
public boolean isNetworkConnected(Conext context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60