How to display power connected duration in android? - java

I am trying to display the duration between power connected and disconnected in my app....i am trying to do it like below ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.batterystat);
batteryStatInfo = (TextView) findViewById(R.id.batteryStatusInfo);
this.registerReceiver(this.batteryStatRec, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver batteryStatRec = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
int icon = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL, 0);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
int chargingBy = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
boolean isChargingByUsb = chargingBy == BatteryManager.BATTERY_PLUGGED_USB;
boolean isChargingByAc = chargingBy == BatteryManager.BATTERY_PLUGGED_AC;
if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED))
{
time = new Time();
time.setToNow();
shour = time.hour;
sminutee = time.minute;
prefs.edit().putInt("shour", shour).commit();
prefs.edit().putInt("sminute", sminutee).commit();
statusBat += "Power Connected \n";
}
else if(intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED))
{
time = new Time();
time.setToNow();
ehour = time.hour;
eminutee = time.minute;
prefs.edit().putInt("ehour", ehour).commit();
prefs.edit().putInt("eminute", eminutee).commit();
statusBat += "Power Disconnected \n";
}
int eHour = prefs.getInt("ehour", 0);
int sHour = prefs.getInt("shour", 0);
int eMinute = prefs.getInt("eminutee", 0);
int sMinute = prefs.getInt("sminutee", 0);
int fHour = eHour - sHour;
int fMinute = eMinute - sMinute;
//statusBat += "Total ChargingTime : "+fHour+":"+fMinute+"\n";
batteryStatInfo.setText(statusBat);
//batteryStatImage.setImageResource(icon);
};
};
but i am not getting the result....and my app crashes all the time......is there any other way to do it??
the errors :
03-03 13:04:32.910: E/AndroidRuntime(28227): FATAL EXCEPTION: main
03-03 13:04:32.910: E/AndroidRuntime(28227): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) } in com.rhs.systmenetworkstat.BatteryStatus$1#419261e0
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Handler.handleCallback(Handler.java:800)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Handler.dispatchMessage(Handler.java:100)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Looper.loop(Looper.java:194)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.ActivityThread.main(ActivityThread.java:5410)
03-03 13:04:32.910: E/AndroidRuntime(28227): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 13:04:32.910: E/AndroidRuntime(28227): at java.lang.reflect.Method.invoke(Method.java:525)
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-03 13:04:32.910: E/AndroidRuntime(28227): at dalvik.system.NativeStart.main(Native Method)
03-03 13:04:32.910: E/AndroidRuntime(28227): Caused by: java.lang.NullPointerException
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.rhs.systmenetworkstat.BatteryStatus$1.onReceive(BatteryStatus.java:139)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
03-03 13:04:32.910: E/AndroidRuntime(28227): ... 9 more

private final BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
// Do something when power connected
//save time in proper format in preference or anywhere
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
// Do something when power disconnected
//take the time differene between connted time that
// was saved and current time and dispay it
tv.setText(time_differenece);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
filter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(receiver, filter);

Related

FatalCrash when I click on a Button

I have this RemoteCar App which has the Buttons,
"LOCK" -> leads you to another Acitivity.
"LOCATION" -> leads you to another Activity.
"START ENGINE" -> Lets you click on it and it changes the txt into
"ENGINE RUNNING".
"REFUEL" -> lets you refuel and increments my ProgressBar(FuelBar).
So the problem I have is that I can't click on START ENGINE or REFUEL anymore since the App keeps crashing for reasons I can not resolve, yet. I can easily click on LOCATION and LOCK those work perfectly fine.
Here I have the ErrorMessage:
05-21 13:39:52.887 1869-1869/? W/gralloc_ranchu: Gralloc pipe failed 05-21 13:39:52.897 1869-1869/? D/OpenGLRenderer: Enabling debug mode 0 05-21 13:39:53.097 1402-1429/system_process I/ActivityManager: Displayed com.example.schwarzerritter.remotecv02/.MainActivity: +546ms 05-21 13:39:53.297 1402-1429/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread) 05-21 13:39:56.857 1402-1486/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 05-21 13:42:00.387 1869-1869/? D/AndroidRuntime: Shutting down VM 05-21 13:42:00.387 1869-1869/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6661228) 05-21 13:42:00.387 1869-1869/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: "AC : 18"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button plusButton;
public Button minusButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
int acNum = 0;
public void onClick(View v) {
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
acNum = Integer.parseInt(seekText.getText().toString());
switch (v.getId()) {
case engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this,"Starting engine..",Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else
if(fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "No fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
}else
engButton.setText("START ENGINE");
}
break;
case refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this,"Tank is full",Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar(){
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
int acNum;
seek_bar();
lockPage();
locationPage();
}
}
java.lang.NumberFormatException: Invalid int: "AC : 18"
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
You are trying to convert the string AC : 18 to an integer in MainActivity.java line 41.
(Reading error messages helps)

