Well, my application would display wifi information (still work in progress for this) and set with a time picker when the wifi turns on. The problem is that i don't know how to connect the button inside the dialog of the picker "set" at the AlarmManager method. This is the code
package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity implements OnClickListener {
private Button mTimeButton;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeButton = (Button) findViewById(R.id.time_button);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
mTimeButton.setOnClickListener(this);
// Creating a memory_info Object
MemoryInfo memory_info = new MemoryInfo();
// Using Activity Manager System Service
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memory_info);
// Assign Memory Value to free_memory Variable
long free_memory = memory_info.availMem / 1048576L;
// Display free Ram Memory
TextView memoryInfoView = (TextView) findViewById(R.id.device_memory_status_txt);
memoryInfoView.setText("Free RAM Memory :-"+ free_memory + " MB");
}
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssid = info.getSSID();
TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssid);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
TextView dateInfoView = (TextView) findViewById(R.id.dateinfo);
dateInfoView.setText("L'attivazione del Wi-Fi è impostata per le ore: " + hour12format + " : " + minute + " / " + ampmStr);
/// Here is the problem: Where have i to put this? ///
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
};
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
As you can see i don't know how put the wifi control. How can i do it? How can i create an AlarmManager with my code? I Need an example if possible. Thanks
This is one example of time picker that I think you can use.
--------Main Activity-------
package com.example.chxboxtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button start_intent_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_intent_button = (Button) findViewById(R.id.start_intent_button);
start_intent_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_intent_button: {
Intent intent = new Intent(this,TimePickerTest.class);
startActivity(intent);
}
break;
}
}
}
-------------Main Activity XML-----------------
<RelativeLayout 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"
>
<Button
android:id="#+id/start_intent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Intent Time Picker"
android:layout_centerInParent="true"
/>
</RelativeLayout>
-------------TimePicker class ---------------
package com.example.chxboxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TimePickerTest extends Activity implements OnClickListener{
private CheckBox cBox;
private TimePicker tPicker;
private TextView showTime;
private Button done;
private String hour;
private String minute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker_layout);
initButtons();
}
private void initButtons() {
tPicker = (TimePicker) findViewById(R.id.time_picker);
showTime = (TextView) findViewById(R.id.get_time);
done = (Button)findViewById(R.id.done);
cBox = (CheckBox) findViewById(R.id.time_picker_checkbox);
cBox.setOnClickListener(this);
done.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//If check enable or disble timePicker
case R.id.time_picker_checkbox: {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(false);
} else {
Toast.makeText(this, "NOT CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(true);
}
}
break;
//If Done button pressed get time selected by user
case R.id.done:{
tPicker.clearFocus();
// re-read the values, in my case i put them in a Time object.
hour = tPicker.getCurrentHour().toString();
minute = tPicker.getCurrentMinute().toString();
if(tPicker.getCurrentMinute().intValue() < 10){
String setTimeText = hour+ " : " + "0" + minute;
showTime.setText(setTimeText);
}else{
String setTimeText = hour+ " : " + minute;
showTime.setText(setTimeText);
}
}
break;
default:
break;
}
}
}
-------------TimerPicker XML------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/timer_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_toRightOf="#+id/time_picker_checkbox"
android:text="Check this to Cancel Alarm" />
<CheckBox
android:id="#+id/time_picker_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_centerHorizontal="true" />
<TimePicker
android:id="#+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/time_picker"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Done" />
<TextView
android:id="#+id/get_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="Time"
android:textColor="#FF0000"
android:textSize="25sp" />
</RelativeLayout>
-------------Manifest.xml-----------
**<activity
android:name="com.example.chxboxtest.TimePickerTest"
android:configChanges="orientation|keyboardHidden">
</activity>**
Dont forget to add TimePicker class as activity.
BestPracice add all xml text in strings.xml
Cheers
Related
I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope
I have an app with several activities. The up button created by
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
works on all the activities except for one. I've checked the manifest and I can see the parent is set correctly.
Code from activity where the up button doesn't work:
package com.icenibees.apiarymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.icenibees.apiarymanager.sample.SampleDataProvider;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.UUID;
public class ApiaryDetails extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
public static final String LOGTAG="APIARYMANAGER";
public String apiaryIDDelete = "";
AMDBDataSource mDataSource;
EditText updateApiaryNameInput;
EditText updateApiaryLocationInput;
EditText updateApiaryDescriptionInput;
EditText updateApiarySetupDateInput;
EditText updateApiaryNotesInput;
String updateApiaryidInput;
private TextView tvName, tvDescription, tvLocation, tvSetupDate, tvNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apiary_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDataSource = new AMDBDataSource(this);
mDataSource.open();
final AMClasses.Apiary updateApiary = new AMClasses.Apiary();
// String apiaryId = getIntent().getExtras().getString(ApiaryItemAdapter.APIARY_ID_KEY);
// AMClasses.Apiary item = SampleDataProvider.apiaryItemMap.get(apiaryId);
final AMClasses.Apiary item = getIntent().getExtras().getParcelable(ApiaryItemAdapter.APIARY_RECORD);
if (item == null) {
throw new AssertionError("No data record received!?!");
}
tvName = (TextView) findViewById(R.id.tvApiaryName);
tvLocation = (TextView) findViewById(R.id.tvApiaryLocation);
tvSetupDate = (TextView) findViewById(R.id.tvApiarySetupDate);
tvDescription = (TextView) findViewById(R.id.tvApiaryDescription);
tvNotes = (TextView) findViewById(R.id.tvApiaryNotes);
tvName.setText(item.getApiaryname());
tvLocation.setText(item.getApiarylocation());
tvSetupDate.setText(item.getApiarysetupdate());
tvDescription.setText(item.getApiarydescription());
tvNotes.setText(item.getApiarynotes());
apiaryIDDelete = item.getApiaryid();
Button updateApiaryButton = (Button) findViewById(R.id.btnUpdateApiary);
updateApiaryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
updateApiaryidInput = item.getApiaryid();
updateApiaryNameInput = (EditText) findViewById(R.id.tvApiaryName);
updateApiaryLocationInput = (EditText) findViewById(R.id.tvApiaryLocation);
updateApiaryDescriptionInput = (EditText) findViewById(R.id.tvApiaryDescription);
updateApiarySetupDateInput = (EditText) findViewById(R.id.tvApiarySetupDate);
updateApiaryNotesInput = (EditText) findViewById(R.id.tvApiaryNotes);
//updateApiary.setApiaryid(UUID.randomUUID().toString());
updateApiary.setApiaryid(updateApiaryidInput);
updateApiary.setApiaryname(updateApiaryNameInput.getText().toString());
updateApiary.setApiarylocation(updateApiaryLocationInput.getText().toString());
updateApiary.setApiarydescription(updateApiaryDescriptionInput.getText().toString());
updateApiary.setApiarysetupdate(updateApiarySetupDateInput.getText().toString());
updateApiary.setApiarynotes(updateApiaryNotesInput.getText().toString());
Log.i(LOGTAG, "Apiary ID to be updated: " + updateApiary.getApiaryid());
Log.i(LOGTAG, "Update Apiary Name: " + updateApiary.getApiaryname());
Log.i(LOGTAG, "Update Apiary Location: " + updateApiary.getApiarylocation());
Log.i(LOGTAG, "Update Apiary Description: " + updateApiary.getApiarydescription());
Log.i(LOGTAG, "Update Apiary Setup Date: " + updateApiary.getApiarysetupdate());
Log.i(LOGTAG, "Update Apiary Notes: " + updateApiary.getApiarynotes());
mDataSource.updateApiary2DB(updateApiary);
Snackbar.make(findViewById(android.R.id.content),
"Apiary updated", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
}
);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//ACTIVITY TIMER CLOSER
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(2500); // As I am using LENGTH_LONG in Toast
ApiaryDetails.this.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//DELETE MENU
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_apiary, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// SETTINGS MENU CASE STATEMENTS
int id = item.getItemId();
switch (id) {
case R.id.action_apiary_delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage("Please confirm you want to delete the apiary?");
builder.setIcon(R.drawable.ic_action_delete);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
mDataSource.deleteApiary(apiaryIDDelete); // Delete Apiary Row
Snackbar.make(findViewById(android.R.id.content),
"Apiary deleted", Snackbar.LENGTH_LONG)
.setAction("Action",null).show();
thread.start();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
}
return true;
}
//DATE PICKER CODE
public void datePickerEditApiary(View view){
NewApiary.DatePickerFragment fragment = new NewApiary.DatePickerFragment();
fragment.show(getSupportFragmentManager(), "date");
}
public void setDate(final Calendar calendar){
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
((TextView) findViewById(R.id.tvApiarySetupDate)).setText(dateFormat.format(calendar.getTime()));
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar cal = new GregorianCalendar(year, month, dayOfMonth);
setDate(cal);
}
public static class DatePickerFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener) getActivity(),year, month, day);
}
}
}
Manifest:
<activity
android:name=".EditApiary"
android:label="#string/title_activity_edit__apiary"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
<activity
android:name=".ApiaryDetails"
android:label="#string/title_activity_apiary_details"
android:parentActivityName=".EditApiary"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.EditApiary" />
</activity>
<activity
android:name=".EditHive"
android:label="#string/title_activity_edit_hive"
android:parentActivityName=".ApiarySetup"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.icenibees.apiarymanager.ApiarySetup" />
</activity>
I see
getSupportActionBar()
So, you are using AppCompatActivity instance
Probably, you should override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
finish();
return true;
//Or another code here
}
return false;
}
Also, you can add parent activity inside AndroidManifest.xml like this:
API 16+
<activity
....
android:parentActivityName="activity_class_name" />
I'm working on a Android App and the layout and all the "android" specific stuff made a friend of my. I only was responsible for the "app" itself.
Nevertheless,
I would like to change some settings, e.g. change the server the stats produced by the app, should be transfered.
Here is the Settings.java:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Settings extends Activity {
private Context mContext;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefEditor;
private EditText textName, textIP;
private RadioButton rdOnline, rdOffline;
private RadioGroup rdGroup;
private Button butSpeichern;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_settings);
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPrefEditor = mPrefs.edit();
textName = (EditText) findViewById(R.id.txtBenutzer);
textIP = (EditText) findViewById(R.id.txtIP);
rdOffline = (RadioButton) findViewById(R.id.rdOffline);
rdOnline = (RadioButton) findViewById(R.id.rdOnline);
rdGroup = (RadioGroup) findViewById(R.id.radioDB);
butSpeichern = (Button) findViewById(R.id.btnSpeichern);
butSpeichern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//Online default an
rdOnline.setChecked(true);
rdOffline.setChecked(false);
loadSettings();
//ggf. Lan
System.out.println("online");
if(automatischLAN()){
setLan();
}
}
private void saveSettings()
{
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.putString("benutzer", textName.getText().toString());
mPrefEditor.putString("ip", textIP.getText().toString());
mPrefEditor.apply();
finish();
}
private void loadSettings() {
textName.setText(mPrefs.getString("benutzer", ""));
textIP.setText(mPrefs.getString("ip", "192.168.0.50"));
rdOnline.setChecked(mPrefs.getBoolean("onlineDB", true));
rdOffline.setChecked(!mPrefs.getBoolean("onlineDB", true));
}
public boolean automatischLAN(){
Calendar cal = new GregorianCalendar();
Date currenttimen = new Date();
cal.setTime(currenttimen);
int freitag = cal.get(Calendar.DAY_OF_WEEK);
int STUNDE = 0;
STUNDE = cal.get(Calendar.HOUR_OF_DAY);
System.out.println(STUNDE);
if(freitag == Calendar.FRIDAY && STUNDE>11 && STUNDE< 14 ) {
System.out.println("lan");
return false;
}
else {
System.out.println("online");
return true;
}
}
public void onBackPressed()
{
saveSettings();
super.onBackPressed();
}
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
}
}
I'm afraid my setLan() method isn't working as the values are not stored in the prefs...
What is the easieast way to check prefs and chance them on each start of the app?
Thanks for your help
You have to commit the changes in the SharedPreference.Editor variable. Replace your function above with the given one
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.apply();
}
I've been working on getting a timepicker dialog to set my countdown timer. I have tried many ways with many different results... none of them worked right. I decided to experiment with some basic code which I will put below.
I cannot get the selected time (I called it selectedStartTime in the code below) to pass through into the actual countdown timer as startTime. I can only get the timer to work right when I use the preset startTime = 10000 (or any number). I don't want the startTime to be a set number. I need it to come from the OnTimeSetListener in the time picker box.
I will be forever grateful to anyone that can show me how to change the code so that the selected time in the dialog box is actually used in the timer.
Complete XML code for: activity_simple_timer_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start" />
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="10dip">
<TableRow>
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time: " />
<TextView
android:id="#+id/timeElapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time elapsed: " />
</TableRow>
</TableLayout>
</LinearLayout>
Complete Java code for: SimpleTimerTest.java
package com.YOURPACKAGE INFO;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class SimpleTimerTest extends Activity implements OnClickListener {
private MalibuCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private Button startB;
private TextView text;
private TextView timeElapsedView;
int selectedStartTime;
// don't want to use a predefined startTime
private final long startTime = 10000;
private final long interval = 1000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_timer_test);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
timeElapsedView = (TextView) this.findViewById(R.id.timeElapsed);
countDownTimer = new MalibuCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime));
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
selectedStartTime = ((hourOfDay*3600000)+(minute*60000));
// I can't get this variable to pass through into the countdown timer
}
};
#Override
public void onClick(View v) {
TimePickerDialog d = new TimePickerDialog(SimpleTimerTest.this, onTimeSetListener, 1, 0, true);
d.setTitle("Pick Sleep Duration hour:min");
d.setCancelable(true);
d.setButton(DialogInterface.BUTTON_POSITIVE, "Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("Stop");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Timer was already running");
}
}
}
});
d.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Restart");
}
}
});
d.show();
}
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
Toast toast = Toast.makeText(getApplicationContext(), "finished", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
}
I'm not completely sure what you're trying to achieve, just create instance of your MalibuCountDownTimer in method onTimeSet, this method will be called only when user selected time.
How can i activate the wifi when i decide the time? This is the code but for now i create the timepicker and the wifi option to turn it on is inside the picker so doesn't go. i want that if i decide in te time picker for example 3.00 AM at the 3.00 AM the wifi turns on.
package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity implements OnClickListener {
private Button mTimeButton;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeButton = (Button) findViewById(R.id.time_button);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
mTimeButton.setOnClickListener(this);
// Creating a memory_info Object
MemoryInfo memory_info = new MemoryInfo();
// Using Activity Manager System Service
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memory_info);
// Assign Memory Value to free_memory Variable
long free_memory = memory_info.availMem / 1048576L;
// Display free Ram Memory
TextView memoryInfoView = (TextView) findViewById(R.id.device_memory_status_txt);
memoryInfoView.setText("Free RAM Memory :-"+ free_memory + " MB");
}
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssid = info.getSSID();
TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssid);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
TextView dateInfoView = (TextView) findViewById(R.id.dateinfo);
dateInfoView.setText("L'attivazione del Wi-Fi è impostata per le ore: " + hour12format + " : " + minute + " / " + ampmStr);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
};
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
Thank you.