im trying to add records to my sqlite database. If you click "add" a DialogFragment opens. Then when you write some information into the textfield and pick one option in the Spinner it should be added to the sqlite databse. This works if i do it from the main activity. But i only get FC when im trying to fo the same from the DialogFragment.
DialogFragment code:
public class CustomDialogFragment extends DialogFragment {
Spinner spin;
EditText etNumber, etForwardNumber;
Boolean initialDisplay = true;
Database mDB = new Database(getActivity());
Cursor c;
public void DialogFragment(){
// Empty constructor required for DialogFragment
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.activity_dialog, null);
etNumber = (EditText)view.findViewById(R.id.etNumber);
etForwardNumber = (EditText)view.findViewById(R.id.etForwardNumber);
etNumber.setHint("Phone Number");
etForwardNumber.setHint("Forward Number");
etForwardNumber.setVisibility(View.GONE);
spin = (Spinner)view.findViewById(R.id.spOptions);
List<String> list = new ArrayList<String>();
list.add("Block Call");
list.add("Forward Call");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.d("DIALOGFRAGMENT", "Option selected: " + position);
if (position == 0) {
Log.d("LOG_TAG", "Block");
etForwardNumber.setVisibility(View.GONE);
//Log.d("LOG_TAG", initialDisplay.toString());
//initialDisplay = false;
}else {
Log.d("LOG_TAG", "Forward");
etForwardNumber.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
builder.setMessage("")
.setTitle("Add a new number")
.setView(view);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Hide the dialog
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Add records to sqlite database
mDB.open();
String cname = "test";
String caction = "Forward";
//String cnumber = "Numbertoforward";
ContentValues cv = new ContentValues();
cv.put("cName", cname);
cv.put("cAction", caction);
//cv.put("cNumber", cnumber);
mDB.empInsert(cv);
c.requery();
}
});
return builder.create();
}
/*#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the XML view for the help dialog fragment
//View view = inflater.inflate(R.layout.activity_dialog, container);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 2. Chain together various setter methods to set the dialog characteristics
/*builder.setMessage("Test msg")
.setTitle("Title");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});*/
/*return view;
} */
}
Logcat:
10-23 15:06:00.125: E/AndroidRuntime(14935): FATAL EXCEPTION: main
10-23 15:06:00.125: E/AndroidRuntime(14935): java.lang.NullPointerException
10-23 15:06:00.125: E/AndroidRuntime(14935): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
10-23 15:06:00.125: E/AndroidRuntime(14935): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
10-23 15:06:00.125: E/AndroidRuntime(14935): at com.spxc.forwardcalls.Database.open(Database.java:23)
10-23 15:06:00.125: E/AndroidRuntime(14935): at com.spxc.forwardcalls.CustomDialogFragment$3.onClick(CustomDialogFragment.java:90)
10-23 15:06:00.125: E/AndroidRuntime(14935): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
10-23 15:06:00.125: E/AndroidRuntime(14935): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 15:06:00.125: E/AndroidRuntime(14935): at android.os.Looper.loop(Looper.java:137)
10-23 15:06:00.125: E/AndroidRuntime(14935): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 15:06:00.125: E/AndroidRuntime(14935): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 15:06:00.125: E/AndroidRuntime(14935): at java.lang.reflect.Method.invoke(Method.java:525)
10-23 15:06:00.125: E/AndroidRuntime(14935): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 15:06:00.125: E/AndroidRuntime(14935): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 15:06:00.125: E/AndroidRuntime(14935): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:112)
10-23 15:06:00.125: E/AndroidRuntime(14935): at dalvik.system.NativeStart.main(Native Method)
Any help is much appreciated!
It's hard to say at the get go, but it seems your database is not initialised properly. You should move
Database mDB = new Database(getActivity());
to your onCreateDialog method. Moving it here would ensure that getActivity() returns a context to initialise the database with.
Alternatively, I highly recommend having a DatabaseHelper class of some sort that uses a singleton pattern. Therefore, you could access your database from anywhere in your app more flexibly.
Related
When I call .notifyDataSetChanged() in my constructor after I set my ArrayList my app still crashes, the same as when I call it before I call .setAdapter, it's been bothering me for hours, would love any kind of help, thanks!
public class CustomSwipeAdapter extends PagerAdapter {
private ArrayList<String> image_resources = new ArrayList<>();
private Context mContext;
private LayoutInflater mLayoutInflater;
private ImageLoader mImageLoader;
public CustomSwipeAdapter(Context context, ArrayList<String> images){
this.mContext = context;
this.image_resources = images;
}
#Override
public int getCount() {
return image_resources.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View item_view = mLayoutInflater.inflate(R.layout.swipe_layout, container, false);
final ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
if (image_resources.get(position) != null || !image_resources.get(position).isEmpty()) {
mImageLoader.get(image_resources.get(position), new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
imageView.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundColor(Color.CYAN);
}
});
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
super.destroyItem(container, position, object);
}
}
Where I set my Adapter (in my Activity's onCreate()), it's most basic activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
}
Stack Trace:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 4 Pager id: sobmad.com.gamingreminder:id/view_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class sobmad.com.gamingreminder.GamePage.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:967)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChange() //Add this line in your activity
I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)
In my listview there are to feilds,ward number and the date.i want to get these data to new activity when i'am clicking a listview.but in this there is a runtime error and i have no idea to how to fix it.
this is my dashboardActivity.java file,
public class DashboardActivity extends ListActivity implements FetchDataListener{
UserFunctions userFunctions;
Button btnLogout;
TextView resultView;
private ProgressDialog dialog;
//private String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
initView();
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
TextView txtviewWard= (TextView) view.findViewById(R.id.ward_number);
String ward = txtviewWard.getText().toString();
TextView txtviewDate= (TextView) view.findViewById(R.id.date_time);
String dateTime = txtviewDate.getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("ward", ward);
i.putExtra("dateTime", dateTime);
startActivity(i);
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
Intent intent = getIntent();
String email = intent.getStringExtra(LoginActivity.EMAIL);
String url = "http://pubbapp.comze.com/pubapp1.php?email=" + email;
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
this is my SingleListItem.java file,
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtWard = (TextView) findViewById(R.id.ward_number);
TextView txtDate = (TextView) findViewById(R.id.date_time);
Intent i = getIntent();
// getting attached intent data
String wardNumber = i.getStringExtra("ward");
String dateTime = i.getStringExtra("dateTime");
// displaying selected product name
txtWard.setText(wardNumber);
txtDate.setText(dateTime);
}
this is my xml file,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ward_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="wardNumber"
android:textColor="#ffffff"
android:textSize="25dip"
android:textStyle="bold" />
<TextView
android:id="#+id/date_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Date"
android:padding="10dip"
android:textColor="#ffffff"
android:textSize="20dip"
android:textStyle="bold" />
</LinearLayout>
and this is the error in the LogCat,
12-02 19:10:01.100: E/AndroidRuntime(22705): FATAL EXCEPTION: main
12-02 19:10:01.100: E/AndroidRuntime(22705): java.lang.NullPointerException
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.example.androidhive.DashboardActivity$1.onItemClick(DashboardActivity.java:59)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.ListView.performItemClick(ListView.java:3745)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1980)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.handleCallback(Handler.java:587)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Looper.loop(Looper.java:130)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.app.ActivityThread.main(ActivityThread.java:3691)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invokeNative(Native Method)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invoke(Method.java:507)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-02 19:10:01.100: E/AndroidRuntime(22705): at dalvik.system.NativeStart.main(Native Method)
please help me to fix this error.
thank you.
In first activity, pass the data as a bundle using putExtras:
// sending data to new activity
Bundle b = new Bundle();
b.putString("ward", ward);
b.putString("dateTime", dateTime);
i.putExtras(b);
In second activity, retrieve the bundle and parse the data as follows:
Bundle b = getIntent().getExtras();
if (b != null)
{
String wardNumber = b.getString("ward");
String dateTime = b.getString("dateTime");
}
try this....
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//your code
}
});
get data like this in ur second activity:
Bundle b = savedInstanceState.getExtras();
if(b!=null)
{
String ward =b.getString("ward");
String dateTime =b.getString("datetime");
}
bundle is responsible to getexras(),so use this.it worked for me and my other friends.
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
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:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.
I'm trying to get my alertDialog working in an arrayAdapter. This is how my function looks like.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Noodnummers currentNoodnummer = noodnummers.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(layoutResourceId, parent, false);
TextView txt_noodnummer_name = (TextView) rowView.findViewById(R.id.txt_noodnummer_name);
txt_noodnummer_name.setText(currentNoodnummer.naam);
TextView txt_noodnummer_telefoon = (TextView) rowView.findViewById(R.id.txt_noodnummer_telefoon);
txt_noodnummer_telefoon.setText(Html.fromHtml(currentNoodnummer.telefoonNummer));
txt_noodnummer_telefoon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//To change body of implemented methods use File | Settings | File Templates.
try {
new AlertDialog.Builder(this)
.setTitle("")
.setMessage("Bent u zeker dat u" + currentNoodnummer.telefoonNummer + "wilt bellen?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
String uri = currentNoodnummer.telefoonNummer;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
v.getContext().startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (ActivityNotFoundException activityException) {
Log.e("genkonstage", "Call failed", activityException);
}
}
});
return rowView;
}
The first problem is, that new AlertDialog.Builder(this) is given me an error on the word this. Then I found that I maybe should use a context. But when I say new AlertDialog.Builder(context) I get no error but when I click the app crashes.
Can someone help me with this?
EDIT
06-18 10:56:20.689 12980-12980/be.appmax.genkOnStage E/AndroidRuntime: FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at android.app.AlertDialog$Builder.show(AlertDialog.java:951)
at be.appmax.genkOnStage.adapters.NoodnummersArrayAdapter$1.onClick(NoodnummersArrayAdapter.java:57)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Creation of arrayAdapter inside NoodnummersActivity
ListView listView = (ListView) findViewById(R.id.listViewNoodnummers);
//addList(noodnummersArrayList, listView);
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(getBaseContext(), R.layout.noodnummers_list, noodnummersArrayList);
// fill the listview with adapter.
listView.setAdapter(adapter);
setListViewHeightBasedOnChildren(listView);
"Never" use getBaseContext()! From a Google Engineer
Try with NoodnummersActivity.this
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(NoodnummersActivity.this, R.layout.noodnummers_list, noodnummersArrayList);
and then try with
new AlertDialog.Builder(context)
By the way, I suggest at the beginning of your activity to define a private field with the context. I found this suggestion here somewhere and I find it awesome:
public class MyActivity extends Activity {
private Context context = MyActivity.this;
}
in this way you can use "context" without any worries.
Use this method for context:
private Context getDialogContext() {
Context context;
if (getParent() != null)
context = getParent();
else
context = this;
return context;
}
try this it will work.