How to call Java class in another class - java

I'm new in Java and Android and I have lots of problems. I Create one Java class call EmptyField.java, this class has 2 methods: Login Empty and Create Empty.
I have another java file called Loginactivity.java. In Loginactivity I want to call EmptyField's class but I'm not able to do it. This is my code.
Emptyfield.java
package com.example.prenotazione_esame;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class EmptyField extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public String LoginEmpty(){
EditText login_text = (EditText) findViewById(R.id.UserName);
EditText password_text = (EditText) findViewById(R.id.Password);
if ((login_text.getText().toString().equals(""))|| (password_text.getText().toString().equals(""))){
return "Empty" ;
}
else{
return "Full";
}
}
public String CreateEmpty(){
EditText login_text = (EditText) findViewById(R.id.UserName);
EditText password_text = (EditText) findViewById(R.id.Password);
EditText conferma_text = (EditText) findViewById(R.id.Conferma);
if ((login_text.getText().toString().equals(""))|| (password_text.getText().toString().equals("")) || (conferma_text.getText().toString().equals(""))){
return "Empty" ;
}
else{
return "Full";
}
}
}
this is Loginactivity.java:
package com.example.prenotazione_esame;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class LoginActivity extends Activity {
private LoginDataBase dbLogin;
EmptyField emptyf = new EmptyField();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button button_crea = (Button) findViewById(R.id.Create);
button_crea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
openCreateAccount();
}
});
dbLogin = new LoginDataBase(this);
Button button_login = (Button) findViewById(R.id.Login);
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeLogin();
}
});
}
private void openCreateAccount(){
Intent intent_crea = new Intent(this, CreateAccountActivity.class);
startActivity(intent_crea);
}
private void executeLogin(){
//EmptyField emptyf = new EmptyField();
String a=emptyf.LoginEmpty();
Toast toast = Toast.makeText(this,a, Toast.LENGTH_SHORT);
toast.show();
}
}
I start my app on the emulator and, when it try to call EmptyField class, the app crash. can ypou help me? Thank you.
my logcat:
05-08 09:24:49.070: E/AndroidRuntime(1162): FATAL EXCEPTION: main
05-08 09:24:49.070: E/AndroidRuntime(1162): Process: com.example.prenotazione_esame, PID: 1162
05-08 09:24:49.070: E/AndroidRuntime(1162): java.lang.NullPointerException
05-08 09:24:49.070: E/AndroidRuntime(1162): at com.example.prenotazione_esame.LoginActivity.executeLogin(LoginActivity.java:55)
05-08 09:24:49.070: E/AndroidRuntime(1162): at com.example.prenotazione_esame.LoginActivity.access$1(LoginActivity.java:44)
05-08 09:24:49.070: E/AndroidRuntime(1162): at com.example.prenotazione_esame.LoginActivity$2.onClick(LoginActivity.java:34)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.view.View.performClick(View.java:4438)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.view.View$PerformClick.run(View.java:18422)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.os.Handler.handleCallback(Handler.java:733)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.os.Looper.loop(Looper.java:136)
05-08 09:24:49.070: E/AndroidRuntime(1162): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-08 09:24:49.070: E/AndroidRuntime(1162): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 09:24:49.070: E/AndroidRuntime(1162): at java.lang.reflect.Method.invoke(Method.java:515)
05-08 09:24:49.070: E/AndroidRuntime(1162): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-08 09:24:49.070: E/AndroidRuntime(1162): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-08 09:24:49.070: E/AndroidRuntime(1162): at dalvik.system.NativeStart.main(Native Method)
here my empyfield.java. Now it run. Thank you.
package com.example.prenotazione_esame;
import android.widget.EditText;
public class EmptyField{
public String LoginEmpty(EditText x, EditText y){
if ((x.getText().toString().equals(""))|| (y.getText().toString().equals(""))){
return "Empty" ;
}
else{
return "Full";
}
}
public String CreateEmpty(EditText x, EditText y, EditText z){
if ((x.getText().toString().equals(""))|| (y.getText().toString().equals("")) || (z.getText().toString().equals(""))){
return "Empty" ;
}
else{
return "Full";
}
}
}

