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

エラーこのコード行でonCreate() の前にアクティビティで利用できないシステム サービスを取得 してい ます ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

質問

  1. これは、アクティビティ メソッドを呼び出す正しい方法ですか。2.このエラーが発生する理由。

編集

私はインターフェースを介してそれをやろうとしました。しかし、最終的にエラーが発生します。

null オブジェクト参照に対する '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

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;
}
于 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 に答える