How to fix setOnItemClickListener inside ListView - android

I have a ListView which has more rows in it. Inside of rows I have two LinearLayouts (deleteItem and editItem) which has setOnClickListener on them. When I'm trying to click on deleteItem or editItem it works only at the second touch, i don't know why.. I've read some answers on stackoverflow but I couldn't find one answer to fix my problem..
This is the code:
import org.json.JSONArray;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.currencymeeting.adapters.GetAllMyCurrencyListViewAdapter;
import com.currencymeeting.beans.User;
import com.currencymeeting.connectors.DeleteCurrencyConnector;
import com.currencymeeting.connectors.MyCurrencyConnector;
import com.currencymeeting.controllers.MessageDialogController;
import com.currencymeeting.controllers.VariableController;
public class MyCurrencyActivity extends FragmentActivity {
private ListView getAllMyCurrencyListView;
private ProgressDialog dialog;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_currency);
this.dialog = ProgressDialog.show(MyCurrencyActivity.this, MessageDialogController.PROGRESS_DIALOG_TITLE, MessageDialogController.PROGRESS_DIALOG_MESSAGE);
this.getAllMyCurrencyListView = (ListView) findViewById(R.id.getAllMyCurrencyListView);
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
getAllMyCurrencyListView.setOnItemClickListener(
new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyCurrencyActivity.this.view = view;
final TextView itemID = (TextView) view.findViewById(R.id.itemID);
final LinearLayout deleteItem = (LinearLayout) view.findViewById(R.id.deleteItem);
final LinearLayout editItem = (LinearLayout) view.findViewById(R.id.editItem);
deleteItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(MyCurrencyActivity.this)
.setMessage("Are you sure do you want to delete it?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String vid = itemID.getText().toString();
String userId = ""+VariableController.getInstance().getUser().getId();
new DeleteCurrencyTask().execute(userId, vid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
);
editItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),EditCurrencyActivity.class);
startActivity(intent);
}
}
);
}
}
);
final LinearLayout menu = (LinearLayout) findViewById(R.id.menu);
menu.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuLoggedActivity.class);
startActivity(intent);
}
}
);
}
public void setListAdapter(JSONArray jsonArray){
this.getAllMyCurrencyListView.setAdapter(new GetAllMyCurrencyListViewAdapter(jsonArray,this));
this.dialog.dismiss();
};
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
#Override
protected JSONArray doInBackground(MyCurrencyConnector... params) {
User user = VariableController.getInstance().getUser();
return params[0].getAllResults(user);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
private class DeleteCurrencyTask extends AsyncTask<String,Void,String[]>{
#Override
protected String[] doInBackground(String... params) {
return params;
}
#Override
protected void onPostExecute(String[] result) {
boolean status = new DeleteCurrencyConnector().deleteTransaction(result[0],result[1]);
LinearLayout itemViewId = (LinearLayout) MyCurrencyActivity.this.view.findViewById(R.id.itemViewID);
if(status){
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
} else {
Toast.makeText(MyCurrencyActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
}

Your problem might be caused by the way your program executes. You first thread your adapter initialization, and then your main thread starts attaching onclick listeners before your adapter initialization finishes. This means your listview will have a click listener but not the items in the adapter, and when you click the listview once
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
this fires off in your DeleteCurrencyTask and sets the adapter again. To fix this try putting setOnClick initializaion in the post execute of your
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{

I believe I realized why the event of deleteItem and editItem is called only on second click, because deleteItem and editItem clickListeners are atached only when getAllMyCurrencyListView.setOnItemClickListener (when I click on row) is called not when the code is loaded. So I guess I have to find another way to make these events

Related

ListView setOnItemLongClickListener not working android

I have an android app, which shows a list of items. By pressing an item it should perform an action like delete item. The problem is that, when I press the item, nothing happens, it is like the screen does not recognize my finger press. But, down on page, I have a button, that works fine, when I press it.
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private ListView listView;
public static FirebaseUtil firebaseUtil;
public static CostumeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseUtil = new FirebaseUtil();
setContentView(R.layout.activity_main);
final Context context = this;
if (firebaseUtil.getmFirebaseUser() == null) {
loadLogInView();
} else {
firebaseUtil.setmUserId(firebaseUtil.getmFirebaseUser().getUid());
listView = (ListView) findViewById(R.id.listView);
adapter = new CostumeAdapter(this);
listView.setAdapter(adapter);
fillData();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final Costume car = adapter.getCostumes().get(position);
final String uuid = car.getUuid();
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Delete")
.setMessage("This car will be deleted.")
.setPositiveButton("Delete", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
firebaseUtil.remove(uuid, car);
}
})
.setNegativeButton("Cancel", null)
.show();
return true;
}
});
The xml files are ok, I guaranteed.
The OnItemLongClickListener that you have implemented would work only if the else part is executed. Is firebaseUtil.getmFirebaseUser() == null false?
I used this, and it worked, You can try out with some Log.d() to see if the clickListener is executed.
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onViewCreated: on View Created");
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> adapterView,View view,final int position, long id) {
new AlertDialog.Builder(getContext())
.setTitle(R.string.attention)
.setMessage(R.string.confirm_to_delete)
.setNegativeButton(R.string.cancel,null)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Cursor c= adapter.getCursor();
c.moveToPosition(position);
int itemID = c.getInt(c.getColumnIndex("_id"));
dbWrite.delete("diary","_id=?",new String[]{""+itemID});
refreshList();
}
}).show();
return true;
}
});
}