Your method is declared as private. Have you tried making it public?
private void executeLogin(){
Try changing it to.
public void executeLogin(){

So, if you want to show another screen with login and password fields, you need to use startActivityForResult() method:
http://developer.android.com/training/basics/intents/result.html
And at this case in EmptyField.onCreate() method you need to setContent (or you have not View to use findViewById() method).
Another way means that EmptyField is just helper class. So there are no reasons to extend Activity class. But in this case you must send your main view to LoginEmpty() method, and call findViewById for this view.

EmptyField will not work calling findViewById() will need to setContentView() in that activity each activity have they own life cycle if you want to access those component maybe passing those component inside bundle not sure.
But in your case i would just create a simple class and pass those component you don't really need extend Activity in your case.

Related

Can't solve Runtime error on Android Studio 2.1

I'm an Android beginner and I'building a test app to know what I can do and what I can't, and I'm trying to solve this Runtime error and don't know what to do.
Can anyone help me please? I post my code and the error
MainActvity.java:
package com.example.android.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText uname;
{
uname = (EditText) findViewById(R.id.username);
}
EditText pword;
{
pword = (EditText) findViewById(R.id.password);
}
Button btn;
{
btn = (Button) findViewById(R.id.button);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickButtonListener();
}
public void OnClickButtonListener() {
btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.android.myapplication.Activity2");
startActivity(intent);
}
}
);
}
}
Log:
05-01 14:32:21.725 32378-32378/com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.myapplication, PID: 32378
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.myapplication/com.example.android.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2773)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2172)
at com.example.android.myapplication.MainActivity.<init>(MainActivity.java:12)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2773) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Move all three of your statements like this one:
uname = (EditText) findViewById(R.id.username);
into onCreate(), after your setContentView() call, for two reasons:
In general, you cannot safely call methods that you inherit from Activity until after super.onCreate() has been called
You specifically cannot call findViewById() until you actually have the views, such as by calling setContentView()
Take these three line of code to oncreate method after the setcontentview method recall. That initializes your view and your NULLPOINTEREXCEPTION will not happen.
uname = (EditText) findViewById(R.id.username);
pword = (EditText) findViewById(R.id.password);
btn = (Button) findViewById(R.id.button);

Android- Null pointer exception from getStringExtra using intent send a value to another activity by button click

I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836

Unable to instantiate activity ComponentInfo - AndroidStudio

I am a complete beginner to android/Java development and I massively appreciate any pointers anyone is able to give me on the issue I'm having. Here is the MainActivity.java.
package com.example.harris.enterappman;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
EditText enterName;
TextView usersName;
String str = enterName.getText().toString();
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
public void printUsersName(){
}
}
Everytime I try and run the program, it fails with the error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.harris.enterappman/com.example.harris.enterappman.Main Activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.harris.enterappman.MainActivity.<init>(MainActivity.java:48)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5021)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
            at dalvik.system.NativeStart.main(Native Method)
From others posts online I have come to the conclusion that the problem is related to abstract methods? I was unable to work out how my code was wrong.
Cheers,
Harris
String str = enterName.getText().toString();
enterName is null at this point, as you are not setting it ever. You are welcome to declare String str; as a field, but you cannot initialize it until after you set a value on enterName.
You have code to initialize enterName in a somewhat strange getName() method, but you do not appear to be calling that ever.
you have not initialised entername properly
either use:
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
...
or use it like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getName();
}
public void getName(){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(str);
}
You call enterName.getText() when enterName is null, which leads to NullPointerException.
Few things I suggest:
If you want to own references to the layout components, call these in the onCreate method:
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
Don't call methods in the class itself (except some constructors), call them in a method (I refer to the str variable).
how possible you are setting your str using enterName, as enterName is not initialized and hence it is null causing Null pointer exception
you must have to initilize enterName before using it, as you are doing initialization in your getName() method, and then use it to get its text
your code must be like this and you have to call this method from onCreate()
public void getName(View view){
enterName = (EditText) findViewById(R.id.enterName);
usersName = (TextView) findViewById(R.id.helloNameView);
usersName.setText(enterName.getText().toString());
}

IBM Worklight - Unable to get network signal strength in Android

