I am new to android, and I'm basically sending a simple byte stream between two devices.
It seems by adding the additional activity (a confirmation button on a second layout) I have introduced some underlying complexity, and I can't pin-point why the crash AFTER the transmission. The message is transmitted on the input stream, and received on the output stream, but the logs seem to indicate a broken pipe, despite a transmission occurring.
I have tried to ensure that the java class for the 'confirm page' inherits the BT capability from the 'main'.
I suspect the error is in MainActivity, and it is upon returning from the confirmation screen that this error happens.
*What happens is that I have a new activity, with a corresponding button, to confirm the start process. Once confirmed, the BT should send a start signal, and return to the main layout
This is where I suspect the error is localized.
MainActivity class
public void OnStartClick(View view) {
Intent GetStartConfirmation = new Intent(this, StartConfirm.class);
final int res = 99; // can use as a signal for another time
startActivityForResult(GetStartConfirmation, res);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
startPaintbot = resultCode;
updateUi(resultCode);
}
private void updateUi(int res)
{
if(res == 1) {
//this should all be done on a result of '1'
char data[] = {'s', 't', 'a', 'r', 't', 'u', 'p'};
String str = new String(data);
byte[] bytes = str.getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
else if (res == 0)
{
char data[] = {'s', 'u', 'p','p'};
String str = new String(data);
byte[] bytes = str.getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
else
{
char data[] = {'s', 'y', 'w','a'};
String str = new String(data);
byte[] bytes = str.getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
}
StartConfirm class
public class StartConfirm extends MainActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_confirm_layout);
Intent activityStartHome = getIntent();
}
public void OnStartConfirmation(View view) {
// Vid 5, Derek
Intent toStart = new Intent();
// this is where the difficulties lie, the intents.
setResult(1, toStart);
finish(); // eventually will need to add something to these two intents
}
public void OnNoStartConfirmation(View view) {
Intent DoNotStart = new Intent();
setResult(0, DoNotStart);
//Do not want canceled, indicates there was a failure on the button
finish();
}
}
The output log is as follows:
04-12 02:59:33.379 15665-15665/com.example.piotr.userinterface D/BluetoothConnectionServ: write: Write Called.
write: Writing to outputstream: startup
04-12 02:59:33.379 15665-15665/com.example.piotr.userinterface D/BluetoothConnectionServ: write: Write Called.
write: Writing to outputstream: startup
04-12 02:59:33.379 15665-15665/com.example.piotr.userinterface E/BluetoothConnectionServ: write: Error writing to output stream. Broken pipe
04-12 02:59:33.449 15665-15680/com.example.piotr.userinterface D/OpenGLRenderer: endAllActiveAnimators on 0x9f355d80 (RippleDrawable) with handle 0x9f42c370
04-12 02:59:33.459 15665-15665/com.example.piotr.userinterface I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#8eaf228 time:88717553
04-12 02:59:33.699 15665-15665/com.example.piotr.userinterface D/MainActivity: onDestroy: called.
04-12 02:59:33.699 15665-15665/com.example.piotr.userinterface D/AndroidRuntime: Shutting down VM
04-12 02:59:33.699 15665-15665/com.example.piotr.userinterface E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.piotr.userinterface, PID: 15665
java.lang.RuntimeException: Unable to destroy activity {com.example.piotr.userinterface/com.example.piotr.userinterface.StartConfirm}: java.lang.IllegalArgumentException: Receiver not registered: com.example.piotr.userinterface.MainActivity$1#dadacf9
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5061)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5084)
at android.app.ActivityThread.access$1700(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1853)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.piotr.userinterface.MainActivity$1#dadacf9
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:878)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1283)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:601)
at com.example.piotr.userinterface.MainActivity.onDestroy(MainActivity.java:217)
at android.app.Activity.performDestroy(Activity.java:7102)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1170)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5039)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5084)
at android.app.ActivityThread.access$1700(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1853)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 02:59:36.049 15665-15665/com.example.piotr.userinterface I/Process: Sending signal. PID: 15665 SIG: 9
Apologies if that is disgusting
https://github.com/PK-GH/PB/tree/PeteInWonderland/app/src/main/java/com/example/piotr/userinterface
Your device which receiving data is disconected with device sending that's why broken pipe appered.
That appere only when 1 side of connection is broken can't know which but in this case i thing is receiver becouse of
java.lang.RuntimeException: Unable to destroy activity {com.example.piotr.userinterface/com.example.piotr.userinterface.StartConfirm}: java.lang.IllegalArgumentException: Receiver not registered: com.example.piotr.userinterface.MainActivity$1#dadacf9
My advice check connection is it connected before and if yes debug step by step and find place where disconecting
Related
I am new to android studio and I am trying to build a Notepad app.
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String title = findViewById(R.id.textView3).toString();
String note_content = findViewById(R.id.textView).toString();
FileOutputStream outputStream;
try
{
outputStream = openFileOutput(title, Context.MODE_PRIVATE);
outputStream.write(note_content.getBytes());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
MainActivity mainActivity = new MainActivity(title);
}
});
This is the button a user clicks to save the note. Once the code saves the note, it should send the Title to MainActivity so that it can be sent to Recycleview Adapter - this will display it in viewholder as a text.
Presently, when I run the code, it crashes - however, when I remove the constructor, the app works fine.
( MainActivity mainActivity = new MainActivity(title);)
Error:
10-02 02:39:13.822 27279-27279/? D/AndroidRuntime: Shutting down VM
10-02 02:39:13.824 27279-27279/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quicknote, PID: 27279
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.quicknote/com.example.quicknote.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-02 02:39:20.081 27279-27279/com.example.quicknote I/Process: Sending signal. PID: 27279 SIG: 9
As per the error message:
java.lang.InstantiationException: java.lang.Class has no zero argument constructor
A zero argument constructor is required for the Android system to instantiate an Activity. You should never be manually calling an Activity constructor yourself since only the system can properly create an Activity.
The Parcelables and Bundles documentation details the correct way of sending information to an Activity using the extras Bundle.
Unable to instantiate activity. Because you can't start an activity like this. You have to use intent to start activity. To sent "title" use intent extra.
Intent intent=new Intent(CurrentActivity.this, NewActivty.this);
intent.putExtra("title", title);
startActivty(intent);
Is your Activity in your AndroidManifest.xml?
If it is, you have to retrieve the title from your extras from onCreate() of MainActivity instead from the constructor.
Something like that:
//that code instead of your MainActivity mainActivity = new MainActivity(title); line
Intent intent = new Intent(YourActualActivity.this, MainActivity.class);
intent.putExtra("title", title);
startActivity(intent);
//That code in the onCreate method of your MainActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString("title");
}
I have a AsyncTask in a Service. I send an ArrayList as broadcast from the AsyncTask.
When I get the ArrayList in onReceive() I get a NullpointerException.
This is how I send the ArrayList.
transits_list = new ArrayList<Transit>();
transits_list.add(trs);
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
The Transit class implements Serializable.
Receiving the ArrayList
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}
I get NullpointerException in this line:
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
The exception from log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=arrayList flg=0x10 } in com.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver#42003268
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:5391)
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.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver.onReceive(AvccActivity.java:271)
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:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
Your method of getting the Intent is incorrect. I believe your BroadcastReceiver is in an activity class since, you are calling getIntent(). However, getIntent() will get you the Intent supplied to the activity and not the receiver. The Intent for receiver is provided to the method onReceive() itself. Make the following changes to your code:
Adding extra:
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
Getting Extra:
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = intent.getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
// System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}
I'm getting the error 'Attempt to invoke method '...' on a null object reference' on Android when trying to access a field which was set previously.
I check upon setting it that it's not null, but when it's accessed in a different activity, it 'null'.
This field is created along with multiple others' and for some reason, it's the only one which appear to old a null reference.
Object in question
public enum Locations {
Meeting_Room,Office_245,Lobby,NOC,VPsoffice
}
Class declaration:
public class Task implements Serializable {
private long taskId;
private String description;
private Boolean completed = false;
private Category task_catg;
private Task_Status task_sts;
private Locations tsk_location;
}
public Locations getTsk_location() {
return tsk_location;
}
public void setTsk_location(Locations tsk_location) {
this.tsk_location = tsk_location;
}
Please note that Task_Status & Category are also enums, and I do not encounter any issues with them.
This is where the object is initialized, I've added prints here and saw that the value returned from the activity is not null.
New Task activity
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK) {
switch (requestCode) {
case ACTIVITY_SELECT_LOCATION:
{
/*returned_selc_loc = (Locations) data.getSerializableExtra("location");
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);*/
switch(Globals.temp)
{
case 0:
returned_selc_loc=Locations.Meeting_Room;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 1:
returned_selc_loc=Locations.Office_245;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 2:
returned_selc_loc=Locations.Lobby;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 3:
returned_selc_loc=Locations.NOC;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 4:
returned_selc_loc=Locations.VPsoffice;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
}
break;
}
default:
break;
}
}
}
This is where the Task object is created and the Location is set:
New Task activity
public void addTaskBtn (View view)
{
boolean state=true;
EditText desc = (EditText)findViewById(R.id.newTaskDesc);
EditText date = (EditText)findViewById(R.id.taskDateEdit);
EditText time = (EditText)findViewById(R.id.taskTimeEdit);
loc = (EditText)findViewById(R.id.taskLocation);
Date myDate = null;
RadioButton rb;
String emp_name;
t = new Task(desc.getText().toString());
t.setTask_sts(Task_Status.WAITING);
int position = spin.getSelectedItemPosition();
switch(position)
{
case 0:
t.setTask_catg(Category.GENERAL);
break;
case 1:
t.setTask_catg(Category.CLEANING);
break;
case 2:
t.setTask_catg(Category.ELECTRICITY);
break;
case 3:
t.setTask_catg(Category.COMPUTERS);
break;
case 4:
t.setTask_catg(Category.OTHER);
break;
}
//Added prints here and value is set correctly, definitely not NULL.
t.setTsk_location(returned_selc_loc);
t.setTaskId(task_id);
task_id++;
Intent returnIntent = new Intent();
dbm = DBManager.getInstance(this);
long seq_tsk_id = dbm.addTask(t);
t.setTaskId(seq_tsk_id);
returnIntent.putExtra("task", t);
setResult(RESULT_OK, returnIntent);
finish();
}
This is the call to the Edit Task activity, the call is from the MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbM = DBManager.getInstance(context);
itemList = dbM.getAllTasks();
list.setAdapter(new TaskItemAdapter(context, itemList));
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long arg3) {
//get item instance from list
Task tt = (Task) ((TaskItemAdapter) parent.getAdapter()).getItem(position);
if(true)
{
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), EditTaskActivity.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_UPDATE_TASK);
}
return false;
}
});
}
Edit Task activity
This is I get the error (left only relevant part, as other variables in the object are successfully,
public void deleteTaskBtn(View view)
{
Intent returnIntent = new Intent(this,MainActivity.class);
Intent i = getIntent();
tastToEdit = (Task)i.getSerializableExtra("task");
tastToEdit.setToDelete(true);
ParseObject parse_task = new ParseObject("Task");
parse_task.put("Description",tastToEdit.getDescription());
parse_task.put("DueDate",tastToEdit.getDueDate());
parse_task.put("Priority",tastToEdit.getPriority().ordinal());
int com_state = (tastToEdit.getCompleted()) ? 1 : 0;
parse_task.put("IsCompleted",com_state);
parse_task.put("Location", tastToEdit.getTsk_location().ordinal());
parse_task.put("Category",tastToEdit.getTask_catg().ordinal());
parse_task.put("Status", tastToEdit.getTask_sts().ordinal());
parse_task.put("TeamName",Globals.team_name);
parse_task.put("Employee",tastToEdit.getEmp_name());
parse_task.deleteInBackground(new DeleteCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("msg","deleted");
} else {
Log.d("msg", "not deleted");
e.printStackTrace();
}
}
});
returnIntent.putExtra("task",tastToEdit);
setResult(RESULT_OK, returnIntent);
finish();
}
This line returns that NULL reference:
Location selected_loc = tastToEdit.getTsk_location();
Full error stack
03-09 21:28:20.192 10425-10425/? I/art: Late-enabling -Xcheck:jni
03-09 21:28:20.229 10425-10433/? I/art: Debugger is no longer active
03-09 21:28:20.240 10425-10425/? W/System: ClassLoader referenced unknown path: /data/app/il.ac.shenkar.david.todolistex2-1/lib/arm
03-09 21:28:20.446 10425-10456/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-09 21:28:20.508 10425-10456/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
03-09 21:28:20.511 10425-10456/? I/OpenGLRenderer: Initialized EGL, version 1.4
03-09 21:28:27.832 10425-10425/il.ac.shenkar.david.todolistex2 I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
03-09 21:28:28.397 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb38ccf80 (RippleDrawable) with handle 0xaef7fe30
03-09 21:28:29.620 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39ba400 (RippleDrawable) with handle 0xaef7f9e0
03-09 21:28:30.360 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb397f900 (RippleDrawable) with handle 0xb3b29370
03-09 21:28:32.921 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cbb80 (ListPopupWindow$DropDownListView) with handle 0xb3b29530
03-09 21:28:33.437 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cad80 (RippleDrawable) with handle 0xb3b295d0
03-09 21:28:40.866 10425-10456/il.ac.shenkar.david.todolistex2 V/RenderScript: 0x9dca9000 Launching thread(s), CPUs 4
03-09 21:28:40.907 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb3947700 (RippleDrawable) with handle 0xb3b29910
03-09 21:28:44.971 10425-10425/il.ac.shenkar.david.todolistex2 W/sdas: null
03-09 21:28:45.143 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39b5380 (ListView) with handle 0xaef7f510
03-09 21:28:48.110 10425-10425/il.ac.shenkar.david.todolistex2 D/AndroidRuntime: Shutting down VM
03-09 21:28:48.111 10425-10425/il.ac.shenkar.david.todolistex2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: il.ac.shenkar.david.todolistex2, PID: 10425
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:278)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
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.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
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.NullPointerException: Attempt to invoke virtual method 'int il.ac.shenkar.david.todolistex2.Location.ordinal()' on a null object reference
at il.ac.shenkar.david.todolistex2.EditTaskActivity.deleteTaskBtn(EditTaskActivity.java:372)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
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)
But as you can see, this field is set successfully previously, in another activity.
What can be the cause?
It looks to me that it's not about whether or not the field has been set, but rather the object you are trying to pull off the intent isn't there on this line in the onCreate:
tastToEdit = (Task)i.getSerializableExtra("task");
Add a check after this to see whether tastToEdit is null, and if so investigate why it hasn't been properly added to the intent if this is the case.
It looks like you're mistaken about what happens to the intent that you populated in one Activity's onActivityResult(). That method is responsible for handling the result of the next activity which was invoked with startActivityForResult(). That next activity can set a result for the prior activity using setResult(), which becomes available in onActivityResult() when the invoked activity finish.
However it looks like you're expecting getIntent() in "a different activity" to be able to see that Intent you created in onActivityResult(). That's simply not the case. getIntent() returns the activity that was used to start the current activity that you're working with. It's completely unrelated the intent from an activity result. So you'll need to change your strategy for passing data around between these activities.
I am trying to encrypt/decrypt a file from my virtual device (Genymotion). I will show you the code and the exceptions that i have. I guess that the nullPointerException comes from the line where i declare View v = null in onActivityResult method but i do not know how to fix it.
Exceptions
07-22 13:34:10.241 10419-10419/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: application.nikola.com.encryptdecrypt, PID: 10419
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=file:///storage/emulated/0/nikola.txt }} to activity {application.nikola.com.encryptdecrypt/application.nikola.com.encryptdecrypt.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getId()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
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.view.View.getId()' on a null object reference
at application.nikola.com.encryptdecrypt.MainActivity.onActivityResult(MainActivity.java:70)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
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)
07-22 13:34:10.263 765-1598/? W/ActivityManager﹕ Force finishing activity application.nikola.com.encryptdecrypt/.MainActivity
07-22 13:34:10.350 765-1598/? E/ActivityManager﹕ Invalid thumbnail dimensions: 576x576
07-22 13:34:10.400 765-2035/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
07-22 13:34:10.466 765-2035/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
07-22 13:34:10.466 765-2035/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x9ea263c0, error=EGL_SUCCESS
07-22 13:34:10.903 765-786/? W/ActivityManager﹕ Activity pause timeout for ActivityRecord{2ef175ff u0 application.nikola.com.encryptdecrypt/.MainActivity t26 f}
07-22 13:34:11.032 1006-1265/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
07-22 13:34:11.033 1006-1265/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa095a020, error=EGL_SUCCESS
07-22 13:34:11.786 2640-2640/? I/art﹕ Explicit concurrent mark sweep GC freed 3007(201KB) AllocSpace objects, 0(0B) LOS objects, 24% free, 16MB/21MB, paused 301us total 21.960ms
07-22 13:34:11.808 2640-2640/? I/art﹕ Explicit concurrent mark sweep GC freed 3080(224KB) AllocSpace objects, 4(252KB) LOS objects, 24% free, 15MB/21MB, paused 173us total 7.668ms
07-22 13:34:11.822 2640-2640/? I/art﹕ Explicit concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 24% free, 15MB/21MB, paused 237us total 13.937ms
07-22 13:34:12.735 10419-10419/? I/Process﹕ Sending signal. PID: 10419 SIG: 9
07-22 13:34:12.738 765-823/? W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
07-22 13:34:12.764 765-805/? W/InputDispatcher﹕ channel '25d12a93 application.nikola.com.encryptdecrypt/application.nikola.com.encryptdecrypt.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-22 13:34:12.764 765-805/? E/InputDispatcher﹕ channel '25d12a93 application.nikola.com.encryptdecrypt/application.nikola.com.encryptdecrypt.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
07-22 13:34:12.777 765-782/? I/ActivityManager﹕ Process application.nikola.com.encryptdecrypt (pid 10419) has died
07-22 13:34:12.778 765-981/? I/WindowState﹕ WIN DEATH: Window{25d12a93 u0 application.nikola.com.encryptdecrypt/application.nikola.com.encryptdecrypt.MainActivity}
07-22 13:34:12.778 765-981/? W/InputDispatcher﹕ Attempted to unregister already unregistered input channel '25d12a93 application.nikola.com.encryptdecrypt/application.nikola.com.encryptdecrypt.MainActivity (server)'
MainActivity
public class MainActivity extends Activity implements View.OnClickListener {
Button btnEncrypt;
Button btnDecrypt;
final int ACTIVITY_CHOOSE_FILE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnEncrypt = (Button) this.findViewById(R.id.btnActivity1);
btnEncrypt.setOnClickListener(this);
btnDecrypt = (Button) this.findViewById(R.id.btnActivity2);
btnDecrypt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file*//*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EncryptDecrypt crypto = new EncryptDecrypt();
View v = null;
String filePath = null;
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
filePath = uri.getPath();
switch(v.getId()) {
case R.id.btnActivity1:
crypto.encryptor(filePath);
break;
case R.id.btnActivity2:
crypto.decryptor(filePath);
break;
}
}
}
}
}
}
This is is the encrypt/decrypt algorithm that i use.
public class EncryptDecrypt {
public void encryptor(String inputFilePath) {
FileOutputStream fos = null;
File file = new File(inputFilePath);
String keyString = "140405PX_0.$88";
String algorithm = "DESede";
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] fileByteArray = new byte[fileInputStream.available()];
fileInputStream.read(fileByteArray);
for (byte b : fileByteArray) {
System.out.println(b);
}
SecretKey secretKey = getKey(keyString);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new CipherOutputStream(new FileOutputStream("encrypt.file"), cipher));
objectOutputStream.writeObject(fileByteArray);
objectOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void decryptor(String inputFilePath) {
String outputFilePath = "decrypt.txt";
String keyString = "140405PX_0.$88";
String algorithm = "DESede";
try {
File inputFileNAme = new File(inputFilePath);
FileInputStream fileInputStream = new FileInputStream(inputFileNAme);
FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
SecretKey secretKey = getKey(keyString);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
ObjectInputStream objectInputStream = new ObjectInputStream(new CipherInputStream(fileInputStream, cipher));
System.out.println(objectInputStream.available());
fileOutputStream.write((byte[]) objectInputStream.readObject());
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
objectInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static SecretKey getKey(String message) throws Exception {
String messageToUpperCase = message.toUpperCase();
byte[] digestOfPassword = messageToUpperCase.getBytes();
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
return key;
}
}
View v = null; // v is null
String filePath = null;
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
filePath = uri.getPath();
switch(v.getId()) { // v is still null
case R.id.btnActivity1:
crypto.encryptor(filePath);
break;
case R.id.btnActivity2:
crypto.decryptor(filePath);
break;
}
}
}
}
your vis null and you are trying to do v.getId(). That is why you are getting NullPointerException.
In order to fix this, You might want to add a OnClickListener to your btnActivity1 and btnActivity2.
btnActivity1.setOnCLickListerner(new OnClickListener() {
#Override
public void onClick(View arg0) {
crypto.encryptor(filePath);
}
});
}
btnActivity2.setOnCLickListerner(new OnClickListener() {
#Override
public void onClick(View arg0) {
crypto.decryptor(filePath);
}
});
}
In your switch-case of MainActivity, you are using v.getId() but v is initialized to null therefore you are getting NullPointerException
Guessing what you are trying to do is that you are trying to decide whether to decrypt or encrypt the file based on whether two of the buttons in your layout is clicked. But you are not doing it in a proper way. Use OnClickListener for each button and set a boolean flag to check whether to decrypt or encrypt at onClick event of those buttons. Then show your FILE CHOOSER.
You can modify your MainActivity in this way
public class MainActivity extends Activity implements View.OnClickListener {
Button btnEncrypt;
Button btnDecrypt;
boolean encrypt=false;
final int ACTIVITY_CHOOSE_FILE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnEncrypt = (Button) this.findViewById(R.id.btnActivity1);
btnEncrypt.setOnClickListener(this);
btnDecrypt = (Button) this.findViewById(R.id.btnActivity2);
btnDecrypt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnActivity1:
encrypt=true;
break;
case R.id.btnActivity2:
encrypt=false;
break;
}
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file*//*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EncryptDecrypt crypto = new EncryptDecrypt();
String filePath = null;
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
filePath = uri.getPath();
switch(encrypt) {
case true:
crypto.encryptor(filePath);
break;
case false:
crypto.decryptor(filePath);
break;
}
}
}
}
}
}
everytime i press the positive button of the dialog my app crashes with an nullpointerexception but i have no idea what i have to change. i think the problem is caused by the part with getText() because it works when i delete it here:
class newLessonDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.new_lesson_dialog, null))
// Add action buttons,
.setPositiveButton("Speichern", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
{
EditText eF = (EditText)getView().findViewById(R.id.editFach);
fach = eF.getText().toString();
EditText eR = (EditText)getView().findViewById(R.id.editRaum);
raum = eR.getText().toString();
EditText eL = (EditText)getView().findViewById(R.id.editLehrer);
lehrer = eL.getText().toString();
save(fach, raum, lehrer, index);
}
})
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
newLessonDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
and
public static void save(String fach, String raum, String lehrer, int index)
{
BufferedWriter out = null;
try
{
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "fach.txt"));
out.write(fach);
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "raum.txt"));
out.write(raum);
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "lehrer.txt"));
out.write(lehrer);
out.close();
}
catch (Exception e)
{
Toast.makeText(getAppContext(), "Fehler beim Speichern!", Toast.LENGTH_SHORT);
}
}
logcat:
08-13 19:14:07.609 23114-23114/de.nathan.android.droidschool W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41760700)
08-13 19:14:07.619 23114-23114/de.nathan.android.droidschool E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at de.nathan.android.droidschool.MainActivity$fragmentTab1$1$1newLessonDialog$2.onClick(MainActivity.java:267)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
08-13 19:14:07.639 438-6851/? W/ActivityManager: Process de.nathan.android.droidschool has crashed too many times: killing!
08-13 19:14:07.639 438-6851/? W/ActivityManager: Force finishing activity de.nathan.android.droidschool/.MainActivity
08-13 19:14:07.659 438-6851/? I/ActivityManager: Killing proc 23114:de.nathan.android.droidschool/u0a10018: crash
08-13 19:14:07.679 438-551/? W/InputDispatcher: channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
08-13 19:14:07.679 438-551/? E/InputDispatcher: channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-13 19:14:07.679 438-551/? W/InputDispatcher: channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
08-13 19:14:07.679 438-551/? E/InputDispatcher: channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-13 19:14:07.679 438-448/? W/InputDispatcher: Attempted to unregister already unregistered input channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)'
08-13 19:14:07.679 438-449/? W/InputDispatcher: Attempted to unregister already unregistered input channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)'
08-13 19:14:07.679 438-448/? I/WindowState: WIN DEATH: Window{41f4abe8 u0 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity}
08-13 19:14:07.679 438-449/? I/WindowState: WIN DEATH: Window{428f0a50 u0 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity}
Try replacing your getView()s with getDialog().
EditText eF = (EditText)getDialog().findViewById(R.id.editFach);
fach = eF.getText().toString();
EditText eR = (EditText)getDialog().findViewById(R.id.editRaum);
raum = eR.getText().toString();
EditText eL = (EditText)getDialog().findViewById(R.id.editLehrer);
lehrer = eL.getText().toString();
You may as well keep a reference to the original view; it'll make things a lot easier. Try:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.new_lesson_dialog, null);
builder.setView(view)
.setPositiveButton("Speichern", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
EditText eF = (EditText)view.findViewById(R.id.editFach);
...etc.