Android error trying to execute startActivity - java

I'm trying to add functionality to an action bar. When I hit the button, I want to go to another activity. I did it before and it worked it, but now I'm getting the following error:
12-27 17:22:48.218 1339-1350/? W/Binder:
Caught a RuntimeException from the binder stub implementation.
java.lang.NullPointerException
at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280)
at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
12-27 17:22:48.218 1253-1416/? W/InputMethodManagerService:
Got RemoteException sending setActive(false) notification to pid 2082 uid 10056
This is the code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ajustes:
return true;
case R.id.modo_edicion:
Intent intent = new Intent(ImagenesAlumnoActivity.this, ModoEdicionActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
And this is the code from the activity that I want to show.
public class ModoEdicionActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modo_edicion);
}
}

Related

DialogFragment crashes when calling show()

I want to display a simple DialogFragment within a Fragment, but it crashes every time the show() method is called.
It either crashes back to the MainActivity or it throws me a NullPointer Exception that does not seem to be related to the crash directly. I think Logcat swallows the actual problem somehow.
Here is the call and the DialogFragment subclass:
private void showCheatingDialog() {
DialogFragment newFragment = new CheatingDialogFragment();
newFragment.show(getChildFragmentManager(), "CheatingDialogFragment");
}
#Override
public void onCheatingPositiveClick(DialogFragment dialog) {
try {
client.puzzleDone(BLUFF);
} catch(IOException ex) {
Log.e("tiles", ex.toString());
Toast.makeText(getActivity(), "Connection to the server failed", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCheatingCancelClick(DialogFragment dialog) {
// do nothing
}
public class CheatingDialogFragment extends DialogFragment {
public interface CheatingDialogListener {
public void onCheatingPositiveClick(DialogFragment dialog);
public void onCheatingCancelClick(DialogFragment dialog);
}
CheatingDialogListener listener;
// Override the Fragment.onAttach() method to instantiate the CheatingDialogListener
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the CheatingDialogListener so we can send events to the host
listener = (CheatingDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(getActivity().toString()
+ " must implement CheatingDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.cheating_dialog_fragment)
.setPositiveButton(R.string.cheating_dialog_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
listener.onCheatingPositiveClick(CheatingDialogFragment.this);
}
})
.setNegativeButton(R.string.cheating_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the negative button event back to the host activity
listener.onCheatingCancelClick(CheatingDialogFragment.this);
}
});
return builder.create();
}
}
Here's the exception Logcat shows:
2021-06-17 08:45:04.952 7095-7095/com.example.se2_gruppenphase_ss21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.se2_gruppenphase_ss21, PID: 7095
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.se2_gruppenphase_ss21.networking.AvailableRoom.getName()' on a null object reference
at com.example.se2_gruppenphase_ss21.menu.RoomFragment.onCreateView(RoomFragment.java:86)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Android: java.lang.IllegalStateException: Already attached

I'm developing an Android app to store personal info in SQLite database, withdraw them out and display the list in Activity.Actually,the moment users have put data into database and returned to Activity,the page must be refreshed to upgrade the list with something new data.I used the statementonCreate(null) to make it,but an exception came into being:java.lang.IllegalStateException: Already attached.
Here is the code :
/* MainActivity */
public class MainActivity
extends AppCompatActivity
implements View.OnClickListener{
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0x1&&resultCode==RESULT_OK){
onCreate(null); // Upgrade the list
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addItem=(Button)findViewById(R.id.addItem);
addItem.setOnClickListener(this);
.....
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addItem:
Intent intent=new Intent(this,AddItemActivity.class);
startActivityForResult(intent,0x1);
break;
default:
break;
}
}
}
/*AddItemActivity*/
public class AddItemActivity
extends AppCompatActivity
implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
Button submit=(Button)findViewById(R.id.submit);//get submit button
submit.setOnClickListener(this);
....
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.submit:
EditText editName=(EditText)findViewById(R.id.editName),
editAge=(EditText)findViewById(R.id.editAge);
insert(new Person(
editName.getText().toString(),
Integer.parseInt(editAge.getText().toString())));
//return
setResult(RESULT_OK,null);
finish();
break;
default:
break;
}
}
}
stackTrace is this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.sqlitetest/com.example.sqlitetest.MainActivity}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2871)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:317)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.example.sqlitetest.MainActivity.onCreate(MainActivity.java:29)
at com.example.sqlitetest.MainActivity.onActivityResult(MainActivity.java:23)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)

App crashed when arrayAdapter.notifyDataSetChanged() was called

public class Activity_search extends ActionBarActivity {
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mArrayAdapter;
private ArrayList<String> mArrayList;
private boolean isDiscovering;
private AdapterView.OnItemClickListener mClickListener = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView,View view,int position, long id ){
mBtAdapter.cancelDiscovery();
isDiscovering=false;
Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
String tmp1 = ((TextView)view).getText().toString();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_search);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mArrayList = new ArrayList<String>();
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(mClickListener);
}
#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_activity_search, 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);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String tmp=device.getName() + "\n" + device.getAddress();
Context appContext = getApplicationContext();
Toast.makeText(appContext,tmp,Toast.LENGTH_LONG).show();
mArrayList.add(tmp);
mArrayAdapter.notifyDataSetChanged();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Toast.makeText(getApplicationContext(),"Discovery Finished",Toast.LENGTH_SHORT).show();
}
}
};
public void onBtn2Clicked(View view) {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Context appContext = getApplicationContext();
if(!isDiscovering) {
mBtAdapter.startDiscovery();
Toast.makeText(appContext, "Discovery Started", Toast.LENGTH_SHORT).show();
isDiscovering=true;
} else {
mBtAdapter.cancelDiscovery();
Toast.makeText(appContext,"Discovery Canceled",Toast.LENGTH_SHORT).show();
isDiscovering=false;
}
}
public void onDestroy(){
super.onDestroy();
if(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
}
App always crashed when it called the function as mentioned at above, And its error code is
02-13 16:04:47.974 27328-27328/com.skyjohn.nxtrpc E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.skyjohn.nxtrpc.Activity_search$2#41532570
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive(Activity_search.java:90)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
But if i hardcoded mArrayList.add("abc") into the code, the "abc" will appear, but if I do it dynamicly (when I received a new bluetooth device) , the app crashed.
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive
mArrayAdapter is null because creating new object of Adapter in onCreate method with same name which declare as class level.
To fix error use:
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
in onCreate method instead of creating new object of ArrayAdapter.
inside onCreate you are hiding the scope of the class member variable mAdapter, declaring and initialazing it in the local scope of onCreate. The fix is to remove ArrayAdapter<String> from onCreate, leaving only
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);

