Android: App crashes at getting text form editText in dialog - java

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.

Related

Why doesn't numberpicker.getvalue() get the return value?

I want to getvalue from my numberpicker, but my numberpicker.getvalue() it's not working.
this is my java
public class MakananIndoVer1 extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_makanan_indo_ver1);
coordinatorLayout = findViewById(R.id.CoordinatorLayout);
final NumberPicker picker = (NumberPicker) findViewById(R.id.number_picker_default);
picker.setMax(15);
picker.setMin(0);
picker.setUnit(1);
picker.setValue(0);
picker.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int value, ActionEnum action) {
Toast.makeText(MakananIndoVer1.this, picker.getValue(), Toast.LENGTH_SHORT).show();
}
});
}
}
and this is my logcat
2019-01-03 17:16:09.006 1563-3245/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1336405 , only wrote 1336320
2019-01-03 17:16:09.009 4907-4907/com.example.denny.prodia D/AndroidRuntime: Shutting down VM
--------- beginning of crash
2019-01-03 17:16:09.079 4907-4907/com.example.denny.prodia E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.denny.prodia, PID: 4907
java.lang.ClassCastException: android.content.res.Resources cannot be cast to java.lang.CharSequence
at com.example.denny.prodia.MakananIndoVer1$1.valueChanged(MakananIndoVer1.java:34)
at com.travijuu.numberpicker.library.NumberPicker.changeValueBy(NumberPicker.java:225)
at com.travijuu.numberpicker.library.NumberPicker.increment(NumberPicker.java:204)
at com.travijuu.numberpicker.library.Listener.ActionListener.onClick(ActionListener.java:40)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
--------- beginning of system
2019-01-03 17:16:09.196 1819-4593/? W/ActivityManager: Force finishing activity com.example.denny.prodia/.MakananIndoVer1
2019-01-03 17:16:09.222 1819-1834/? W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.DROPBOX_ENTRY_ADDED flg=0x10 (has extras) } to com.google.android.gms/.stats.service.DropBoxEntryAddedReceiver
2019-01-03 17:16:09.223 1819-1834/? W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.DROPBOX_ENTRY_ADDED flg=0x10 (has extras) } to com.google.android.gms/.chimera.GmsIntentOperationService$PersistentTrustedReceiver
2019-01-03 17:16:09.227 4907-4907/com.example.denny.prodia I/Process: Sending signal. PID: 4907 SIG: 9
2019-01-03 17:16:09.268 2599-2612/? W/gle.android.gm: Couldn't lock the profile file /data/misc/profiles/cur/0/com.google.android.gms/primary.prof: Failed to lock file '/data/misc/profiles/cur/0/com.google.android.gms/primary.prof': Try again
2019-01-03 17:16:09.268 2599-2612/? W/gle.android.gm: Could not forcefully load profile /data/misc/profiles/cur/0/com.google.android.gms/primary.prof
2019-01-03 17:16:09.291 1819-1895/? W/InputDispatcher: channel '62146ad com.example.denny.prodia/com.example.denny.prodia.MakananIndoVer1 (server)' ~ Consumer closed input channel or an error occurred. events=0x9
2019-01-03 17:16:09.291 1819-1895/? E/InputDispatcher: channel '62146ad com.example.denny.prodia/com.example.denny.prodia.MakananIndoVer1 (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-01-03 17:16:09.291 1819-1895/? W/InputDispatcher: channel 'e7decf7 com.example.denny.prodia/com.example.denny.prodia.MenuMakananUtama (server)' ~ Consumer closed input channel or an error occurred. events=0x9
2019-01-03 17:16:09.291 1819-1895/? E/InputDispatcher: channel 'e7decf7 com.example.denny.prodia/com.example.denny.prodia.MenuMakananUtama (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-01-03 17:16:09.291 1819-1895/? W/InputDispatcher: channel '12dd43d com.example.denny.prodia/com.example.denny.prodia.MakananKhasIndo (server)' ~ Consumer closed input channel or an error occurred. events=0x9
2019-01-03 17:16:09.291 1819-1895/? E/InputDispatcher: channel '12dd43d com.example.denny.prodia/com.example.denny.prodia.MakananKhasIndo (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-01-03 17:16:09.291 1819-1895/? W/InputDispatcher: channel 'eff06b com.example.denny.prodia/com.example.denny.prodia.MenuUtama (server)' ~ Consumer closed input channel or an error occurred. events=0x9
2019-01-03 17:16:09.291 1819-1895/? E/InputDispatcher: channel 'eff06b com.example.denny.prodia/com.example.denny.prodia.MenuUtama (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-01-03 17:16:09.293 1668-1668/? I/Zygote: Process 4907 exited due to signal (9)
in here i want to view the value from my numberpicker. but, i just know my picker.getvalue() is error and break my emulator. i just want to know where i can fix the error.
The method makeText() has several overloads.
You wanted to use this:
public static Toast makeText(Context context, CharSequence text, #Duration int duration) {
return makeText(context, null, text, duration);
}
but because you passed picker.getValue() which is an integer value,
the compiler used this:
public static Toast makeText(Context context, #StringRes int resId, #Duration int duration)
throws Resources.NotFoundException {
return makeText(context, context.getResources().getText(resId), duration);
}
which as you can see takes as 2nd parameter an integer, but this integer is interpreted as a resource id.
So the app crashes because there is no resource id with the value picker.getValue().
You only have to make that 2nd parameter you pass to be a String:
Toast.makeText(MakananIndoVer1.this, String.ValueOf(picker.getValue()), Toast.LENGTH_SHORT).show();
or
Toast.makeText(MakananIndoVer1.this, "" + picker.getValue(), Toast.LENGTH_SHORT).show();
i tried on my own and i found the problem.
Toast is expecting for another kind of value, you can fix it up with:
Toast.makeText(MakananIndoVer1.this, String.ValueOf(picker.getValue()), Toast.LENGTH_SHORT).show();
and here is my code with a working numberpicker:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final NumberPicker picker = (NumberPicker) findViewById(R.id.number_picker_default);
picker.setMaxValue(15);
picker.setMinValue(0);
picker.setValue(0);
picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
Toast.makeText(MainActivity.this, String.valueOf(picker.getValue()), Toast.LENGTH_SHORT).show();
}
});
}
However, if you check the logcat, there's wrote : java.lang.ClassCastException: android.content.res.Resources cannot be cast to java.lang.CharSequence. And you can easily find the problem, hope that helps for future problems, have a good luck and keep coding :)

