I am trying to make a small Android App for personal stuff and have two problem with my code now:
The code should execute the following until
isAlarm == false;
do {
(new BTask(context)).execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (isAlarm);
But it only does this once.
I want it to close the dialog box only it the correct password is entered, but it closes it everytime and not executing the command:
isAlarm = false;
I know, the code is not very beautiful, but I'm still learning. =)
package top.sysop.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
public static Button btn1;
public static Button btn2;
public static Button btn3;
private MediaPlayer mMediaPlayer;
boolean isAlarm;
private String m_Text = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_main);
dialogevent3();
}
public void dialogevent3() {
int i=1;
btn3 = (Button) findViewById(R.id.dial3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Diebstahl!");
// Set up the input
final EditText input = new EditText(MainActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
dialogevent3();
}
}
});
do {
(new BTask(context)).execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (isAlarm);
// alert.show();
builder.show();
}
});
}
}
You're not initialzing the value of isAlarm so its containing the default value that is false.
there are some changes like
initialize boolean isAlarm = true
change while (isAlarm) to while (!isAlarm)
Hope this helps
You can achieve this continuous checking using TextWatcher and runnable.
custom_layout_for_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Password..."/>
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:ems="10"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Password here"
/>
</LinearLayout>
call this method to open a custom dialog from your Activity
public void customDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_layout_for_dialog);
dialog.setCancelable(true);
EditText edt_password= (EditText) dialog.findViewById(R.id.editText);
edt_password.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//write all your operations here
String m_Text=s.toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
dialogevent3();
}
}
});
//This handler checks for isAlarm for every 300ms
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (isAlarm){
(new BTask(context)).execute();
}
}
},300);
dialog.show();
}
Thanks guys
I've solved it using the following code:
MainActivity.java
package top.sysop.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "";
public static Button btn1;
public static Button btn2;
public static Button btn3;
private MediaPlayer mMediaPlayer;
public static boolean isAlarm;
private String m_Text = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_main);
dialogevent1();
dialogevent2();
dialogevent3();
}
public void dialogevent1() {
btn1 = (Button) findViewById(R.id.dial1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Bitte geben Sie mich bei der Kasse ab.").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");
alert.show();
}
});
}
public void dialogevent2() {
btn2 = (Button) findViewById(R.id.dial2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Bitte geben Sie mich sofort bei der Kasse ab!").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");
alert.show();
}
});
}
public void dialogevent3() {
isAlarm = true;
btn3 = (Button) findViewById(R.id.dial3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buildDialog();
/* AlertDialog.Builder altdial = new AlertDialog.Builder(MainActivity.this);
altdial.setMessage("Sie begehen Diebstahl!").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isAlarm = false;
dialogInterface.cancel();
}
});
AlertDialog alert = altdial.create();
alert.setTitle("xxx");*/
// alert.show();
}
});
}
private void buildDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Diebstahl!");
// Set up the input
final EditText input = new EditText(MainActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.equals("pass"))
{
//end
isAlarm = false;
}
else
{
//repeat
dialog.dismiss();
buildDialog();
input.setText("");
}
}
});
(new BTask(context)).execute();
builder.show();
}
}
and
BTask.java
package top.sysop.myapplication;
import android.content.Context;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.AsyncTask;
import android.os.Vibrator;
/**
* Created by Szalewicz on 22.11.2017.
*/
public class BTask extends AsyncTask {
Context context;
public BTask() {
}
public BTask(Context context) {
this.context = context;
}
#Override
protected Object doInBackground(Object[] objects) {
final Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
final ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
do {
v.vibrate(500);
toneGen1.startTone(ToneGenerator.TONE_CDMA_MED_SSL, 500);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (MainActivity.isAlarm);
//for (int faktor = 1; faktor <= 10; faktor ++) {
v.vibrate(500);
toneGen1.startTone(ToneGenerator.TONE_CDMA_MED_SSL, 500);
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//}
return false;
}
}
Now it's doing what I want =)
Related
I used an alert dialog box for confirmation of delete, I make a recycler view in which two methods are applied 1.swipe for delete method, 2. menu bar delete method. In swipe method when I swipe the view it removed the list and show alert dialog when clicking no then it replaces not original space but another space that creates a space between them kindly guide me what issue it is?
package com.example.framelayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerClickListener, RecyclerActionClick {
private RecyclerView recyclerView;
private detailAdapt adapt;
private List<detailModel> modelList = new ArrayList<>();
detailModel modelData, swipeData;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
final int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT) {
swipeData = modelList.get(position);
showDialogBox(position, true);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_details);
populateList();
}
private void populateList() {
for (int i = 0; i < 10; i++) {
int img = R.drawable.ic_person;
String person = "Person " + i;
String name = "Person Name " + i;
String msg = "Person Last Message " + i;
detailModel model = new detailModel(person, name, msg, img);
modelList.add(model);
}
addRecycle(modelList);
}
private void addRecycle(List<detailModel> modelList) {
adapt = new detailAdapt(this, modelList, this, this);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setSmoothScrollbarEnabled(true);
recyclerView.setAdapter(adapt);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layout);
ItemTouchHelper helper = new ItemTouchHelper(simpleCallback);
helper.attachToRecyclerView(recyclerView);
}
#Override
public void onDeleteCLick(Object obj, int position) {
showDialogBox(position, false);
}
private void showDialogBox(final int position, final boolean isSwiped) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Are you sure to delete this Item");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
deleteItem(position);
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void deleteItem(final int position) {
modelData = modelList.get(position);
modelList.remove(position);
adapt.notifyItemRemoved(position);
Snackbar snackbar = Snackbar.make(recyclerView, "item removed at position " + position, Snackbar.LENGTH_LONG);
snackbar.setAction("undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
modelList.add(position, modelData);
adapt.notifyItemInserted(position);
}
});
snackbar.show();
}
#Override
public void onUndoCLick(Object obj, int position) {
}
#Override
public void onSingleClick(Object obj, int position) {
detailModel model = (detailModel) obj;
Toast.makeText(this, "click at " + position, Toast.LENGTH_SHORT).show();
}
}
Please remove below
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
from the cancel button of the alert dialog, as you already didn't remove the item yet, so no need to insert it again. instead replace them with notifyItemChanged(position); like below
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
adapt.notifyItemChanged(position);
}
}
});
I have problem with Runnable. It don't want to works, and i don't know what is the problem, because it is works in my other app... Can somebody help me?
Just example, there are "healt" with deafult value=5, for the test i made a button, when i click button, healt value -1... and i want start Runnable when health<5... and add +1 to health.... for the test i setted the Runnable 1 secunds
Here is the code:
MainActivity.java
package com.mygame.test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import static com.mygame.test.variables.coin;
import static com.mygame.test.variables.health;
public class Main2Activity extends AppCompatActivity {
public static final String PREFS_NAME_MAIN = "mainpref";
TextView coinText, healthText, textView;
Button button3;
private final Context app = this;
private final Handler update = new Handler();
private final Runnable updateHealth = new Runnable()
{
public void run()
{
if (variables.run)
{
healthText.setText(""+health);
update.postDelayed(updateHealth, 500);
}
else if (!variables.run) update.removeCallbacksAndMessages(null);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
coinText = findViewById(R.id.coinText);
healthText = findViewById(R.id.healthText);
healthText.setText(String.valueOf(health));
button3 = findViewById(R.id.button3);
textView = findViewById(R.id.textView);
Button closeButton = findViewById(R.id.closeButton);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, ExitActivity.class));
}
});
Button coinsplusButton = findViewById(R.id.coinsplusButton);
coinsplusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, StoreActivity.class));
}
});
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//finishAffinity();
startActivity(new Intent(Main2Activity.this, Level1Activity.class));
}
});
}
public void buttontest(View button3)
{
if (health > 0) {
health = health-1;
healthText.setText(""+health);
}
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
update.post(updateHealth);
save();
}
#Override
protected void onStart()
{
super.onStart();
load();
textupgrade();
if (!variables.run)
{
variables.run = true;
Intent activeClick = new Intent(this, ClickService.class);
this.startService(activeClick);
}
}
protected void onResume()
{
super.onResume();
load();
textupgrade();
update.post(updateHealth);
}
private void load()
{
SharedPreferences varReader = app.getSharedPreferences(PREFS_NAME_MAIN, MODE_PRIVATE);
variables.run = varReader.getBoolean("run", false);
coin = varReader.getInt("coin", 0);
health = varReader.getInt("health", 5);
}
private void save()
{
SharedPreferences.Editor varReader = app.getSharedPreferences(PREFS_NAME_MAIN, 0).edit();
varReader.putBoolean("run", variables.run);
varReader.putInt("coin", coin);
varReader.putInt("health", health);
varReader.apply();
}
private void textupgrade(){
coinText.setText(""+coin);
healthText.setText(""+health);
}
}
ClickService.java
package com.mygame.test;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
public class ClickService extends IntentService
{
private final Handler handler = new Handler();
private final Runnable addHealth = new Runnable()
{
public void run()
{
variables.health++;
if (!variables.run) handler.removeCallbacksAndMessages(null);
else if (variables.run) handler.postDelayed(addHealth, 1000);
}
};
public ClickService()
{
super("ClickService");
}
#Override
protected void onHandleIntent(Intent activeClick)
{
handler.postDelayed(addHealth, 500);
}
}
variables.java
package com.mygame.test;
public class variables {
static int coin;
static int health;
static boolean run;
}
Oh, i fixed it :D ClickService was not registered in AndroidManifest
<service
android:name=".ClickService"
android:exported="false" />
In Google play service 10.0.1, for the following code, when building it I get the error:
“GooglePlayServicesClient” cannot resolve the symbol
Any idea how to resolve this?
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationRequest;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.asyncTasks.EmployeeSerchResult;
import com.shuan.Project.asyncTasks.GetEmployeeSerach;
import com.shuan.Project.employer.PostViewActivity;
import java.util.List;
import java.util.Locale;
public class EmplyeeSearchActivity extends AppCompatActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private Toolbar toolbar;
private Common mApp;
private Boolean flag = false;
private LocationClient mLocationClient;
private ProgressDialog pDialog;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private ProgressBar progressBar;
private ListView list;
private AutoCompleteTextView preferSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
mApp = (Common) getApplicationContext();
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
setTheme(R.style.Junior);
} else {
setTheme(R.style.Senior);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emplyee_search);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
toolbar.setBackgroundColor(getResources().getColor(R.color.junPrimary));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.senPrimary));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
mLocationRequest = new LocationRequest();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
list = (ListView) findViewById(R.id.ser_res);
preferSearch = (AutoCompleteTextView) findViewById(R.id.prefered_serach);
new GetEmployeeSerach(EmplyeeSearchActivity.this, progressBar, preferSearch).execute();
preferSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
preferSearch.dismissDropDown();
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, preferSearch.getText().toString(),
"all").execute();
}
return false;
}
});
preferSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
TextView txt = (TextView) view.findViewById(R.id.display);
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
preferSearch.setText(txt.getText().toString());
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, txt.getText().toString(),
txt1.getText().toString()).execute();
}
});
preferSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
list.setAdapter(null);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
Intent in = new Intent(getApplicationContext(), PostViewActivity.class);
in.putExtra("jId", txt.getText().toString());
in.putExtra("apply", "no");
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emp_search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gps) {
flag = gpsStatus();
if (flag) {
new displayCurrentLocation().execute();
} else {
showGpsAlert();
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class displayCurrentLocation extends AsyncTask<String, String, String> {
String location;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmplyeeSearchActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Searching");
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Location currentLocation = mLocationClient.getLastLocation();
Geocoder geocoder = new Geocoder(EmplyeeSearchActivity.this, Locale.getDefault());
Location loc = currentLocation;
List<android.location.Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
final android.location.Address address = addresses.get(0);
location = address.getLocality();
}
} catch (Exception e) {
}
return location;
}
#Override
protected void onPostExecute(final String s) {
super.onPostExecute(s);
pDialog.cancel();
Intent in = new Intent(getApplicationContext(), EmployeeSearchResultActivity.class);
in.putExtra("loc", s);
startActivity(in);
}
}
private void showGpsAlert() {
AlertDialog.Builder build = new AlertDialog.Builder(EmplyeeSearchActivity.this);
build.setTitle("Alert")
.setMessage("Turn On your GPS! Find the Jobs & companies")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
dialog.cancel();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "Can't Find Employer", Toast.LENGTH_SHORT).show();
}
}).show();
}
private Boolean gpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStus) {
return true;
} else {
return false;
}
}
}
as mentioned in this answer i guess GooglePlayServiceClient and has become outdated so remove it and use GoogleApiClientinstead.Also LocationServices.API, and FusedLocationProviderApi were introduced.
Usage of GoogleApiClient :
To use GoogleApiClient the first thing to change is the interface, the activity or service is implementing
//old code of GooglePlayServiceClient :
public class LocationMonitoringService extends Service implements GooglePlayServicesClient.ConnectionCallbacks
//replace the above ^ code with this: new code for GoogleApiClient
public class LocationMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks
in GooglePlayServiceClient, mLocationClient was just a regular class constructor.
inGoogleApiClient a Builder is used like :
//old code of GooglePlayServiceClient :
LocationClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
replace it^ with new builder code of GoogleApiClient :
GoogleApiClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationClient.connect();
}
Examples :
Requesting location :
Old code was just a simple call like
mLocationClient.requestLocationUpdates(mLocationRequest, locationListener);
in GoogleApiClient we use FusedLocatonApi like :
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationListener);
This post shows you a implementation of most of the methods like :onConnected onConnectionFailed onConnectionSuspended etc.
Hi guys I am looking for a bit of help and advise with my app, At the moment I have a custom adapter printing out each row, in each row it prints two buttons, one button to increment and one button to decrement. What I want to happen is for when a button is clicked a editText(totalCost) outside the listView changes. I have no idea how to go about doing this as I am pretty new to android and java, so any help will be great. Thanks
The custom adapter that I am using is
package com.example.rory.dbtest;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pinchtapzoom.R;
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
}
});
}
}
This is the main activity where I want the editText(TotalCost) to change depending on the click
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.pinchtapzoom.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords());
list1.setAdapter(customAdapter);
}
});
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
And the XML file for the adapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="30sp"
android:paddingBottom="5dp"/>
<Button
android:id="#+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/runningTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusButton"
android:layout_toStartOf="#+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="#+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
You should use an Interface
1) create an interface class:
public interface MyAdapterInterface {
public void updateEditText(String value);
}
2) change your adapter to:
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor c, MyAdapterInterface myInterface) {
super(context, c);
this.context = context;
this.mMyInterface = myInterface;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
}
}
3) implement the interface in your activity:
public class MyActivity extends Activity implements MyAdapterInterface {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), this);
list1.setAdapter(customAdapter);
}
});
#Override
public void updateEditText(String value) {
EditText myEditText = (EditText)findViewById(R.id./*YOUR EDITTEXT ID*/);
myEditText.setText(value);
}
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a NullPointerException.
My DialogHost class, this constructs, returns and links the parent to its buttons.
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
#override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
This is my MainActivity class showing the dialog
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
#override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
#override
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
Thisthe layout of my Dialog for reference.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/hint_add_item" />
</LinearLayout>
There seems to be problem with the way you are referring to the edit text. You need to get it from the view you inflated Please try the below code which adds all functionality in your main activity itself. If you want you can adapt to your case with a separate class:
public void showNoticeDialog() {
public String inputvalue;
LayoutInflater inflater = LayoutInflater.from(this);
final View textenter = inflater.inflate(R.layout.dialog_add, null)
final EditText userinput = (EditText) textenter.findViewById(R.id.item_added);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(textenter)
.setTitle("Your title");
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
inputvalue = userinput.getText().toString();
// Do something with value in inputvalue
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
builder.show();
}
For alert dialog , you need to inflate an xml, only if you are planning to have multiple views like more than 1 edittext in that dialog. If you plan to have only 1 edittext as in your example, you dont need an xml and you can directly define an edittext and set it as the view of the alert dialog.
final EditText userinput = new EditText(context);
builder.setView(userinput);