Hello I'm trying to get the value of a SeekBar in android studio. If i run app it is crashing. There is no syntax error.
package prosis.guiaturistico;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static SeekBar seek_bar;
private static TextView text_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekbar();
}
public void seekbar(){
seek_bar = (SeekBar)findViewById(R.id.seekbar);
text_view = (TextView)findViewById(R.id.seekbarValue);
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Covered : " + progress + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in progress",Toast.LENGTH_LONG).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this,"SeekBar in start",Toast.LENGTH_LONG).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Covered : " + progress_value + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in stop",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my layout.
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:layout_above="#+id/bt_pes"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/bt_mon"
android:max="5000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/seekbarValue"
android:layout_above="#+id/seekbar"
android:layout_below="#+id/bt_caf"
android:layout_alignEnd="#+id/bt_pes"
android:layout_alignStart="#+id/bt_pes" />
When I run I get these error messages and the emulator says that unfortunatly your program has stopped.
04-27 16:26:18.615 2846-2846/prosis.guiaturistico E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: prosis.guiaturistico, PID: 2846
java.lang.RuntimeException: Unable to start activity ComponentInfo{prosis.guiaturistico/prosis.guiaturistico.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at a android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at prosis.guiaturistico.MainActivity.seekbar(MainActivity.java:27)
at prosis.guiaturistico.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
The problem is this line:
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
Both seek_bar.getProgress() and seek_bar.getMax() return primitive int values. The TextView.setText() method tends to assume primitive int values to be Resource IDs.
To avoid this, use String.valueof() to convert primitive values to a String representation. Or better yet, use a StringBuilder instead of plain String concatenation.
Related
What I'm trying to do
I'm trying to create an app that searches all the Bluetooth devices nearby and connects to the ones user wishes to connect to.
I'm trying to create a Connect button in one activity that starts the discovery function in another activity
How I'm trying to do it
So I have this MainActivity.java class / activity that has the Connect button. Upon clicking this button, it should do three things:
Check if the Bluetooth on my Smartphone is on & if it's not, turn it on.
Display a TOAST message to show whether BT has been successfully turned on or not
Start this new activity, called SearchBTDevice.java that looks for nearby BT devices & list them in a ListView
The first two are perfectly working since they're on MainActivity.java & that's where my button has been created.
Problem comes when it creates the new activity & tries to do the 3rd one. The app crashes.
This is what my MainActivity.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void connect(View v)
{
if(BA == null)
Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
else if(!BA.isEnabled())
{
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQ_CODE);
}
else {
Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!=RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
else
Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
}
public void searchBTDevices()
{
Thread searchThread = new Thread() {
#Override
public void run() {
Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
startActivity(searchBT);
}
};
searchThread.start();
}
}
This is what my SearchBTDevice.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter, BTArrayAdapter;
public IntentFilter filter = new IntentFilter();
public ListView devicesFound;
public Set<BluetoothDevice> pairedDevices;
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(!BTArrayAdapter.isEmpty())
BTArrayAdapter.clear();
searchBTDevices();
}
public void searchBTDevices()
{
pairedDevices = BlueAdapter.getBondedDevices();
if(pairedDevices.size()>0)
for(BluetoothDevice device: pairedDevices)
PairedArrayAdapter.add(device.getName() + "\t\t" + device.getAddress() + "\n");
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
BlueAdapter.startDiscovery();
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
}
}
This is what the logcat shows when my app crashes
03-17 11:51:40.120 19178-19178/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluealert, PID: 19178
java.lang.RuntimeException: Unable to start activity ComponentInfo{vertex2016.mvjce.edu.bluealert/vertex2016.mvjce.edu.bluealert.SearchBTDevice}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at vertex2016.mvjce.edu.bluealert.SearchBTDevice.onCreate(SearchBTDevice.java:57)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
So these are my questions:
Where am I going wrong & what should I do?
Is there any way I can retrieve the BluetoothAdapter, which was created in my MainActivity.java, in my new activity called SearchBTDevice.java?
Is there anyway I can set the onClick operation of a button defined in one activity from another activity?
Thank you for your time!
Define your BTArrayAdapter object in SearchBTDevice class. It is null while you call BTArrayAdapter.isEmpty() in onCreate().
I am going through an Android course online and have hit a stumbling block.
When an EditText (Number) field is submitted without any content, my app crashes.
I have tried adding exception handlers to the code, to my understanding. Nut I still have the same problem. I am handling the exceptions that show up in my logs, shown below.
The InvocationTargetException entry flags in Android Studio as Cannot resolve symbol InvocationTargetException.
I'm not sure what the problem is with that or if it might be related.
Code:
package com.example.richardcurteis.higherorlower;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
EditText getUserInput;
public int getRandomNumber() {
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(10) +1;
return randomNumber;
}
public void higherOrLower(View view) {
String exceptionMessage = "";
try {
getUserInput = (EditText) findViewById(R.id.userInput);
} catch (InvocationTargetException e) {
exceptionMessage = "InvocationTargetException";
} catch (NumberFormatException e) {
exceptionMessage = "NumberFormatException";
} catch (IllegalStateException e) {
exceptionMessage = "IllegalStateException";
}
Toast.makeText(this, exceptionMessage, Toast.LENGTH_LONG).show();
int userInteger = Integer.parseInt(getUserInput.getText().toString());
String message = "";
if (userInteger > randomNumber) {
message = "Lower!";
getUserInput.getText().clear();
} else if (userInteger < randomNumber) {
message = "Higher!";
getUserInput.getText().clear();
} else {
message = "You win!";
getUserInput.getText().clear();
getRandomNumber();
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
randomNumber = getRandomNumber();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Errors:
12-28 16:36:23.985 5035-5035/com.example.richardcurteis.higherorlower E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.richardcurteis.higherorlower, PID: 5035
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.richardcurteis.higherorlower.MainActivity.higherOrLower(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Use this helper method to convert string to integer
public static Integer toInteger(final String str, final Integer defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.valueOf(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
Something like this
Integer userInteger = toInteger(getUserInput.getText().toString(), null);
if (userInteger == null) {
Toast.makeText(getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
return;
}
Move into the "try" block this line of your code:
int userInteger = Integer.parseInt(getUserInput.getText().toString());
Looking through the error log it shows you're trying to parse a blank string to an int.
Caused by: java.lang.NumberFormatException: Invalid int: ""
InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation.
The exceptions are thrown because you're try catching around the wrong snippet of code.
I am getting Error in receiving broadcast intent i am using BatteryManager for it. I have no clue why I am getting this error.
Someone please help.
thanks in advance
Let me know if you need more code.
Here is the error:
> Error receiving broadcast Intent {
> act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras)
> } in com.example.android.login.MainActivity$1#260e12dc
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:933)
> at android.os.Handler.handleCallback(Handler.java:739)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:145)
> at android.app.ActivityThread.main(ActivityThread.java:5972)
> at java.lang.reflect.Method.invoke(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:372)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference
> at com.example.android.login.MainActivity$1.onReceive(MainActivity.java:37)
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:923)
> at android.os.Handler.handleCallback(Handler.java:739)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:145)
> at android.app.ActivityThread.main(ActivityThread.java:5972)
> at java.lang.reflect.Method.invoke(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:372)
Activity Class
package com.example.android.login;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogOutCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.ParseException;
public class MainActivity extends ActionBarActivity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
}
};
private Toolbar toolbar;
public Button logoutButton;
public int level;
#Override
public void onCreate(Bundle savedInstanceState) {
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set up a progress dialog
final ProgressDialog logout = new ProgressDialog(MainActivity.this);
logout.setTitle("Please wait.");
logout.setMessage("Logging out. Please wait.");
logout.show();
ParseUser.logOutInBackground(new LogOutCallback() {
public void done(ParseException e) {
logout.dismiss();
if (e == null) {
Intent logoutDone = new Intent(MainActivity.this, DispatchActivity.class);
startActivity(logoutDone);
} else {
Toast.makeText(MainActivity.this, "Logout Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Based on your stack trace, it looks like it is throwing a NullPointerException because the batteryTxt field is null at the time that the intent was received. As Daniel Nugent pointed out, this is because the receiver is registered before calling setContentView(). However, it looks like you're also never unregistering your receiver, so I suggest moving the code to register the receiver to the onResume() method, and adding an unregister call in the onPause() method to prevent this same NullPointerException from occurring when your activity is stopped.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
protected void onPause() {
unregisterReceiver(mBatInfoReceiver);
super.onPause();
}
do this
batteryTxt = (TextView) this.findViewById(R.id.percent);
after this
setContentView(R.layout.activity_main_appbar);
always read this section in your error log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Write the code like that
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception
I keep getting this error, I am not sure what's causing it. I declared and initialized the variables, but the error didn't disappear. I have been looking at the same error but I can't catch the mistake.
05-01 20:57:43.162 32675-32675/com.ammar.customlistview1.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40be21f8)
05-01 20:57:43.172 32675-32675/com.ammar.customlistview1.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ammar.customlistview1.app/com.ammar.customlistview1.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
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:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1810)
at com.ammar.customlistview1.app.MainActivity.<init>(MainActivity.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1026)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
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:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Here is my class code:
package com.ammar.customlistview1.app;
/**
* Created by Ammar on 5/1/2014.
*/
public class person {
private String name = "Ammar";
private int age = 21;
private int picture = R.drawable.ic_launcher;
public person(String name, int age, int picture) {
this.name = name;
this.age = age;
this.picture = picture;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPicture() {
return picture;
}
public void setPicture(int picture) {
this.picture = picture;
}
}
Here is my main activity code:
package com.ammar.customlistview1.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
personadaptor adapter ;
ArrayList <person> theperson = new ArrayList<person>();
ListView lv = (ListView) findViewById(R.id.lvmain);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
person p1 = new person("Ammar", 21 , R.drawable.ic_launcher);
person p2 = new person("Ali", 25 , R.drawable.ic_launcher);
person p3 = new person("Saber", 23 , R.drawable.ic_launcher);
theperson.add(p1);
theperson.add(p2);
theperson.add(p3);
adapter = new personadaptor(theperson, this);
lv.setAdapter(adapter);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can't call findViewById() until you've called setContentView().
You cannot use Android UI methods such as findViewById() in the initializers of an Activity (or similar) Class, as these are only valid during and after the call to onCreate().
Move your initialization code to onCreate()
(And when you do so, be sure to put the findViewById() after setContentView() as Matiash so correctly points out - otherwise you will only get a different null pointer exception)
1.ListView lv;
Listview initialization shld be after
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvmain);
2.no need to initialize this name,age and picture in person just write
private String name;
private int age ;
private int picture ;
3.in adapterclass u need layout
adapter = new personadaptor(theperson, this);//where is your row layout