getting contact phone number

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (people.moveToNext()){
int NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
int NumIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String Name = people.getString(NameIndex);
//String Num = people.getString(NumIndex);
myArr.add(Name.toString());
myNum.add(Num.toString());
}
Hello I am experiencing problems retrieving a contact's phone number where each time i enable this line of code
String Num = people.getString(NumIndex);
03-03 15:38:30.436: E/AndroidRuntime(496): FATAL EXCEPTION: main
03-03 15:38:30.436: E/AndroidRuntime(496): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.GhattasAk.RingMe/com.GhattasAk.RingMe.Main}: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Looper.loop(Looper.java:123)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 15:38:30.436: E/AndroidRuntime(496): at dalvik.system.NativeStart.main(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString_native(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString(CursorWindow.java:329)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWrapper.getString(CursorWrapper.java:135)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.GhattasAk.RingMe.Main.onCreate(Main.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-03 15:38:30.436: E/AndroidRuntime(496): ... 11 more
the application crashes.. I do not understand why
this is the edit to get a name based on a number is this true ?
if(state==TelephonyManager.CALL_STATE_RINGING)
{
// Find contact based on name.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"NUMBER = '" + number + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// Get all phone numbers.
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String numb = phones.getString(phones.getColumnIndex(Phone.DISPLAY_NAME));
}
phones.close();
}
cursor.close();
Probably becouse the contact have multiple phone nrs like work...
try this:
// Find contact based on name.
//
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();

getExtras causing app to crash

I am working on an Android App that lets me create an Event in CreateActivity, and than passes the data from CreateActivity to the MainActivity through Bundle and putExtras().
It appears as if I am using .getExtras() or getString() wrong. The app crashes once the b.getString("TITLE") function is implemented.
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents;
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView img;
View vw_master;
boolean _isBack = true;
ImageButton add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// get list view
listView = (ListView) findViewById(R.id.listViewFragment);
lstEvents = new ArrayList<Event>();
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
Bundle b = this.getIntent().getExtras();
b.getString("TITLE");
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivity(intent);
break;
}
}
}
CREATEACTIVITY
public class CreateActivity extends Activity implements OnClickListener {
EditText etTitle;
Button btDate;
Button btTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// /onclicklistener
findViewById(R.id.btn_confirm).setOnClickListener(this);
// edittexts and buttons
btDate = (Button) findViewById(R.id.btn_date);
etTitle = (EditText) findViewById(R.id.editTextTitle);
btTime = (Button) findViewById(R.id.btn_time);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_confirm:
String title = etTitle.getText().toString();
String time = btTime.getText().toString();
String date = btDate.getText().toString();
Log.e("LOG", title);
Log.e("LOG", time);
Log.e("LOG", date);
Bundle newBundle = new Bundle();
newBundle.putString("TITLE", title);
newBundle.putString("TIME", time);
newBundle.putString("DATE", date);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtras(newBundle);
startActivity(intent);
break;
}
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
}
Error Log :
03-03 15:44:07.117: E/AndroidRuntime(15202): FATAL EXCEPTION: main
03-03 15:44:07.117: E/AndroidRuntime(15202): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datetracker/com.example.datetracker.MainActivity}: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread.access$600(ActivityThread.java:146)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.os.Looper.loop(Looper.java:137)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread.main(ActivityThread.java:5168)
03-03 15:44:07.117: E/AndroidRuntime(15202): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:44:07.117: E/AndroidRuntime(15202): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
03-03 15:44:07.117: E/AndroidRuntime(15202): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
03-03 15:44:07.117: E/AndroidRuntime(15202): at dalvik.system.NativeStart.main(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202): Caused by: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202): at com.example.datetracker.MainActivity.onCreate(MainActivity.java:47)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.Activity.performCreate(Activity.java:5200)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:44:07.117: E/AndroidRuntime(15202): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
I figured out that the problem was being caused from the fact that when the app is initially opened it is trying to getExtras() on values that haven't been placed yet.
I used this as a simple fix to check if there is any extras at first launch.
Intent intent = getIntent();
if (intent.getExtras() == null) {
// Do first time stuff here
} else {
// Do stuff with intent data here
Bundle b = getIntent().getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
}
I think the problem is you didn't initialize lstEvents.
Let's try lstEvents = new ArrayList<Event>() in onCreate() methods
You should declare all your variables inside onCreate() method!!!
public class WebsiteActivity extends AppCompatActivity {
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_website);
WebView webView;
Intent intent = getIntent();
String website = intent.getStringExtra("key");
//Open website
webView = findViewById(R.id.webViewId);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(website);
}
}
My guess would be that in this line:
Integer id = eventItem.get_Id();
get_Id() is returning null, based on the observation that you aren't initializing that field in the new Event() calls and that you haven't gotten into the habit of initializing variable instances yet.
Given that, you'd be passing in null to the view.setId(id) call. When you do initialiaze it, don't initialize it to 0 as that's not a valid Id for views. you can use NO_ID or a positive number.
Also:
in onCreate()
You can check that findViewById(R.id.add) is returning a View and not null. That would cause a NullPointerException at about the right line of code.