Below is my Java implementation. The idea is to display myUtilString in an edit text in order to see the signal strength in a Hybrid android app while in a WL.NativePage, but I get nothing.
I have tested the app on a real device, changing to 2G, 3G and LTE but I don't receive anything. I have implemented a function called onSignalStrengthsChanged, but I cant figure out what is wrong.
In LogCat there is nothing of interest; maybe onSignalStrengthsChanged never is fired.
package com.AndroidShowNativePage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.telephony.gsm.GsmCellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.CellLocation;
import android.webkit.WebView;
public class HelloNative extends Activity {
EditText editText = null;
EditText editText1 = null;
String myUtilString = "";
private TelephonyManager tm ;
private DroidPhoneStateListener listener;
private GsmCellLocation location;
public void GSM(Activity activity, WebView view) {
tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
listener = new DroidPhoneStateListener(view);
location = new GsmCellLocation();
}
public void listen() {
tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
//TODO
//tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
//tm.listen(listener, PhoneStateListener.LISTEN_CELL_LOCATION);
//tm.listen(listener, PhoneStateListener.LISTEN_DATA_ACTIVITY);
}
public void unlisten() {
tm.listen(listener, PhoneStateListener.LISTEN_NONE);
}
public int getCid() {
return location.getCid();
}
public int getLac() {
return location.getLac();
}
/*
* ???? public int getPsc() { return location.getPsc(); }
*/
private class DroidPhoneStateListener extends PhoneStateListener {
private WebView view;
DroidPhoneStateListener(WebView view) {
this.view = view;
}
#Override
public void onCellLocationChanged(CellLocation location) {
myUtilString = ( "onCellLocationChanged: " + location.toString());
// view.loadUrl("javascript:droid.Accelerometer.onUpdate();
}
#Override
public void onDataConnectionStateChanged(int state, int networkType) {
myUtilString =( "onDataConnectionStateChanged: " + state + ":" + networkType);
}
#Override
public void onSignalStrengthsChanged(SignalStrength s) {
super.onSignalStrengthsChanged(s);
String r = s.getGsmSignalStrength() + ":" + s.getCdmaDbm() + ":"
+ s.getCdmaEcio() + ":" + s.getEvdoDbm() + ":"
+ s.getEvdoEcio() + ":" + s.getEvdoSnr() + ":"
+ s.getGsmBitErrorRate();
myUtilString = ("hello Change('" + r.toString()+ "');");
}
#Override
public void onSignalStrengthChanged(int asu) {
myUtilString = ( "onSignalStrengthChanged: " + asu);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String name = getIntent().getStringExtra("nameParam");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
TextView textView1 = new TextView(this);
textView1.setText("Name received from JavaScript :: " + name);
TextView textView2 = new TextView(this);
textView2.setText("Enter the phone number");
editText = new EditText(this);
editText.setText("1234567890");
editText1 = new EditText(this);
editText1.setText("any measure on dBd");
Button submitButton = new Button(this);
submitButton.setText("Return to the Web App");
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = editText.getText().toString();
Intent phoneNumberInfo = new Intent();
phoneNumberInfo.putExtra("phoneNumber", phoneNumber);
setResult(RESULT_OK, phoneNumberInfo);
finish();
}
});
Button submitMeasure = new Button(this);
submitMeasure.setText("Go measure");
submitMeasure.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editText1.setText( myUtilString );
}
});
linearLayout.addView(textView1);
linearLayout.addView(textView2);
linearLayout.addView(editText);
linearLayout.addView(submitButton);
linearLayout.addView(submitMeasure);
linearLayout.addView(editText1);
}
}
here is LogCat:
05-08 12:06:30.140: D/SoftKeyboardDetect(1078): Ignore this event
05-08 12:06:31.190: D/WLDroidGap(1078): Started copying files to local storage...
05-08 12:06:48.800: D/dalvikvm(1078): GC_FOR_ALLOC freed 494K, 15% free 3318K/3896K, paused 35ms, total 35ms
05-08 12:06:59.950: D/dalvikvm(1078): GC_FOR_ALLOC freed 370K, 16% free 3319K/3908K, paused 34ms, total 34ms
05-08 12:07:10.540: D/WLDroidGap(1078): Finished copying files to local storage...
05-08 12:07:10.550: D/WLDroidGap(1078): no need to check web resource integrity
05-08 12:07:10.690: D/CordovaWebView(1078): >>> loadUrl(file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:10.690: D/PluginManager(1078): init()
05-08 12:07:10.730: D/CordovaWebView(1078): >>> loadUrlNow()
05-08 12:07:12.560: D/CordovaActivity(1078): onMessage(onPageStarted,file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:14.610: D/CordovaWebViewClient(1078): onPageFinished(file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:14.610: D/CordovaActivity(1078): onMessage(onPageFinished,file:///data/data/com.AndroidShowNativePage/files/www/skinLoader.html)
05-08 12:07:16.650: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:17.250: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:17.260: W/PluginManager(1078): THREAD WARNING: exec() call to App.show blocked the main thread for 21ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.400: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:17.400: D/CordovaActivity(1078): onMessage(networkconnection,3g)
05-08 12:07:17.420: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:17.660: D/dalvikvm(1078): GC_FOR_ALLOC freed 458K, 14% free 3365K/3908K, paused 36ms, total 39ms
05-08 12:07:17.710: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 95ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.780: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 35ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.790: D/CordovaWebView(1078): >>> loadUrl(file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:17.810: D/PluginManager(1078): init()
05-08 12:07:17.810: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.loadSkin blocked the main thread for 29ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:17.820: D/CordovaWebView(1078): >>> loadUrlNow()
05-08 12:07:18.020: D/CordovaActivity(1078): onMessage(onPageStarted,file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:23.320: D/CordovaActivity(1078): onMessage(spinner,stop)
05-08 12:07:23.370: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:23.400: D/CordovaNetworkManager(1078): Connection Type: 3g
05-08 12:07:23.400: D/CordovaActivity(1078): onMessage(networkconnection,3g)
05-08 12:07:24.010: D/CordovaWebViewClient(1078): onPageFinished(file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:24.010: D/CordovaActivity(1078): onMessage(onPageFinished,file:///data/data/com.AndroidShowNativePage/files/www/default/AndroidShowNativePage.html)
05-08 12:07:24.240: I/Choreographer(1078): Skipped 32 frames! The application may be doing too much work on its main thread.
05-08 12:07:24.440: D/AndroidShowNativePage(1078): wlclient init started
05-08 12:07:24.530: D/AndroidShowNativePage(1078): Read cookies: null
05-08 12:07:24.560: D/AndroidShowNativePage(1078): CookieMgr read cookies: {}
05-08 12:07:24.870: W/AndroidShowNativePage(1078): Your application is using the WL.OptionsMenu API. Note that, if your application targets Android 3.0 (API level 11) or higher, WL.OptionsMenu might have no effect, depending on the device.
05-08 12:07:24.970: W/PluginManager(1078): THREAD WARNING: exec() call to DeviceAuth.getDeviceUUID blocked the main thread for 24ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:25.000: D/AndroidShowNativePage(1078): addDeviceIDHeader deviceIDSuccessCallback
05-08 12:07:25.050: W/PluginManager(1078): THREAD WARNING: exec() call to Utils.writePref blocked the main thread for 21ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:07:25.080: D/AndroidShowNativePage(1078): connectOnStartup finalizeInit
05-08 12:07:25.190: D/AndroidShowNativePage(1078): before: app init onSuccess
05-08 12:07:25.310: D/AndroidShowNativePage(1078): after: app init onSuccess
05-08 12:07:25.350: D/AndroidShowNativePage(1078): added onPause event handler
05-08 12:07:25.370: D/AndroidShowNativePage(1078): wlclient init success
05-08 12:26:11.550: D/CordovaActivity(1078): Paused the application!
05-08 12:26:11.550: D/CordovaWebView(1078): Handle the pause
05-08 12:26:11.650: W/PluginManager(1078): THREAD WARNING: exec() call to NativePage.show blocked the main thread for 151ms. Plugin should use CordovaInterface.getThreadPool().
05-08 12:26:12.620: I/Choreographer(1078): Skipped 60 frames! The application may be doing too much work on its main thread.
05-08 12:26:13.040: D/AndroidShowNativePage(1078): Flush called
05-08 12:26:17.070: I/Choreographer(1078): Skipped 75 frames! The application may be doing too much work on its main thread.
Do you get any errors either in Eclipse console or in the LogCat view? Provide the output from LogCat, that should help. Edit the question with this information.
The following permission needs to be added to AndroidManifest.xml as well:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Edit:
There is also the following tutorial to get signal strength: http://www.firstdroid.com/2010/05/12/get-provider-gsm-signal-strength/
I've followed it, and it worked for me in the Android emulator.
This is my Java implementation:
package com.testapp;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class HelloNative extends Activity {
TelephonyManager tm;
MyPhoneStateListener MyListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyListener = new MyPhoneStateListener();
tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
Button submitButton = new Button(this);
submitButton.setText("Return to the Web App");
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_OK);
finish();
};
});
linearLayout.addView(submitButton);
}
private class MyPhoneStateListener extends PhoneStateListener
{
/* Get the Signal strength from the provider, each time there is an update */
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
Toast.makeText(getApplicationContext(), "Signal strength is: "
+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
}
};
}

How can I access a function in another class?

I am developing an app for android that has to access another class, but i don't know why it doesn't work.
When run the App in android 2.3.3 it force closes, and I don't understand why. I think that the method is correct.
Log in the force close the phone android:
> app_vercode:1
device_model:u8800
build_version:111180
condition:1
processName:beta.tester
pid:13277
uid:10088
tag:null
shortMsg:java.lang.NullPointerException
longMsg:java.lang.NullPointerException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
stackTrace:java.lang.RuntimeException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at beta.tester.BetaTesterActivity.onCreate(BetaTesterActivity.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
... 11 more
Detail logs:
EDIT: This code already is correctly.
The code:
class BetaTesterActivity:
package beta.tester;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class BetaTesterActivity extends Activity {
public TextView text1;
private teste cmd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (TextView) findViewById(R.id.text1);
//Start the function
cmd = new teste();
cmd.start(this);
}
}
class teste:
package beta.tester;
public class teste {
//Function that I will start
public void start(BetaTesterActivity zav){
zav.text1.setText("Hello");
}
//
}
In class teste, you are creating a new BetaTesterActivity, which is useless. You need to use the instance created by the framework. Change your class teste to this:
public class teste {
//Function that I will start
public void start(BetaTesterActivity zav){
zav.text1.setText("Hello");
}
}
Then in the onCreate method of your activity class, you need to initialize cmd and then call start like this:
cmd.start(this);

Categories