Error in Alert dialog

There is an error in 'return view' at listview.setOnItemLongClickListener method. The error says cannot return a value from a method with void result type. I am trying to create an alert dialog where it will notify the user whether it wants to delete.
package com.example.user.swen;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.user.swen.DB.RecordsDataSource;
import com.example.user.swen.Model.Records;
public class Record extends ListActivity {
public Button NewButton;
public RecordsDataSource Recordsdatasource;
ArrayAdapter<Records> RecordAdapter;
List<Records> records;
ListView listview;
Records selectedRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Addrecords();
//Referencing the Database
Recordsdatasource = new RecordsDataSource(this);
Recordsdatasource.open();
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//set the listView to use the custom List Adapter
records = (List<Records>) Recordsdatasource.getAll();
RecordAdapter = new RecordAdapter(this, 0, (ArrayList<Records>) records);
listview = (ListView) findViewById(android.R.id.list);
listview.setAdapter(RecordAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Duty: " + selectedRecord.getType())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Information</font>"));
alert.show();
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(selectedRecord);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Alert!!</font>"));
alert.show();
return true;
}
});
return view;
}
public void Addrecords() {
NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecords = new Intent(Record.this, NewRecord.class);
startActivity(addrecords);
}
});
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
private void deleteItem(Records selectedRecord) {
Recordsdatasource.removeRecords(selectedRecord);
showToast(this, "Usage deleted");
RecordAdapter.notifyDataSetChanged();
RecordAdapter.notifyDataSetInvalidated();
refreshDisplay();
}
private void refreshDisplay() {
records = Recordsdatasource.getAll();
RecordAdapter.clear();
RecordAdapter.addAll(records);
}
}
You are trying to return a View from your Activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//...
return view;
}
As you can see, onCreate() in an Activity has a void return type, meaning you shouldn't be returning anything in this method.
From the looks of your code, you are attempting to use this layout as the Activity's layout, but you are confusing the View inflation code with that used in a Fragment's onCreateView() method, which does indeed require you to return a View.
In an Activity, you need to call setContentView() to set the layout. You can either set the layout using the resource ID via setContentView(R.layout.activity_record), or if you want to inflate the View yourself you can call setContentView(view).
The call return view is actually located in onCreate. The function onCreate is declared to return nothing (void). Therefore, you cannot return an instance of View. You just have to remove that line or replace it with return; Also, onItemLongClick must return a boolean. So you can't move return view there either.

Android - Click on image multiple times to open dialog

I am looking for a code that would let me click on an imageView 3 times to open a dialog box. That would be very helpful, thank you!
Here is my code:
package natanrosenfeld.texteditor;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import com.natanrosenfeld.texteditor.R;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Handler;
import java.lang.Runnable;
public class CreditsActivity extends ActionBarActivity{
private AtomicInteger mCounter = new AtomicInteger();
private Handler handler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
mCounter = new AtomicInteger();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_credits);
ImageView img = (ImageView) findViewById(R.id.imageView);
addClickToImage(img);
}
public void addClickToImage(ImageView imageView) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(mRunnable);
handler.postDelayed(mRunnable, 1000);
if (mCounter.incrementAndGet() == 2) {
//Display your dialog fragment
new AlertDialog.Builder(getApplicationContext())
.setTitle("Easter Egg")
.setMessage("Easter Egg...")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
});
}
}
ddmlib: Broken pipe
java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:675)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:342)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:521)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
at
com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:633)
at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)
Here you have a way to handle the 3 clicks, even if you want to manipulate the counter from other threads. It adds the click listener and waits 1 second to put the counter of clicks to 0.
public class MyActivity extends Activity{
private AtomicInteger mCounter = new AtomicInteger();
private Handle handler = new Handler();
private Runnable mRunnable = new Runnable(){
#Override
public void run(){
mCounter = new AtomicInteger();
}
}
public void onCreate(Bundle savedInstance){
...
ImageView myImage = (ImageView) findViewById(R.id.imageView);
addClickToImage(myImage);
}
public void addClickToImage(ImageView image){
image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
handler.removeCallback(mRunnable);
handler.postDelayed(mRunnable, 1000);
if(mCounter.incrementAndGet() == 3){
//Display your dialog fragment
}
}
});
}
}
Error 2
You are opening your dialog by providing the application context. Here is the line:
new AlertDialog.Builder(getApplicationContext())
The only context that can open dialogs is the current activity context, never the application one. So to fix this error:
new AlertDialog.Builder(CreditsActivity.this)

