-2

我试图从适配器调用外部类方法

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

它工作正常。

但是当我这样做时

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

if(status)
   check();

check() 是适配器类的方法。

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;
    }

错误我 在这行代码 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);得到System services not available to Activities before onCreate( );

问题

  1. 这是调用活动方法的正确方法吗?2.为什么我会收到这个错误。

编辑

我试图通过界面来做到这一点。但最终得到错误。

'int self.anotherclassfunction.SimpleAdapter$AdapterCallback.onMethodCallback()' 在空对象引用上

适配器类

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();
    }


}

适配器调用类

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);

    }
}

我试图调用其方法的活动:

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;
    }
}
4

2 回答 2

0

你为什么不像这样创建你isNetworkConnectedUtils课堂并根据需要在任何地方打电话。

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;
}
于 2016-12-07T13:39:44.060 回答
0

您需要将上下文传递给 isNetworkConnected 方法,

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;
    }
于 2016-12-07T13:41:15.343 回答