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();
}
};
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Whats wrong in this code? It is not sending the intent to next page.I have done it many times.When i click on the button on the Mainactivity.java i get this log.It doesn't go to the next page.Intent is not working in this activity why?Hope to get answer soon.Thanks in advance.
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num1", String.valueOf(hisnumber));
Log.d("img1", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Testing2.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num", String.valueOf(hisnumber));
Log.d("img", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Mainactivity.java
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class Testing2 extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing2);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num3", String.valueOf(hisnumber));
Log.d("img3", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(hisnumber==null){
hisnumber=new ArrayList<>();
hisimages=new ArrayList<>();
}
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Testing.java
07/28 11:07:11: Launching 'app' on Realme RMX1901.
$ adb shell am start -n "com.example.testing1/com.example.testing1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18360 on device 'realme-rmx1901-618cb732'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
E/Perf: Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
W/xample.testing: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.testing: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/num1: null
D/img1: null
D/WindowManager: Add to mViews: DecorView#5a6d981[MainActivity], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/AdrenoGLES: QUALCOMM build : e4029f9, I6b4cbc7431
Build Date : 10/01/19
OpenGL ES Shader Compiler Version: EV031.27.05.01
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
I/AdrenoGLES: Build Config : S P 8.0.11 AArch64
I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
W/AdrenoUtils: <ReadGpuID_from_sysfs:194>: Failed to open /sys/class/kgsl/kgsl-3d0/gpu_model
<ReadGpuID:218>: Failed to read chip ID from gpu_model. Fallback to use the GSL path
W/Gralloc3: mapper 3.x is not supported
I/Choreographer: Skipped 9 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 349 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=334.0, y[0]=349.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660935273, downTime=660935273, deviceId=7, source=0x1002, displayId=0 } rotation 0
D/num: null
D/img: null
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#fa02c62
D/num3: null
D/img3: null
D/WindowManager: Add to mViews: DecorView#76b323c[Testing2], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/Choreographer: Skipped 6 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 3 frames! The application may be doing too much work on its main thread.
I/xample.testing: ProcessProfilingInfo new_methods=681 is saved saved_to_disk=1 resolve_classes_delay=5000
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 327 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=81.0, y[0]=327.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660939314, downTime=660939314, deviceId=7, source=0x1002, displayId=0 } rotation 0
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 3240640)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testing1, PID: 8832
java.lang.RuntimeException: Failure from system
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1720)
at android.app.Activity.startActivityForResult(Activity.java:5319)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5263)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5648)
at android.app.Activity.startActivity(Activity.java:5616)
at com.example.testing1.Testing2$1.onClick(Testing2.java:50)
at android.view.View.performClick(View.java:7256)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
Caused by: android.os.TransactionTooLargeException: data parcel size 3240640 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:523)
at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3868)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1714)
at android.app.Activity.startActivityForResult(Activity.java:5319)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5263)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5648)
at android.app.Activity.startActivity(Activity.java:5616)
at com.example.testing1.Testing2$1.onClick(Testing2.java:50)
at android.view.View.performClick(View.java:7256)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
I/Process: Sending signal. PID: 8832 SIG: 9
Log
Main reason behind NPE is this
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
You need to check why is this not working
Workaround for NPE
Arraylist seems to be null , so check if its null or not in onClick()
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
if(hisnumber!=null){
myIntent.putExtra("hisnumber", hisnumber);
}
if(hisimages!=null){
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
}
startActivity(myIntent);
}
});
Your hisnumberand hisimages lists are NULL
Check their Nullability before adding somthing..
Testing.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (hisnumber != null) {
hisnumber.add("ass");
}
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
if (hisimages != null) {
hisimages.add(bp);
}
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});
I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
#InjectView(R.id.humidityValue) TextView mHumidityValue;
#InjectView(R.id.precipValue) TextView mPrecipValue;
#InjectView(R.id.summaryLabel) TextView mSummaryLabel;
#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 38.627;
final double longitude = -90.199;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if(isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
toggleRefresh();
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
updateDisplay();
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mRefreshImageView.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON:" + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getLong("time"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
"PropertyFetcher: AdbCommandRejectedException getting properties for
device 0043d8b5c84ed1f5: device unauthorized.
Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy#b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.
After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getForecast(); //run all your network intensive methods
return response;
}
#Override
protected void onPostExecute(String result) {
//update all your UI stuff.
}
Can't seem to correctly intent the code. But thats what you should use. Good luck.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I tried knowledge base before asking this question but I didn't find anything relevant.
I am building a native app in Android platform. I want users of this app to be able to login using their Facebook or Google login details. I have main activity in my app called StartingPoint.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner.*;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook.*;
import com.facebook.android.FacebookError;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.*;
import com.google.android.gms.plus.PlusClient;
#SuppressWarnings("deprecation")
public class StartingPoint extends Activity
implements View.OnClickListener, ConnectionCallbacks, OnConnectionFailedListener{
private static final String TAG = "StartingPoint";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
public static String APP_ID = "**************";
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
TextView signup;
//Buttons
Button btnfacebook, google;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
setContentView(R.layout.login);
signup = (TextView) findViewById(R.id.textView5);
btnfacebook = (Button) findViewById(R.id.loginfb);
google = (Button) findViewById(R.id.loging);
google.setOnClickListener(this);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnfacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/*google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.aristoslabs.com");
// AlertDialog alertDialog = new
// AlertDialog.Builder(StartingPoint.this).create();
// alertDialog.setTitle("Welcome to Colletor");
// alertDialog.setMessage("We will be back soon");
// alertDialog.show();
}
});*/
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
protected void onActivityResult1(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
/**
* Function to login into facebook
* */
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Intent i = new Intent();
i.setClass(StartingPoint.this, Settings.class);
startActivity(i);
/* *********************************************** */
btnfacebook.setVisibility(View.INVISIBLE);
// Making get profile button visible
// btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Intent i = new Intent();
i.setClass(StartingPoint.this, Settings.class);
startActivity(i);
// Making Login button invisible
// btnfacebook.setVisibility(View.INVISIBLE);
// Making logout Button visible
//btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.starting_point, menu);
return true;
}*/
#Override
public void onClick(View view) {
if (view.getId() == R.id.loging && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
}
When I run my application basically my app is getting crashed. Following log report I get in my logcat
09-18 18:22:52.750: D/libEGL(20862): loaded /system/lib/egl/libEGL_mali.so
09-18 18:22:52.760: D/libEGL(20862): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-18 18:22:52.765: D/libEGL(20862): loaded /system/lib/egl/libGLESv2_mali.so
09-18 18:22:52.770: D/(20862): Device driver API match
09-18 18:22:52.770: D/(20862): Device driver API version: 10
09-18 18:22:52.770: D/(20862): User space API version: 10
09-18 18:22:52.770: D/(20862): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
09-18 18:22:52.810: D/OpenGLRenderer(20862): Enabling debug mode 0
09-18 18:22:52.865: D/dalvikvm(20862): GC_CONCURRENT freed 149K, 8% free 12371K/13319K, paused 21ms+1ms, total 52ms
09-18 18:22:53.710: D/AndroidRuntime(20862): Shutting down VM
09-18 18:22:53.710: W/dalvikvm(20862): threadid=1: thread exiting with uncaught exception (group=0x411452a0)
09-18 18:22:53.725: E/AndroidRuntime(20862): FATAL EXCEPTION: main
09-18 18:22:53.725: E/AndroidRuntime(20862): java.lang.SecurityException: Missing android.permission.GET_ACCOUNTS
09-18 18:22:53.725: E/AndroidRuntime(20862): at android.os.Parcel.readException(Parcel.java:1425)
09-18 18:22:53.725: E/AndroidRuntime(20862): at android.os.Parcel.readException(Parcel.java:1379)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.ej$a$a.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.ek.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.plus.PlusClient.getAccountName(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at StartingPoint.onConnected(StartingPoint.java:136)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.u.v(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.u$f.a(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.u$f.a(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.u$b.A(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.google.android.gms.internal.u$a.handleMessage(Unknown Source)
09-18 18:22:53.725: E/AndroidRuntime(20862): at android.os.Handler.dispatchMessage(Handler.java:99)
09-18 18:22:53.725: E/AndroidRuntime(20862): at android.os.Looper.loop(Looper.java:137)
09-18 18:22:53.725: E/AndroidRuntime(20862): at android.app.ActivityThread.main(ActivityThread.java:4898)
09-18 18:22:53.725: E/AndroidRuntime(20862): at java.lang.reflect.Method.invokeNative(Native Method)
09-18 18:22:53.725: E/AndroidRuntime(20862): at java.lang.reflect.Method.invoke(Method.java:511)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-18 18:22:53.725: E/AndroidRuntime(20862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-18 18:22:53.725: E/AndroidRuntime(20862): at dalvik.system.NativeStart.main(Native Method)
09-18 18:23:03.805: I/Process(20862): Sending signal. PID: 20862 SIG: 9
I know that there something in this code which not correct but I am not able to figure it out.
Please let me know.
Thanks in advance
Inside <manifest> and </manifest> put this node:
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
This is your clue.
09-18 18:22:53.725: E/AndroidRuntime(20862):
java.lang.SecurityException: Missing android.permission.GET_ACCOUNTS
You need to add this permission to your manifest.
I've added AOKP's Custom Carrier Label options to my rom and everything works with the exception of getting a Settings fc when OK is clicked in the dialog window...The customlabeltextsummary is updated correctly and the carrier is changed as it should be...
Settings.java :
package com.android.settings.cyanogenmod;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.view.IWindowManager;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.provider.Settings;
import android.text.Spannable;
import android.util.Log;
import android.view.IWindowManager;
import android.view.Display;
import android.view.LayoutInflater;
import android.widget.EditText;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SystemSettings extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener{
private static final String TAG = "SystemSettings";
private static final String KEY_POWER_BUTTON_TORCH = "power_button_torch";
private CheckBoxPreference mPowerButtonTorch;
private static final String KEY_CHRONUS = "chronus";
private static final String PREF_FORCE_DUAL_PANEL = "force_dualpanel";
private static final String PREF_CUSTOM_CARRIER_LABEL = "custom_carrier_label";
Preference mCustomLabel;
Context mContext;
String mCustomLabelText = null;
CheckBoxPreference mDualpane;
private boolean torchSupported() {
return getResources().getBoolean(R.bool.has_led_flash);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.system_settings);
mCustomLabel = findPreference(PREF_CUSTOM_CARRIER_LABEL);
updateCustomLabelTextSummary();
// Dont display the lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_CHRONUS));
mPowerButtonTorch = (CheckBoxPreference) findPreference(KEY_POWER_BUTTON_TORCH);
if (torchSupported()) {
mPowerButtonTorch.setChecked((Settings.System.getInt(getActivity().
getApplicationContext().getContentResolver(),
Settings.System.POWER_BUTTON_TORCH, 0) == 1));
} else {
getPreferenceScreen().removePreference(mPowerButtonTorch);
}
mDualpane = (CheckBoxPreference) findPreference(PREF_FORCE_DUAL_PANEL);
mDualpane.setOnPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mPowerButtonTorch) {
boolean enabled = mPowerButtonTorch.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.POWER_BUTTON_TORCH,
enabled ? 1 : 0);
return true;
} else if (preference == mCustomLabel) {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.custom_carrier_label_title);
alert.setMessage(R.string.custom_carrier_label_explain);
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(mCustomLabelText != null ? mCustomLabelText : "");
alert.setView(input);
alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = ((Spannable) input.getText()).toString();
Settings.System.putString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL, value);
updateCustomLabelTextSummary();
Intent i = new Intent();
i.setAction("com.android.settings.LABEL_CHANGED");
mContext.sendBroadcast(i);
}
});
alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
ContentResolver cr = getActivity().getContentResolver();
if (preference == mDualpane) {
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.FORCE_DUAL_PANEL,
((CheckBoxPreference)preference).isChecked() ? 0 : 1);
return true;
}
return false;
}
private boolean removePreferenceIfPackageNotInstalled(Preference preference) {
String intentUri=((PreferenceScreen) preference).getIntent().toUri(1);
Pattern pattern = Pattern.compile("component=([^/]+)/");
Matcher matcher = pattern.matcher(intentUri);
String packageName=matcher.find()?matcher.group(1):null;
if(packageName != null) {
try {
getPackageManager().getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
Log.e(TAG,"package "+packageName+" not installed, hiding preference.");
getPreferenceScreen().removePreference(preference);
return true;
}
}
return false;
}
private void updateCustomLabelTextSummary() {
mCustomLabelText = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL);
if (mCustomLabelText == null || mCustomLabelText.length() == 0) {
mCustomLabel.setSummary(R.string.custom_carrier_label_notset);
} else {
mCustomLabel.setSummary(mCustomLabelText);
}
}
}
logcat :
W/System.err(13551): Removed 2131231241
W/System.err(13551): Removed 2131231255
D/dalvikvm( 3528): GC_CONCURRENT freed 384K, 16% free 2993K/3552K, paused 2ms+4ms, total 33ms
D/dalvikvm(13551): GC_CONCURRENT freed 190K, 10% free 3282K/3644K, paused 2ms+8ms, total 37ms
D/AndroidRuntime(13551): Shutting down VM
W/dalvikvm(13551): threadid=1: thread exiting with uncaught exception (group=0x40d12600)
E/AndroidRuntime(13551): FATAL EXCEPTION: main
E/AndroidRuntime(13551): java.lang.NullPointerException
E/AndroidRuntime(13551): at com.android.settings.cyanogenmod.SystemSettings$1.onClick(SystemSettings.java:143)
E/AndroidRuntime(13551): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
E/AndroidRuntime(13551): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13551): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(13551): at android.app.ActivityThread.main(ActivityThread.java:5191)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
E/AndroidRuntime(13551): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 1108): Force finishing activity com.android.settings/.SubSettings
W/ActivityManager( 1108): Activity pause timeout for ActivityRecord{40ff74b8 u0 com.android.settings/.SubSettings}
D/dalvikvm(13124): GC_FOR_ALLOC freed 411K, 22% free 3616K/4608K, paused 28ms, total 34ms
I/Process (13551): Sending signal. PID: 13551 SIG: 9
W/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
I/WindowState( 1108): WIN DEATH: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings}
I/ActivityManager( 1108): Process com.android.settings (pid 13551) has died.
E/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
E/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '41188140 com.android.settings/com.android.settings.SubSettings (server)'
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '40ffd998 com.android.settings/com.android.settings.Settings (server)'
I/WindowState( 1108): WIN DEATH: Window{41188140 u0 com.android.settings/com.android.settings.SubSettings}
I/WindowState( 1108): WIN DEATH: Window{40ffd998 u0 com.android.settings/com.android.settings.Settings}
I/ActivityManager( 1108): Start proc com.android.settings for activity com.android.settings/.Settings: pid=13575 uid=1000 gids={41000, 1015, 1028, 3002, 3001, 3003, 3007}
W/WindowManager( 1108): Rebuild removed 7 windows but added 6
W/WindowManager( 1108): This window was lost: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings EXITING}
W/WindowManager( 1108): mDisplayId=0 mSession=Session{41e7d3b0 13551:1000} mClient=android.os.BinderProxy#4108dde8
line 143 is as follows :
mContext.sendBroadcast(i);
anyone got an idea whats going on here?
mContext is null, since it is declared at the top of your class, but never given anything to hold.
You could probably use getActivity() in place of mContext since this is a Fragment and Activity is a Context subclass.
This means
mContext.sendBroadcast(i);
should be
getActivity().sendBroadcast(i);