EditText.getText().toString() crashes

In my android application , I have 3 dialogue boxes in which the user puts info into 3 editTexts and it will display the one of the data onto another class/page after it randomly picks which data to choose.
This is my mainClass
public class MainActivity extends Activity {
//Variables are displayed in this area
String choices[] = new String[3];
//EditText editText;
//EditText editText2;
//EditText editText3;
Button mainButton ;
Random rand = new Random();
int finalChoice;
String displayChoice = "";
EditText editText ;
EditText editText2;
EditText editText3;
EditText editText4;
String test;
int count = 3;
//--------------------------- --------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Makes Button
setContentView(R.layout.activity_main);
declareTextBox();
setButton();
String choice1 = editText.getText().toString();
String choice2 = editText2.getText().toString();
String choice3 = editText3.getText().toString();
choices[0] = choice1; //pass from click button to method.
choices[1] = choice2;
choices[2] = choice3;
finalChoice =rand.nextInt(2);
}
public void setButton()
{
final Button mainbutton = (Button) findViewById(R.id.mainButton);
mainbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
test = ((EditText) findViewById(R.id.editText4)).getText().toString();
// count++;
//retChoice();
// loadScreen();
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}
});
}
public void declareTextBox()
{
editText = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
}
public void getString(String finalChoice)
{
finalChoice = displayChoice;
}
public String retChoice()
{
displayChoice = choices[finalChoice];
return displayChoice;
}
public void clearText()
{
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText(" ");
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText2.setText(" ");
}
});
editText3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText3.setText(" ");
}
});
}
public void getText2()
{
}
public void getText()
{
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my Display class :
public class resultScreen extends Activity {
MainActivity ma = new MainActivity();
//Method supposedly retrieves the string data from MainActivity Class but somehow displayed null instead.
//Find a way to keep the string variable when transfering from one class to another class.
String finalResult = ma.retChoice();
public void onCreate(Bundle resultScreen){
super.onCreate(resultScreen);
setContentView(R.layout.resultscreen);
//ma.displayChoice.toString();
String str = finalResult;
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(str);
final Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(resultScreen.this,MainActivity.class);
resultScreen.this.startActivity(intent);
}
});
}
}
And this is my loading screen class right after the main button is clicked
public class loadingScreen extends Activity{
protected void onCreate(Bundle loadingScreen) {
// TODO Auto-generated method stub
super.onCreate(loadingScreen);
setContentView(R.layout.loadingscreen);
//If sound clip 20 sec long we don't want to carryit outside next class
// A timer thread looking for "run" method
Thread timer = new Thread()
{
public void run() {
try {
//this is how many mil sec
sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(loadingScreen.this, resultScreen.class);
loadingScreen.this.startActivity(intent);
loadingScreen.this.finish();
}
}
};
timer.start();
}
}
My app crashes a few seconds into the loading screen when the program attempts to display the data on the resultScreen.
Here's my logCat
05-17 22:32:54.446: D/AndroidRuntime(1181): Shutting down VM
05-17 22:32:54.446: W/dalvikvm(1181): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
05-17 22:32:54.636: E/AndroidRuntime(1181): FATAL EXCEPTION: main
05-17 22:32:54.636: E/AndroidRuntime(1181): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.choiceprototest/com.example.choiceprototest.resultScreen}: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Looper.loop(Looper.java:137)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.main(ActivityThread.java:5039)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invokeNative(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invoke(Method.java:511)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-17 22:32:54.636: E/AndroidRuntime(1181): at dalvik.system.NativeStart.main(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): Caused by: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.MainActivity.retChoice(MainActivity.java:101)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.resultScreen.<init>(resultScreen.java:18)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstanceImpl(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstance(Class.java:1319)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
05-17 22:32:54.636: E/AndroidRuntime(1181): ... 11 more
05-17 22:33:03.385: I/Process(1181): Sending signal. PID: 1181 SIG: 9
05-17 22:33:05.435: E/Trace(1204): error opening trace file: No such file or directory (2)
Thanks guys.
I believe I see the problem. You are trying to access your Array but it is an instance variable instead of static so it is being killed off when you exit your Activity. You can either put them in a static class and access them that way or pass a String variable through your Intent, depending on what you need.
If you have the value of the String you need when you leave MainActivity then I would probably just pass it through your Intent. If the value depended on something in one of your other Activities then I would consider putting it in a separate class but it doesn't look like that's what you need here
Edit
You are already doing it here, kind of
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
But you aren't starting the Activity that would get the String
i.putExtra("display" , displayChoice);
that line would pass a String with key "displpay" and value of displayChoice, although I think that value is an empty String at that point, but you don't start that Activity. I'm lost on how your flow is suppose to work but basically you would do something like this
String displayChoice = "testValue"; // some arbitrary value--whatever you need to send
Intent i = new Intent(MainActivity.this, resultScreen.class); // create the Intent
i.putExtra("display" , displayChoice); // add the extra
startActivity(i); //start the Activity
then to get the value inside resultScreen in onCreate()
Intent recIntent = getIntent(); // get the Intent that started this Activity
String value = recIntent.getStringExtra("display"); // get the value using the key
// value now equals "testValue"
I think your app chash because you have an ANR: "Application Not Responding" because you are running a long procces inside the UIThread. (onCreate() method is form the UIThread)
Use rather as an Asyntack for your sleeping thread or one handler (with messages).
If you need more I can edit your code tomorrow.

Notification runs then immediately crashes

I have proximity alerts set up. (ADDED CRASH LOG)
When the proximity alert fires, I want a notification to load. Then when the user clicks the notification, a new activity/form should load.
Right now, the notification runs then the app crashes. The notification text is received and displayed successfully though.
Does anyone see something wrong with my code that would cause it to crash when firing the notification?
This code sets up the proximity alert/notification
public void SetupProximityAlerts(LocationManager lm, String name, String info, double latitude, double longitude, int range)
{
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtra("Name", name);
intent.putExtra("Info", info);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
lm.addProximityAlert(latitude, longitude, range, -1, pi);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(new MyBroadcastReceiver(), filter);
}
And here is my BroadcastReceiver which sets the data to display in the notification. The app crashes when running: nm.notify(0, n);
Everything up until nm.notify(0, n); runs successfully. I've verified this with logging.
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extras = intent.getExtras();
String deal = (String) extras.get("Info");
Intent notificationIntent = new Intent(context, ViewTarget.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = context.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon).setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.icon)).setTicker(deal).setWhen(System.currentTimeMillis()).setAutoCancel(true).setContentTitle("Message")
.setContentText(deal);
Notification n = builder.getNotification();
n.defaults |= Notification.DEFAULT_ALL;
nm.notify(0, n);
}
}
And here is the activity I want to load when the user clicks the notification
public class ViewTarget extends ListActivity
{
#Override
public ListAdapter getListAdapter()
{
// TODO Auto-generated method stub
return super.getListAdapter();
}
#Override
public ListView getListView()
{
// TODO Auto-generated method stub
return super.getListView();
}
#Override
public void setListAdapter(ListAdapter adapter)
{
// TODO Auto-generated method stub
super.setListAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locations);
Log.v("db", "Inside ViewTarget");
}
}
Here is the crash log
04-17 21:53:52.407: E/AndroidRuntime(4717): FATAL EXCEPTION: main
04-17 21:53:52.407: E/AndroidRuntime(4717): java.lang.RuntimeException: Error receiving broadcast Intent { act=com.kjdv.gpsVegas.MyBroadcastReceiver (has extras) } in com.kjdv.gpsVegas.MyBroadcastReceiver#44a4bc30
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:905)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.os.Handler.handleCallback(Handler.java:587)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.os.Looper.loop(Looper.java:123)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 21:53:52.407: E/AndroidRuntime(4717): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 21:53:52.407: E/AndroidRuntime(4717): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 21:53:52.407: E/AndroidRuntime(4717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 21:53:52.407: E/AndroidRuntime(4717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 21:53:52.407: E/AndroidRuntime(4717): at dalvik.system.NativeStart.main(Native Method)
04-17 21:53:52.407: E/AndroidRuntime(4717): Caused by: java.lang.SecurityException: Requires VIBRATE permission
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.os.Parcel.readException(Parcel.java:1247)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.os.Parcel.readException(Parcel.java:1235)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:274)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.NotificationManager.notify(NotificationManager.java:110)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.NotificationManager.notify(NotificationManager.java:90)
04-17 21:53:52.407: E/AndroidRuntime(4717): at com.kjdv.gpsVegas.MyBroadcastReceiver.onReceive(MyBroadcastReceiver.java:51)
04-17 21:53:52.407: E/AndroidRuntime(4717): at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:892)
04-17 21:53:52.407: E/AndroidRuntime(4717): ... 9 more
Thanks!
Kevin
Caused by: java.lang.SecurityException: Requires VIBRATE permission
Did you forget a permission?
Caused by: java.lang.SecurityException: Requires VIBRATE permission
the above line in your crash indicate that you are using vibrate functionality then youmust add permission in manifeast file.The below is the permission needed to add
<uses-permission android:name="android.permission.VIBRATE" />

Categories

Resources