Android Services

I'm writing a web server for android. Actually it works with threads, but now I would use a service to make it running in background. I replaced the thread with a service, but I don't know if this design is ok...
When I press a button it starts then it stays in listening. When there is a request, the service create a thread to serve it.
This is my structure:
WebServer.java
class WebServer extends Service{
onCreate(){...}
onDestroy(){...}
}
DroidServer.java
class DroidServer extends WebServer{...}
MyActivity.java
MyActivity extends Activity{
boolean isOn=false;
btn.setOnClickListener(new OnClickListener(){
public void onClick(View V){
if(!isOn){
startService(new Intent(this, DroidWebServer.class));
btn.setText("Stop");
}else{
stopService(new Intent(this, DroidWebServer.class));
btn.setText("Start");
}}});
}
AndroidManifest.xml
... <service android:name='DroidWebServer'/> ...
But when I click on the button I get this exception:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to Instantiate service it.giox.ws.DroidWebServer: java.lang.InstantiationException: it.giox.ws.DroidWebServer
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1933)
at android.app.ActivityThread.access$2500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3729)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: it.giox.ws.DroidWebServer
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1409)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1930)
... 10 more
Where's the problem?
Have you seen this post? It basically says there is an error in your constructor. His fix was to remove the argument, and also make sure to call the super's constructor ...
InstantiationException occurs when an exception is thrown out of a
constructor. Generally there should be another exception reported as
causing the InstantiationException, and the stack trace should point
to the specific lines that are in error. Stack trace is your friend,
and you should be grateful -- their are poor children programming on
Symbian devices who have no stack trace.
Did you implement the callback method onStartCommand() in your subclass (either WerServer or DroidServer)? Check out Service.startService() for details.
Personally, I think use the bound form of service is more reasonable in your design, where you can replace a is-a relationship with a has-a relationship.
Your WebServer:
class WebServer implements IWebServer {
doSoming();
}
Your DroidServer:
class DroidServer extends Service {
private WebServer webServer;
private WebServerBinder myBinder;
onCreate(){...}
IBinder onBind(Intent intent) {
return myBinder;
}
onDestroy(){...}
protected class WebServerBinder extends Binder implements IWebServer {
doSomething() {
myServer.doSomething();
}
}
}
In your Activity, use your DroidServer like this:
public class MyActivity extends Activity {
private IWebServer myWebService;
private ServiceConnection myServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myWebService = (IWebServer) service;
}
public void onServiceDisconnected(ComponentName className) {
if (myWebService != null)
myWebService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(this, DroidWebServer.class),
myServiceConnection, Context.BIND_AUTO_CREATE);
boolean isOn=false;
btn.setOnClickListener(new OnClickListener(){
public void onClick(View V){
if(!isOn){
myWebService.doSomething();
btn.setText("Stop");
}else{
myWebService.doSomethingElse(someParam);
btn.setText("Start");
}}});
}
#Override
public void onDestroy() {
super.onDestroy();
unbindService(myServiceConnection );
}
}

Show menu in android on startup

Is there any way to automatically show the menu when an activity starts as it's a list activity which will be blank when it starts for the first time.
Check Following link, It explain how to open and close option menu progamatically
http://kahdev.wordpress.com/2010/03/15/progamatically-open-and-close-an-activitys-option-menu/
I played around with this one and it didn't matter if I put it in onCreate, onStart, onResume, onPostResume it always threw (physical Galaxy S4 # 4.4.2 and Genymotion Galaxy S2 # 2.3.7):
10-23 12:50:22.389 27702-27702/net.twisterrob.debug D/AndroidRuntime﹕ Shutting down VM
10-23 12:50:22.389 27702-27702/net.twisterrob.debug W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e3da0)
10-23 12:50:22.389 27702-27702/net.twisterrob.debug E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.twisterrob.debug, PID: 27702
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.twisterrob.debug/net.twisterrob.android.MyActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
...
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:751)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:278)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:746)
at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:621)
at android.app.Activity.openOptionsMenu(Activity.java:2960)
at net.twisterrob.android.MyActivity.onCreate(MyActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
...
The final solution that worked is:
#Override public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
After the activity has resumed and !isFinishing() it is safe to use openOptionsMenu in any event handler or AsyncTask.onPostExecute.
All you have to do is call either on of these in a listener and you can open or close the menu no problem.
openOptionsMenu();
closeOptionsMenu();
So call it in onCreate.
public class List extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
openOptionsMenu();
}
// Menu Button Stuff
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater Menu = getMenuInflater();
Menu.inflate(R.menu.menu_layout, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menuBack:
finish();
return true;
}
return false;
}
}

Categories