Android - Nullpointer Exception when clicking a listitem to show AlertDialog - android

I have a listview and when I click on a item it should show a AlertDialog with Radiobuttons in it. But when calling the alertDialog, the app crashes. Logcat gives a NullPointerException. What am I doing wrong?
private void registerClickCallBack() {
ListView list = (ListView) findViewById(R.id.settingsList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
final AlertDialog levelDialog
final CharSequence[] items = { " Easy ", " Medium ",
" Hard ", " Very Hard " };
AlertDialog.Builder builder = new AlertDialog.Builder(
MyActivity.this);
builder.setTitle("Select The Difficulty Level");
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
Intent i = new Intent(
getApplictionContext(),
MyActivity.class);
switch (item) {
case 0:
String msg = "Alert A";
Toast.makeText(
MyActivity.this,
msg, Toast.LENGTH_LONG).show();
break;
case 1:
String msga = "Alert B";
Toast.makeText(
MyActivity.this,
msga, Toast.LENGTH_LONG).show();
break;
case 2:
String msgz = "Alert C";
Toast.makeText(
MyActivity.this,
msgz, Toast.LENGTH_LONG).show();
break;
case 3:
String msge = "Alert E";
Toast.makeText(
MyActivity.this,
msge, Toast.LENGTH_LONG).show();
break;
}
}
});
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
}
else if (position == 1) {
String msg = "1";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
} else if (position == 2) {
String msg = "2";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
else if (position == 3) {
String msg = "3";
Toast.makeText(MyActivity.this, msg,
Toast.LENGTH_LONG).show();
}
}
});
}

You are calling a function on levelDialog before instantiating it
levelDialog.dismiss();
levelDialog = builder.create();
levelDialog.show();
change it to
levelDialog = builder.create();
levelDialog.show();
levelDialog.dismiss();
But I'm not sure why you are calling dismiss() right there. If this doesn't solve it then please post logcat so we know where the NPE is. To be more clear, switching these lines should fix your NPE but dismiss() shouldn't be called right there.
Edit
Take out this
AlertDialog levelDialog=null;
and declare and initialize it here like so
final AlertDialog levelDialog = builder.create();
levelDialog.show();
and call dismiss() in your onClick() but use dialog.dismiss() instead of levelDialog.dismiss()
Also, its typically better to use Activity Context instead of Application Context so in your Intent you might change getApplicationContext() to MyActivity.this

Related

Iterate through arraylist and show alert dialog for each item in array list and then move to next item when click positive button

I am creating an auto caller app in which i have used a button which takes data from arrayList, iterate through the arraylist and ask user on each element if want to do next call or pause on that for this i have used alert dialog, but the loop is not getting pause on each element it went to the last element and show alert dialog for that contact number.
private List<ContactEntity> mContactsList = new ArrayList<>();
private ContactEntity c;
private int i = 0;
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.start_call) {
Toast.makeText(this, "Call Started" + mContactsList.size(), Toast.LENGTH_LONG).show();
startAutoCall();
}
return super.onOptionsItemSelected(item);
}
private void startAutoCall() {
if (mContactsList.isEmpty()) {
Toast.makeText(this, "Import Contacts ", Toast.LENGTH_LONG).show();
} else {
c = mContactsList.get(i);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
while(i < mContactsList.size()){
c = mContactsList.get(i);
Log.d(TAG, "startAutoCall: " + c.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Auto Dialer Start");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
}
});
AlertDialog dialog = builder.create();
dialog.show();
i++;
}
}
}
It's not a good idea to build alert dialog inside a loop. Instead, create one and update the value for each element in the list on button click. Override onClickListener for the dialog so that you can control the flow better.
Here's a snippet in kotlin.
if(mContactList.isNotEmpty()){
c = mContactList.get(i)
val builder = AlertDialog.Builder(this)
builder.setTitle("Auto Dialer Start")
builder.setMessage("Your message here...")
builder.setPositiveButton("OK", null)
val dialog = builder.create()
dialog.setOnShowListener{ dialogInterface->
val btnOk = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btnOk.setOnClickListener{
//Your code here...
if(i == mContactList.size-1){
dialogInterface.dismiss()
}else {
i++
c = mContactList.get(i)
}
}
}
dialog.show()
}

alertdialog redirection to url

I used the android alertdialog in order to redirect to a url, the redirection should go according to user choice, here is the code:
final CharSequence[]stringArray = {"1" ,"2" , "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (stringArray.toString().equals("1")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st));
startActivity(intent);
}
else if (stringArray.toString().contains("2")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
but when I click 1 or 2 there is no redirection to the url
what is wrong with the code?
You are checking your arrays items which is not valid way to implement. You need to check for selected item's id which you can get from onclick method only.
As the array count starts from "0" so can check your selected item with "0 to 2" where your 0 will be considered as "1" selected and so on.
Check out below code:
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (item == 0)
// if (stringArray.toString().equals("1"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st));
startActivity(intent);
} else if (item == 1)
// else if (stringArray.toString().contains("2"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
Please use following code:-
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (position == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st));
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st2));
startActivity(intent);
}
else if (position == 2) {
// write some code
}
}
});
AlertDialog alert = builder.create();
alert.show();

SQLite Database not updating properly after deleting row