clicking item on listview android

on my application i want to click the list item and make some changes like deleting or updating the item.but i could not implemented the other codes to my code.so little help will be useful. here is my code
package com.example.todolist;
import java.util.ArrayList;
import java.util.Collection;
import android.os.Bundle;
import android.provider.Contacts;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener,OnKeyListener,OnInitListener {
EditText txtitem;
ListView listitem;
TextToSpeech talker;
ArrayList<String> todolist;
ArrayAdapter<String> arrayadapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtitem = (EditText) findViewById(R.id.txtitem);
listitem = (ListView) findViewById(R.id.listitem);
talker = new TextToSpeech(this, this);
txtitem.setOnKeyListener(this);
todolist = new ArrayList<String>();
arrayadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todolist);
listitem.setAdapter(arrayadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem toAdd = menu.add("AddItem");
MenuItem toDelete = menu.add("DeleteItem");
MenuItem toSave = menu.add("SaveItem");
MenuItem toExit = menu.add("ExitItem");
MenuItem toUpdate = menu.add("UpdateItem");
return true;
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if(item.getTitle().equals("AddItem")){
todolist.add(txtitem.getText().toString());
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("DeleteItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
todolist.remove(y-1);
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("SaveItem")){
say("Save Complete");
arrayadapter.notifyDataSetChanged();
}
if (item.getTitle().equals("ExitItem")){
talker.speak("Are you sure you want to close this activity?",TextToSpeech.QUEUE_FLUSH,null);
onBackPressed();
}
if(item.getTitle().equals("UpdateItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
arrayadapter.notifyDataSetChanged();
txtitem.setText(todolist.get(y-1));
todolist.remove(y-1);
}
return true;
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onInit(int status) {
}
#Override
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
}
#Override
public void onBackPressed()
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
runOnUiThread(new Runnable() {
#Override
public void run() {
say("Bye");
}
});
}
})
.setNegativeButton("No", null)
.show();
}
this code takes the list's elemnt number and delete's it.but i want to click and delete or update.son little help will be useful.thank you already
To remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
To Add items you can do something like this :
on a click of button take text from edittext and add it as an item on list
/** Reference to the button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
Read official android docs here 1 and 2 for handling click of menu items ...
What you want to do is set the itemClickListener(). This is done by something like this:
list.setOnItemClickListner(new OnItemClickListener(){
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Do stuff here.
}
});
From that block, you just need to call your delete statement. Alternatively, you could have your class use the AdapterView.OnItemClickListener interface, and put the routine there, then changing the command to list.setOnItemClickListner(this);

AlertDialog crashes application

Can someone explain to me why this AlertDialog crashes?
package com.clicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Clicker extends Activity
{
public int clickerNumber = 0;
private TextView clickerText;
private Button clickerButton;
private Button resetButton;
// Called when the activity is first created.
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare each of the layout objects
clickerText = (TextView)findViewById(R.id.clickerText);
clickerButton = (Button)findViewById(R.id.clickerButton);
resetButton = (Button)findViewById(R.id.resetButton);
clickerText.setText("0");
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
resetQuestion.setMessage("Are you sure you want to reset the counter?");
resetQuestion.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clickerNumber = 0;
clickerText.setText("0");
}
});
resetQuestion.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
clickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickerNumber++;
clickerText.setText(Integer.toString(clickerNumber));
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetQuestion.show();
}
});
};
};
This is a great fail:
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
You are trying to use a null object, and that (of course) will throw a NullPointerException
This is how I create dialogs (and I think it's the best way to do it):
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialogo_layout, null);
final AlertDialog.Builder resetQuestion = new AlertDialog.Builder(YourActivity.this)
// do whatever you want with the resetQuestion AlertDialog
Here, R.layout.dialogo_layout represent a file called dialogo_layout.xml in the res/layout dir that contains the dialog layout.

Categories

Resources