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.
Related
package com.example.riplee07.trydialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listss = new ArrayList<String>();
ArrayAdapter <String>adapter;
String add1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText tt = (EditText)findViewById(R.id.editText);
final ListView lv = (ListView)findViewById(R.id.listView1);
Button br = (Button)findViewById(R.id.button);
add1 = tt.getText().toString();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listss);
lv.setAdapter(adapter);
listss.add(add1);
adapter.notifyDataSetChanged();
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listss.add(add1);
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
}
}
Try this code below (for getting edittext data):
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText et = (EditText) ss.findViewById(E.id.editText);
listss.add(et.getText().toString());
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
Here is the method in which i call on Button button.setOnClickListener
public void saveNote(View view){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_new_note_layout);
mTitle = (EditText)dialog.findViewById(R.id.titleID);
mMessage = (EditText)dialog.findViewById(R.id.messageID);
save = (Button)dialog.findViewById(R.id.saveBtn);
setFilePathll();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int titleLength = mTitle.getText().length();
if(titleLength != 0){
String title = mTitle.getText().toString();
String msg = mMessage.getText().toString();
helper.addNote(title, mFilePath, msg);
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this,"Empty Message is not valid",Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
Here helper.addNote(title, mFilePath, msg); is the method which i declared in the database helper class to insert data.
you Should use RecyclerView for what you want instead of using 'ListView'
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.
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)
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
Here is my code:
package com.example.userpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class UserPage extends Activity {
AlertDialog.Builder builder;
private final static int EMPTY_TEXT_ALERT = 0;
#Override
public Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
builder = new AlertDialog.Builder(this);
builder.setMessage("Message:Fields Empty!!!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
String tv,tv1;
EditText name,pass;
TextView x,y;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.widget44);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent obj = new Intent(UserPage.this,UserPage.class);
startActivity(obj);
}
});
x = (TextView) findViewById(R.id.widget46);
y = (TextView) findViewById(R.id.widget47);
name = (EditText)findViewById(R.id.widget41);
pass = (EditText)findViewById(R.id.widget43);
Button button1 = (Button) findViewById(R.id.widget45);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//tv= name.getText().toString();
//tv1 = pass.getText().toString();
x.setText(tv);
y.setText(tv1);
tv = name.getText().toString();
if(tv.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
tv1 = pass.getText().toString();
if (tv1.trim().equals(""))
{
showDialog(EMPTY_TEXT_ALERT);
}
}
});
}
}
What is happening when you try to run it? Which part are you having a problem with?
From what I can tell your code is not going to display any dialogs because you've never called the dialog.show() method. You'd have to do something like this for the way you have it set up:
showDialog(EMPTY_TEXT_ALERT).show();
If you are trying to make it two separate dialogs, one for name, and one for pass then all you'd have to do is make another id variable and add a case: for it inside the switch statement that inside your showDialog(id) method.
You should also really consider using descriptive names for your variables. Your code would be easier to understand if you didn't use names like x,y, and widget#.