When I delete any data then listitem click is showing error when opening listitem and data are also not correct on custom listview. After deleting row 0 data is not updating properly. Please help..
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
// means this is the view part not the add contact part.
Cursor crs = mydb.getData(Value);
id_To_Update = Value;
crs.moveToFirst();
String nam = crs.getString(crs.getColumnIndex(DBHelper.C_NAME));
String phon = crs.getString(crs
.getColumnIndex(DBHelper.C_PHONE));
String addr = crs.getString(crs
.getColumnIndex(DBHelper.C_ADDRESS));
String dat = crs.getString(crs.getColumnIndex(DBHelper.C_DATE));
String typ = crs.getString(crs.getColumnIndex(DBHelper.C_TYPE));
if (!crs.isClosed()) {
crs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
type.setText((CharSequence) typ);
type.setFocusable(false);
type.setClickable(false);
address.setText((CharSequence) addr);
address.setFocusable(false);
address.setClickable(false);
date.setText((CharSequence) dat);
date.setFocusable(false);
date.setClickable(false);
}
}
}
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(),
"Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateContact(id_To_Update, name.getText().toString(),
phone.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertContact(name.getText().toString(), phone
.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
DBHelper.java
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
}
Finally I have got the solution. I have a text view in custom list view which has Table id which is unique for every row and after deleting the row it's value does not change so I am opening the data of that row on different activity.

context menu not working properly

please have a look at the code below...
i am creating a context menu and implementing the method onContextItemSelected but the problem is that when i press the reply item...the dialog on the delete case also appears and the activity also starts twice...means all the cases executes...the delete the reply and the forward case...what happens to be the problem please help
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId())
{
case R.id.reply:
{
Intent i = new Intent();
String s2 = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(2);
i.putExtra("number", s2);
// Log.v("number", s2);
i.setClass(this, CreateMessage.class);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
case R.id.delete:
{
final String s = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(1);
dba = new DBAdapter(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Log.v("", "You Clicked " + s);
dba.delete("messages", "id=?", new String[] { s });
populate();
dba.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
case R.id.forward:
{
Intent i = new Intent();
String s3 = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(4);
// Log.v("message", s3);
i.putExtra("message", s3);
i.setClass(this, CreateMessage.class);
startActivity(i);
}
default:
return super.onContextItemSelected(item);
}
}
and here is the error from the logcat that is displayed in the logcat...
03-30 09:13:28.439: E/WindowManager(2273): Activity sms.app.Displayer has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44eb95c8 that was originally added here
sms.app.Displayer is the class in which i am implementing the context menu..
and here is the code of the context menu file..
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/reply" android:title="Reply"></item><item
android:id="#+id/forward"
android:title="Forward">
</item>
<item android:id="#+id/delete" android:title="Delete Message">
</item>
</menu>
add breaks after your case statements
Edit:
You fall thru to the following case blocks because you are missing the breaks. Either add breaks to you case statements (and handle the return value later) or directly add return true instead of the breaks.
Once check this code a minor change in your onContextItemSelected method::
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()){
case R.id.reply:
Intent i = new Intent();
String s2 = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(2);
i.putExtra("number", s2);
// Log.v("number", s2);
i.setClass(this, CreateMessage.class);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
break;
case R.id.delete:
final String s = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(1);
dba = new DBAdapter(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Log.v("", "You Clicked " + s);
dba.delete("messages", "id=?", new String[] { s });
populate();
dba.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case R.id.forward:
Intent i = new Intent();
String s3 = (String) ((Cursor) getListView().getItemAtPosition(info.position))
.getString(4);
// Log.v("message", s3);
i.putExtra("message", s3);
i.setClass(this, CreateMessage.class);
startActivity(i);
break;
}
return true;
}

Android AlertDialog remembers string from previous shown?

The problem I am having with my Alert dialog is that, I have a custom dialog which has 3 edittext end 3 textview on it. when I pick up a contact from contacts I just filled the information in the dilaog edtitext like contactName.setText(bla); however the strange thing happens here that if I cancel the dialog and again pick another contact the details on the dialog is not getting changed and remembers the details from the first picked contact? is int weird? it seems that once it creates the dialog even though if I call the same process creating again the dialog it keeps the first dialog and keeps showing the same dialog. is there anyone whom have had the same experience and know how to solve this?
Here is the code that handles the result comes back from the contact picker.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI,
null, Email.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
contactUEmail=email;
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
// EditText emailEntry = (EditText) findViewById(R.id.invite_email);
// emailEntry.setText(email);
if (email.length() == 0) {
Toast.makeText(this, "No email found for contact.",
Toast.LENGTH_LONG).show();
}
}
showDialog(DIALOG_ADD_NEW_CALL);// this is where I call the dialog.
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
and here is the dialog DIALOG_ADD_NEW_CALL;
case DIALOG_ADD_NEW_CALL:
{
builder = new AlertDialog.Builder(this);
entryView = getLayoutInflater().inflate(R.layout.entry, null);
builder.setView(entryView);
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
if(!contactUEmail.equals(""))//here is the code that I am setting the text.
CEmailEditor.setText(contactUEmail);
else{}
builder.setTitle(R.string.addDialogTitle);
builder.setPositiveButton(R.string.addItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancelItem,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
return builder.create();
}
To destroy the dialog, you can call removeDialog. Alternatively, you could override onPrepareDialog and update the dialog before it's shown. Just FYI, both methods are deprecated in favor of DialogFragment along with FragmentManager but you probably have to redo a lot of code to use those.
Override onPrepareDialog
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ADD_NEW_CALL:
AlertDialog callDialog = (AlertDialog) dialog;
View entryView = callDialog;
CNameEditor = (EditText) entryView.findViewById(R.id.cName);
CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
// do stuff to those variables here
}
}

Categories

Resources