如何从适配器调用外部活动方法?

时间:2016-12-07 13:34:06

标签: android android-recyclerview android-arrayadapter android-adapter android-connectivitymanager

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

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

错误我收到了 在onCreate()之前,活动无法使用系统服务 在这行代码中ConnectivityManager cm =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

问题

  1. 这是调用activity方法的正确方法吗? 2.为什么我收到这个错误。
  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;
        }
    }
    

2 个答案:

答案 0 :(得分:0)

为什么不在这样的isNetworkConnected课程中创建Utils,并根据需要随时拨打电话。

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

答案 1 :(得分: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;
    }