Android - Bluetooth - Crash at the end of write

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

Why does my app shut down if i use service android?

I'm trying to make a simple audio player. When I create it in the main activity without service, it works correctly, music is playing (it works if I press power button to turn off the screen) and this is still working correctly after turn on the screen. But if I use service for playing music in the background, my app shuts down when I press power button for turn on the screen.
public class MainActivity extends AppCompatActivity {
static ArrayList<HashMap<String, Object>> listSongs = new ArrayList<>();
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listSongs = getAllMusicInfo();
intent = new Intent(this, BackgroundPlayer.class);
Button buttonStart = (Button) findViewById(R.id.startService);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(intent);
Toast.makeText(MainActivity.this, "It's started", Toast.LENGTH_SHORT).show();
}
});
Button buttonStop = (Button) findViewById(R.id.StopService);
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(intent);
Toast.makeText(MainActivity.this, "It's stopped", Toast.LENGTH_SHORT).show();
}
});
}
public class BackgroundPlayer extends Service implements MediaPlayer.OnCompletionListener {
MediaPlayer player;
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
try {
player.setDataSource((String) MainActivity.listSongs.get(0).get("path"));
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
#Override
public void onCompletion(MediaPlayer mp) {}
}
06-05 09:58:54.206 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer: start
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: message received msg=6, ext1=0, ext2=0
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: Received MEDIA_STARTED
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: callback application
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: back from callback
06-05 09:58:54.236 31873-31873/com.vitaliylevashov.serviceplayer I/MediaPlayer: Don't send intent. msg.arg1 = 0, msg.arg2 = 0
06-05 09:58:54.236 31873-31873/com.vitaliylevashov.serviceplayer E/MediaPlayer: Should have subtitle controller already set
06-05 09:58:54.256 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer-JNI: getCurrentPosition: 192 (msec)
06-05 09:58:54.256 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer-JNI: isPlaying: 1
<<
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer D/AndroidRuntime: Shutting down VM
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41660bc0)
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vitaliylevashov.serviceplayer, PID: 31873
android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:64)
at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:133)
at android.database.CursorWrapper.requery(CursorWrapper.java:186)
at android.app.Activity.performRestart(Activity.java:5346)
at android.app.ActivityThread.handleSleeping(ActivityThread.java:3487)
at android.app.ActivityThread.access$3000(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
add a service tag in Manifest ,may be you havent added that in manifest
<service android:name=".MyService" />
request to post error log/logcat

I can't Toast variable value in setOnClickListener()

I want to show variable value from imageAndTexts1.get(position).getUrl() in setOnClickListener().
This is my code
public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
List<RssFeedStructure> imageAndTexts1 = null;
public RssReaderListAdapter(Activity activity,
List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView
.findViewById(R.id.feed_updatetime);
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
try {
Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
+ imageAndTexts1.get(position).getImgLink() + " :: "
+ imageAndTexts1.get(position).getTitle()+ " :: "
+ imageAndTexts1.get(position).getUrl());
textView.setText(imageAndTexts1.get(position).getTitle());
SpannableString content = new SpannableString(imageAndTexts1.get(
position).getPubDate());
content.setSpan(new UnderlineSpan(), 0, 13, 0);
timeFeedText.setText(content);
textView.setOnClickListener(new View.OnClickListener() {
private Activity context;
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), imageAndTexts1.get(position).getUrl().toString(), Toast.LENGTH_SHORT).show();
/* String url = imageAndTexts1.get(position).getUrl().toString();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i); */
}
});
when I run this code it can show text from Log.d(). But when I click textView in Emulator it show error like this.
07-02 09:49:10.844: E/AndroidRuntime(968): FATAL EXCEPTION: main
07-02 09:49:10.844: E/AndroidRuntime(968): java.lang.NullPointerException
07-02 09:49:10.844: E/AndroidRuntime(968): at com.amit.adapter.RssReaderListAdapter$1.onClick(RssReaderListAdapter.java:84)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.view.View.performClick(View.java:4204)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.view.View$PerformClick.run(View.java:17355)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.os.Handler.handleCallback(Handler.java:725)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.os.Handler.dispatchMessage(Handler.java:92)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.os.Looper.loop(Looper.java:137)
07-02 09:49:10.844: E/AndroidRuntime(968): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-02 09:49:10.844: E/AndroidRuntime(968): at java.lang.reflect.Method.invokeNative(Native Method)
07-02 09:49:10.844: E/AndroidRuntime(968): at java.lang.reflect.Method.invoke(Method.java:511)
07-02 09:49:10.844: E/AndroidRuntime(968): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-02 09:49:10.844: E/AndroidRuntime(968): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-02 09:49:10.844: E/AndroidRuntime(968): at dalvik.system.NativeStart.main(Native Method)
In log.d() it can show text without error. But in setOnClickListener() when I click text in list it show NullPointerException. please help me.
You are using context, which is going to be null at this point since you don't assign to it.
You should be able to use activity from the getview method. i.e replace context in your listener with activity.
private Activity context;
is your problem, that is already null.
Use instead YourActivityName.this inside your Toast.
Activity testActivity; add this line below List<RssFeedStructure> imageAndTexts1 = null;
then initialize this in your constructor.
public RssReaderListAdapter(Activity activity,
List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
testActivity=activity; // Newly added
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
Now you can use the Toast message like this,
Toast.makeText(testActivity, imageAndTexts1.get(position).getUrl().toString(), Toast.LENGTH_SHORT).show();
Use this code.
Toast.makeText(ActivityName.this, ""+imageAndTexts1.get(position).getUrl().toString(), Toast.LENGTH_SHORT).show();
first Change is ActivityName.this
and second is : ""+imageAndTexts1.get(position).getUrl().toString()
problem in ur code is u r using getActivityContext() which cause problem sometimes... instead use
Toast.makeText(UrActivity.this; "UrlValue is" + imageAndTexts1.get(position).getUrl(), 3000).show();

Android Custom Carrier Label nullpointerexception

I've added AOKP's Custom Carrier Label options to my rom and everything works with the exception of getting a Settings fc when OK is clicked in the dialog window...The customlabeltextsummary is updated correctly and the carrier is changed as it should be...
Settings.java :
package com.android.settings.cyanogenmod;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.view.IWindowManager;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.provider.Settings;
import android.text.Spannable;
import android.util.Log;
import android.view.IWindowManager;
import android.view.Display;
import android.view.LayoutInflater;
import android.widget.EditText;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SystemSettings extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener{
private static final String TAG = "SystemSettings";
private static final String KEY_POWER_BUTTON_TORCH = "power_button_torch";
private CheckBoxPreference mPowerButtonTorch;
private static final String KEY_CHRONUS = "chronus";
private static final String PREF_FORCE_DUAL_PANEL = "force_dualpanel";
private static final String PREF_CUSTOM_CARRIER_LABEL = "custom_carrier_label";
Preference mCustomLabel;
Context mContext;
String mCustomLabelText = null;
CheckBoxPreference mDualpane;
private boolean torchSupported() {
return getResources().getBoolean(R.bool.has_led_flash);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.system_settings);
mCustomLabel = findPreference(PREF_CUSTOM_CARRIER_LABEL);
updateCustomLabelTextSummary();
// Dont display the lock clock preference if its not installed
removePreferenceIfPackageNotInstalled(findPreference(KEY_CHRONUS));
mPowerButtonTorch = (CheckBoxPreference) findPreference(KEY_POWER_BUTTON_TORCH);
if (torchSupported()) {
mPowerButtonTorch.setChecked((Settings.System.getInt(getActivity().
getApplicationContext().getContentResolver(),
Settings.System.POWER_BUTTON_TORCH, 0) == 1));
} else {
getPreferenceScreen().removePreference(mPowerButtonTorch);
}
mDualpane = (CheckBoxPreference) findPreference(PREF_FORCE_DUAL_PANEL);
mDualpane.setOnPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mPowerButtonTorch) {
boolean enabled = mPowerButtonTorch.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.POWER_BUTTON_TORCH,
enabled ? 1 : 0);
return true;
} else if (preference == mCustomLabel) {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.custom_carrier_label_title);
alert.setMessage(R.string.custom_carrier_label_explain);
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(mCustomLabelText != null ? mCustomLabelText : "");
alert.setView(input);
alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = ((Spannable) input.getText()).toString();
Settings.System.putString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL, value);
updateCustomLabelTextSummary();
Intent i = new Intent();
i.setAction("com.android.settings.LABEL_CHANGED");
mContext.sendBroadcast(i);
}
});
alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
ContentResolver cr = getActivity().getContentResolver();
if (preference == mDualpane) {
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.FORCE_DUAL_PANEL,
((CheckBoxPreference)preference).isChecked() ? 0 : 1);
return true;
}
return false;
}
private boolean removePreferenceIfPackageNotInstalled(Preference preference) {
String intentUri=((PreferenceScreen) preference).getIntent().toUri(1);
Pattern pattern = Pattern.compile("component=([^/]+)/");
Matcher matcher = pattern.matcher(intentUri);
String packageName=matcher.find()?matcher.group(1):null;
if(packageName != null) {
try {
getPackageManager().getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
Log.e(TAG,"package "+packageName+" not installed, hiding preference.");
getPreferenceScreen().removePreference(preference);
return true;
}
}
return false;
}
private void updateCustomLabelTextSummary() {
mCustomLabelText = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.CUSTOM_CARRIER_LABEL);
if (mCustomLabelText == null || mCustomLabelText.length() == 0) {
mCustomLabel.setSummary(R.string.custom_carrier_label_notset);
} else {
mCustomLabel.setSummary(mCustomLabelText);
}
}
}
logcat :
W/System.err(13551): Removed 2131231241
W/System.err(13551): Removed 2131231255
D/dalvikvm( 3528): GC_CONCURRENT freed 384K, 16% free 2993K/3552K, paused 2ms+4ms, total 33ms
D/dalvikvm(13551): GC_CONCURRENT freed 190K, 10% free 3282K/3644K, paused 2ms+8ms, total 37ms
D/AndroidRuntime(13551): Shutting down VM
W/dalvikvm(13551): threadid=1: thread exiting with uncaught exception (group=0x40d12600)
E/AndroidRuntime(13551): FATAL EXCEPTION: main
E/AndroidRuntime(13551): java.lang.NullPointerException
E/AndroidRuntime(13551): at com.android.settings.cyanogenmod.SystemSettings$1.onClick(SystemSettings.java:143)
E/AndroidRuntime(13551): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
E/AndroidRuntime(13551): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13551): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(13551): at android.app.ActivityThread.main(ActivityThread.java:5191)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13551): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
E/AndroidRuntime(13551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
E/AndroidRuntime(13551): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 1108): Force finishing activity com.android.settings/.SubSettings
W/ActivityManager( 1108): Activity pause timeout for ActivityRecord{40ff74b8 u0 com.android.settings/.SubSettings}
D/dalvikvm(13124): GC_FOR_ALLOC freed 411K, 22% free 3616K/4608K, paused 28ms, total 34ms
I/Process (13551): Sending signal. PID: 13551 SIG: 9
W/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
I/WindowState( 1108): WIN DEATH: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings}
I/ActivityManager( 1108): Process com.android.settings (pid 13551) has died.
E/InputDispatcher( 1108): channel '41188140 com.android.settings/com.android.settings.SubSettings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Consumer closed input channel or an error occurred. events=0x9
E/InputDispatcher( 1108): channel '40ffd998 com.android.settings/com.android.settings.Settings (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '41188140 com.android.settings/com.android.settings.SubSettings (server)'
W/InputDispatcher( 1108): Attempted to unregister already unregistered input channel '40ffd998 com.android.settings/com.android.settings.Settings (server)'
I/WindowState( 1108): WIN DEATH: Window{41188140 u0 com.android.settings/com.android.settings.SubSettings}
I/WindowState( 1108): WIN DEATH: Window{40ffd998 u0 com.android.settings/com.android.settings.Settings}
I/ActivityManager( 1108): Start proc com.android.settings for activity com.android.settings/.Settings: pid=13575 uid=1000 gids={41000, 1015, 1028, 3002, 3001, 3003, 3007}
W/WindowManager( 1108): Rebuild removed 7 windows but added 6
W/WindowManager( 1108): This window was lost: Window{41369d90 u0 com.android.settings/com.android.settings.SubSettings EXITING}
W/WindowManager( 1108): mDisplayId=0 mSession=Session{41e7d3b0 13551:1000} mClient=android.os.BinderProxy#4108dde8
line 143 is as follows :
mContext.sendBroadcast(i);
anyone got an idea whats going on here?
mContext is null, since it is declared at the top of your class, but never given anything to hold.
You could probably use getActivity() in place of mContext since this is a Fragment and Activity is a Context subclass.
This means
mContext.sendBroadcast(i);
should be
getActivity().sendBroadcast(i);

Categories