Search code examples
javaandroidtelephonymanager

How to move TelephonyManager to different class then MainActivity


im making and APP about the Network information etc. I got a problem when i want to use TelephonyManager in different class then my MainActivity class. When i have a simple code in one class then everything is working OK, but the problem is when i want to make another class. Program then is compiling without any problem, but the APP is crashing.

Working code in one class:

MainActivity.java

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textMCC = findViewById(R.id.mcc);
    textMCC.setText(getMCC());
}
public String getMCC() {
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = telephonyManager.getNetworkOperator();
    return networkOperator.substring(0, 3);
}

When i try to split this to two different classes, MainActivity.java and Cell.java the APP is crashing.

Main Activity:

public class MainActivity extends AppCompatActivity {


 Cell cellex = new Cell();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textMCC = findViewById(R.id.mcc);
    textMCC.setText(cellex.getMCC());
}
}

Cell.java:

public class Cell {
Context context;
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

public String getMCC() {
    // TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = telephonyManager.getNetworkOperator();
    return networkOperator.substring(0, 3);
}
}

Before adding line: Context context, the program didn't compile.


Solution

  • This happens because Activity has method getSystemService which forwards the request to Context.getSystemService(). So you have to send param Context inside getMCC().

    String getMCC(Context content){ TelephonyManager telephonyManager = context.getSystemService(Context.TELEPHONY_MANAGER_SERVICE); }

    String mcc = cell.getMCC(MainActivity.this);