Android - Click on image multiple times to open dialog - android

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)

Related

Progress circle not running till it loads RecyclerView

I am trying to move from one activity A to another activity B.In activity B there is a recycler view,In that recycler view I am loading data in background thread(Using AsyncTask) from SQLite database.When I switch to activity B I have given a Progress Bar to show the loading of data.But that progress bar doesn't spin till it fully loads the data.I want it to spin to show loading is happening.
This some what looks like this,
When loading happens then it starts to spin,and looks like this.Running behind the recycler view.
package com.freakydevs.kolkatalocal;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class TrainTable extends AppCompatActivity {
String from, to;
ProgressDialog progressDialog;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.train_table);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_DARK);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected void onStart() {
super.onStart();
new MyAsyncTask().execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Cursor> {
public int FromStationId, ToStationId;
String sday, sday1, sday2, sday3;
int check = 5;
private List<Train> trainList = new ArrayList<>();
private RecyclerView recyclerView;
private TrainTableAdapter trainTableAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onPreExecute() {
Intent intent = getIntent();
sday = intent.getStringExtra("day");
from = intent.getStringExtra("From");
to = intent.getStringExtra("To");
FromStationId = intent.getIntExtra("trainId", 0);
ToStationId = intent.getIntExtra("trainId1", 0);
check = intent.getIntExtra("samay", 0);
}
#Override
protected Cursor doInBackground(Void... params) {
//Some codes are here to make a cursor and send it to postExecute
c3 = SQ.rawQuery(s, null);
return c3;
}
#Override
protected void onPostExecute(final Cursor cursor) {
if (cursor.getCount() == 0) {
progressDialog.dismiss();
setProgressBarIndeterminateVisibility(false);
ShowNoTrain();
} else {
recyclerView = (RecyclerView) findViewById(R.id.tiimetable_list);
new Thread(new Runnable() {
#Override
public void run() {
trainTableAdapter = new TrainTableAdapter(TrainTable.this, cursor, from, to);
runOnUiThread(new Runnable() {
#Override
public void run() {
mLayoutManager = new LinearLayoutManager(TrainTable.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(trainTableAdapter);
trainTableAdapter.notifyDataSetChanged();
progressDialog.dismiss();
setProgressBarIndeterminateVisibility(false);
}
});
}
}).start();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
}
public void ShowNoTrain() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TrainTable.this);
// set title
//alertDialogBuilder.setTitle("Invalid Date");
// set dialog message
alertDialogBuilder
.setMessage("No Train Available for this Route!")
.setCancelable(false);
//final AlertDialog my = alertDialogBuilder.create();
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// create alert dialog
// show it
alertDialog.show();
}
}

How to fix setOnItemClickListener inside ListView

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

how to wake a thread from sleep in android

I have an activity thats waiting for the user press on an image. if the user dont press anything in 3 second i want the activity to close (finish()).
thats my code:
private final int delay = 3000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_hangup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
final ImageView pressToLaunchbrowser = (ImageView) findViewById(R.id.after_hang_up_image);
pressToLaunchbrowser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // if we want to open the device.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
Thread.interrupted();
}
});
new Thread() {
public void run() {
try {
Thread.sleep(delay);
finish();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}}
My question is how can i wake the Thread if the press was made? i tried Thread.interrupted(); but its not working. the thread still waits 3 seconds if i press or not. Thanks!
Threads are not recommended to use in Android..use Handler to manage time-dependant operations..for example, instead of new Thread().., try
Handler handler = new Handler();
handler.postDelayed('runnable-that-will-finish-activity', 3000);
and in onclicklistener:
handler.remove('runnable-that-will-finish-activity') ;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
public class NewActivity extends Activity {
private final int delay = 3000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_hangup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
final ImageView pressToLaunchbrowser = (ImageView) findViewById(R.id.after_hang_up_image);
final Handler handler = new Handler();
handler.postDelayed(finishRunnable, delay);
pressToLaunchbrowser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// // if we want to open the device.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
handler.removeCallbacks(finishRunnable);
}
});
}
private Runnable finishRunnable = new Runnable() {
#Override
public void run() {
finish();
}
};
}

I want to display seperate alerts for name and pass fields

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#.

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