Android tabhost missing when nfc scanned - java

When I scan my NFC tag, my application fires up and does what it have to do , but the tabhost goes missing. The mainactivity.java is where I initialize the tabhost with 3 tabs and this following first part of the code is one of the tab in which I utilize the NFC reading function. Is this because of the pendingintent? I don't really know how to fix it, do I have to implement the 3 tabs in every activity layout?
My code:
package com.example.ponpon;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PatternMatcher;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
#TargetApi(10)
public class CouponManager extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
public static final String PREF_FILE_NAME = "PrefFile";
private int[] images = new int[11];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
//List of images
images[0]=R.drawable.cp0;
images[1]=R.drawable.cp1;
images[2]=R.drawable.cp2;
images[3]=R.drawable.cp3;
images[4]=R.drawable.cp4;
images[5]=R.drawable.cp5;
images[6]=R.drawable.cp6;
images[7]=R.drawable.cp7;
images[8]=R.drawable.cp8;
images[9]=R.drawable.cp9;
images[10]=R.drawable.cp10;
//Restore preferences
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
//Image to use depending on coupon collected
final ImageView img = (ImageView)findViewById(R.id.imageView1);
if(storedPreference!=10)
{
img.setImageResource(images[storedPreference]);
img.invalidate();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Coupon Redemption");
builder.setMessage("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
img.invalidate();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
img.invalidate();
}
});
builder.show();
}
//Check and send Intent from NFC tag discovered
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
/*| Intent.FLAG_ACTIVITY_CLEAR_TOP*/), 0);
IntentFilter coupontag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
coupontag.addDataScheme("http");
coupontag.addDataAuthority("www.ichatime.com", null);
coupontag.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
mNdefExchangeFilters = new IntentFilter[] { coupontag };
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if(mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mNdefExchangeFilters, null);
} else {
Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onDestroy() {
super.onDestroy();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
public void onBackPressed() {
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
super.onBackPressed();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
if (result.contains("ichatime.com"))
{
final ImageView img = (ImageView)findViewById(R.id.imageView1);
/*if (storedPreference!=10)
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
img.invalidate();
}*/
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
img.invalidate();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
img.invalidate();
}
});
builder.show();
}
else
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
editor.commit();
img.setImageResource(images[storedPreference]);
img.invalidate();
}}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
//Debugging Mode to see what is contained in the tags.
// Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();
}
}
}
}
and also, my main activity:
package com.example.ponpon;
import android.os.Bundle;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec spec1=tabHost.newTabSpec("Coupon Manager");
spec1.setContent(R.id.tab1);
spec1.setIndicator("Coupons");
Intent CouponsIntent = new Intent(this, CouponManager.class);
spec1.setContent(CouponsIntent);
TabSpec spec2=tabHost.newTabSpec("Help");
spec2.setIndicator("Help");
spec2.setContent(R.id.tab2);
Intent SettingsIntent = new Intent(this, Settings.class);
spec2.setContent(SettingsIntent);
TabSpec spec3=tabHost.newTabSpec("Write[Vendor]");
spec3.setIndicator("Write\n[Vendor]");
spec3.setContent(R.id.tab3);
Intent HelpIntent = new Intent(this, HelpActivity.class);
spec3.setContent(HelpIntent);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Take a close look at your logic: you have
if (storedPreference!=10) {
...stuff... (including storedPreference++)
}
if (storedPreference==10) {
...stuff...
} else {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 10);
img.setImageResource(images[10]);
img.invalidate();
}
You should consider replacing the contents of the else block with the storedPreference!=10 block, then getting rid of that first block. All you need is if storedPreference==10 and else.

Related

How do I transfer data from one activity to another in Android Studio? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 1 year ago.
I am creating a Pomodoro Timer app. It has 2 activities:
The first one is the home page.
Second is for setting a time.
I want to make a third activity with recent times
I want to create a third activity that takes the input times from the second activity and stores them in a list, but I don't know how to transfer the input-data from the second activity to the third ?
Activity 1:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newTime = findViewById(R.id.newTime);
Button currentTime = findViewById(R.id.currentTime);
Button recents = findViewById(R.id.recentTime);
newTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2Intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
// currentTime.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent currentActivityIntent = new Intent(getApplicationContext(), currentActivity.class);
// startActivity(currentActivityIntent);
// overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
// }
// });
}
}
Activity 2:
package com.example.pomotimer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Locale;
public class Activity2 extends AppCompatActivity {
private TextView TextViewCountdown;
private Button Button_Start_Pause;
private Button Reset;
private Button buttonSet;
private Button select_Time;
private EditText edit_Text_Input;
private CountDownTimer countDownTimer;
public long mStartTimeinMillis;
private long timeLeft = mStartTimeinMillis;
private boolean timerRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
TextViewCountdown = findViewById(R.id.textViewCount);
Button_Start_Pause = findViewById(R.id.bnStartPause);
Reset = findViewById(R.id.reset);
select_Time = findViewById(R.id.selectTime);
edit_Text_Input = findViewById(R.id.edit_Text_Input);
buttonSet = findViewById(R.id.buttonSet);
select_Time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_Text_Input.setVisibility(View.VISIBLE);
buttonSet.setVisibility(View.VISIBLE);
buttonSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = edit_Text_Input.getText().toString();
if (input.length() == 0){
Toast.makeText(Activity2.this, "Field can't be empty", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(input)*60000;
if (millisInput == 0){
Toast.makeText(Activity2.this, "Timer cannot be set to 0", Toast.LENGTH_SHORT).show();
return;
}
setTime(millisInput);
edit_Text_Input.setText("");
// Intent res = new Intent(getApplicationContext(), currentActivity.class);
// startActivityForResult(res, (int) millisInput, null);
}
});
}
});
Button_Start_Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerRunning){
pauseTimer();
}
else{
startTimer();
}
}
});
Reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void setTime(long milliseconds){
mStartTimeinMillis = milliseconds;
resetTimer();
}
private void startTimer(){
countDownTimer = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
// The countdown timer has an automatic method of reducing time by 1s
timeLeft = millisUntilFinished;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void onFinish() {
timerRunning = false;
Button_Start_Pause.setText("Start");
Button_Start_Pause.setVisibility(View.INVISIBLE);
}
}.start();
timerRunning = true;
Button_Start_Pause.setText("pause");
}
private void pauseTimer(){
countDownTimer.cancel();
timerRunning = false;
Button_Start_Pause.setText("Start");
}
private void resetTimer(){
timeLeft = mStartTimeinMillis;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
Button_Start_Pause.setVisibility(View.VISIBLE);
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("millisleft", timeLeft);
editor.putBoolean("timerRunning", timerRunning);
editor.apply();
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
timeLeft = prefs.getLong("millisleft",mStartTimeinMillis);
timerRunning = prefs.getBoolean("timeRunning", false);
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
}
We can pass data to another activity using Intent.
Like before startActivity we need to do:
intent.putExtra("Data", data);
and in thirdActivity onCreate we need to do
intent.getStringExtra("Data");
Inside Activity2
You can place data inside the Intent directly or you can put them in a Bundle and then put the inside the Intent. Avoid using both for consistency.
Intent activity3Intent = new Intent(getApplicationContext(), Activity3.class);
//Direct Intent approach
activity3Intent.putExtras("YOUR_STRING_KEY","YOUR_DATA");
//OR Bundle approach
Bundle bundle = new Bundle();
bundle.putString("YOUR_STRING_KEY","YOUR_DATA");
activity3Intent.putExtras(bundle);
startActivity(activity3Intent);
Inside the Activity3 class.
//if direct intent approach
String value = getIntent.getStringExtra("YOUR_STRING_KEY")
//If bundle approach was used.
String value = getIntent().getExtras().getString("YOUR_STRING_KEY");

Shared Preference CANNOT store and read the value with the condition.(Android Studio)

I'm developing an Attendance System. To avoid student helping their friend sign the attendance, I plan to use Shared Preference method to store the student ID, after that will blocking their access when login with his friend ID.
But the if else statement seems doesn't read the Shared Preference method.
Please guide me where I'm wrong, Thanks:
Here is the code:
package com.example.android.jomsign;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final SharedPreferences sharedPref = getSharedPreferences("data",MODE_PRIVATE);
final Boolean Logined = sharedPref.getBoolean("Logined", false);
final String sid = sharedPref.getString("SID", "");
final EditText etid = (EditText) findViewById(R.id.etid);
final EditText etpwd = (EditText) findViewById(R.id.etpwd);
final Button btnlogin = (Button) findViewById(R.id.btnlogin);
final Button btnregister = (Button) findViewById(R.id.btnregister);
final TextView TextView2 = (TextView) findViewById(R.id.etid);
TextView2.setText(sid);
btnregister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id = etid.getText().toString();
final String pwd = etpwd.getText().toString();
if(Logined == true) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String id = jsonResponse.getString("id");
String pwd = jsonResponse.getString("pwd");
String name = jsonResponse.getString("name");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("id", id);
intent.putExtra("pwd", pwd);
intent.putExtra("name", name);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putBoolean("Logined", true);
prefEditor.putString("SID", id);
prefEditor.apply();
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(id, pwd, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}else if(Logined == false) {
AlertDialog.Builder helpfriend = new AlertDialog.Builder(LoginActivity.this);
helpfriend.setMessage("The login ID not same with the previous ID.Trying to help friend sign? Please contact your lecturer.")
.setNegativeButton("Close", null)
.create()
.show();
}
};
});
}
}
I set the TextView2 is because I want to view the shared Preference value. But seem doesn't work.
It will never go into the if block.
Focus on this line.
final Boolean Logined = sharedPref.getBoolean("Logined", false);
When you open your first time it takes default value false so it will directly go into else if.
For it's solution update above line as following
final int Logined = sharedPref.getInt("Logined", 0);
In btnlogin.setOnClickListeren()
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id = etid.getText().toString();
final String pwd = etpwd.getText().toString();
if(Logined == 0) {
//Simply allow user to login and write here code for logging.
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Logined", 1);
editor.putString("SID", sid);//You have to get sid from somewhere.
editor.commit();
}
else if(Logined == 1)
{
if(!sid.equals(sid2))//sid2 is a sid of user who is logging currently
{
AlertDialog.Builder helpfriend = new AlertDialog.Builder(LoginActivity.this);
helpfriend.setMessage("The login ID not same with the previous ID.Trying to help friend sign? Please contact your lecturer.")
.setNegativeButton("Close", null)
.create()
.show();
}
else
{
//allow user for login and write code for logging.
}
}

Entered Username won't appear after App title

I'm developing a simple to do list application, where on the welcome page, you enter your name and when you click to goto your tasks (on tasks page) your username which you just entered should appear at the top of the screen (For example: "App: Username") but when I tried this it appeared as "App: null" on the welcome page and "null: null" on the tasks page. Can anyone see why? Thank you.
Welcome.java
package winfield.joe.assignment.two;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.ProgressDialog;
import android.widget.CheckBox;
public class Welcome extends Activity {
//global vars
private CheckBox check;
private ProgressDialog progress;
private ToggleButton toggleButton;
private RatingBar ratingBar;
private String givenTitle;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
givenTitle = (String) this.getTitle();
progress = new ProgressDialog(this);
addListenerOnCheck();
addListenerOnButton();
addListenerOnRatingBar();
}
//on click CheckBox displays a toast message - CLICK!
public void addListenerOnCheck() {
check = (CheckBox) findViewById(R.id.check);
check.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("CLICK!");
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//on click toggle button displays on/off
public void addListenerOnButton() {
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Toggle = ").append(toggleButton.getText());
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//Give a rating - Toast appears of star rating
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
//if rating value has changed, display the current rating on a toast
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(Welcome.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_SHORT).show();
}
});
}
//Onclick - go to About
public void aboutMe(View view) {
Intent intent = new Intent(Welcome.this, About.class);
startActivity(intent);
}
//Onclick - go to Tasks
public void doStuff(View view) {
this.setTitle(givenTitle + ": " + username);
Intent intent = new Intent(Welcome.this, Tasks.class);
startActivity(intent);
//ProgressBarDialog appears saying its finding yours tasks and loads to 100 and changes activity
progress.setMessage("Finding tasks...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();
//Goes to 100
final int totalProgressTime = 100;
final Thread t = new Thread(){
#Override
public void run(){
//Goes from 0 to 100 in jumps of 5 until the total amount of jumps reaches 100/total progress time
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
Thread.sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}; t.start();
}
}
Tasks.java
package winfield.joe.assignment.two;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import winfield.joe.assignment.two.database.TaskContract;
import winfield.joe.assignment.two.database.TaskDBHelper;
public class Tasks extends ListActivity {
//add required global variables
private ListAdapter listAdapter;
private TaskDBHelper helper;
private String givenTitle;
private String username;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
updateUI();
this.setTitle(givenTitle + ": " + username);
}
//add in the menu (refers to menu.xml file)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
//to get selected tasks from menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
//create new alert dialog which asks you if you want to make a new task entry
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add a new task");
builder.setMessage("What do you need to do?");
final EditText inputField = new EditText(this);
builder.setView(inputField);
//if 'add' then place it into the db, update it
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Clicking add - stores data in the database
String task = inputField.getText().toString();
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK,task);
db.insertWithOnConflict(TaskContract.TABLE,null,values,SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
//quits out of alert dialog and goes back to the task list if 'cancel'
builder.setNegativeButton("Cancel",null);
builder.create().show();
return true;
default:
return false;
}
}
//Show database entries on the tasks page
private void updateUI() {
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE, new String[]{
TaskContract.Columns._ID, TaskContract.Columns.TASK
},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
//Deletes tasks (clicking done next to them)
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
//This query deletes the entry associated with the id/button pressed
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
//onClick finished method assigned to the 'Finished' button
public void finished(View view) {
//Make alert dialog box appear and give it it's title
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert));
// set dialog message
builder.setCancelable(false)
//Positive response = return to list (tasks page)
.setPositiveButton(getString(R.string.positive),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the Tasks
dialog.cancel();
}
})
//Neutral response = go to about (about page)
.setNeutralButton(getString(R.string.neutral),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You go to About Activity
Intent intent = new Intent(Tasks.this, About.class);
startActivity(intent);
}
})
//Negative response = exit app (homescreen)
.setNegativeButton(getString(R.string.negative),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, exit app to homescreen
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
//create it and show it
AlertDialog alert = builder.create();
alert.show();
}
}
Username within activity_welcome.xml
<EditText
android:ems="10"
android:hint="#+string/username"
android:id="#+id/username"
android:inputType="text"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_width="match_parent">
<requestFocus/>
</EditText>
Relevant strings from strings.xml
<string name="app_name">ForYouToDo</string>
<string name="username">Username</string>
Go to Android - Pass Data Between Two Activities get NullPointerException
A complete guide(How to pass data between two activity?)
and do in your Tasks Activity
this.setTitle(getResources().getString(R.string.app_name)+ ": " + username);

Skip the Activity only if account registeration is done

In my project user have to register and then proceed forward.After the restart of the app the login activity should start skipping the registration activity.But the problem arises when user restarts the app without registering,the login activity appears and not the register activity.So plz help me with this issue Thanks in Advance
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 4000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code here
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
boolean firstboot = getSharedPreferences("BOOT_PREF", MODE_PRIVATE).getBoolean("firstboot", true);
//
if (firstboot){
// // 1) Launch the authentication activity
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
// // 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
}
else
{
Intent i = new Intent(getApplicationContext(), enterpass.class);
startActivity(i);
}
// Intent i =new Intent(getApplicationContext(), NewAccount.class);
// startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
NewAccount.java
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class NewAccount extends Activity implements OnClickListener {
EditText ed1, ed2, ed3, ed4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
Button ok;
ok = (Button) findViewById(R.id.new_account_btn_ok);
ok.setOnClickListener(this);
ed1 = (EditText) findViewById(R.id.new_account_name);
ed2 = (EditText) findViewById(R.id.new_account_email);
ed3 = (EditText) findViewById(R.id.new_account_pass);
ed4 = (EditText) findViewById(R.id.new_account_repass);
}
public final static boolean isValidEmail(String email) {
{
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
#Override
public void onClick(View arg0) {
String s2 = ed2.getText().toString();
String s3 = ed3.getText().toString();
String s4 = ed4.getText().toString();
if (ed1.getText().toString().length() == 0
|| ed2.getText().toString().length() == 0
|| ed3.getText().toString().length() == 0
|| ed4.getText().toString().length() == 0) {
if (ed1.getText().toString().length() == 0) {
ed1.setError("field required");
} else if (ed2.getText().toString().length() == 0) {
ed2.setError("field required");
} else if (ed3.getText().toString().length() == 0) {
ed3.setError("field required");
} else if (ed4.getText().toString().length() == 0) {
ed2.setError("field required");
}
} else if (isValidEmail(s2) == false) {
Toast.makeText(getApplicationContext(), "Invalid Email",
Toast.LENGTH_SHORT).show();
} else if (ed3.getText().toString().length() < 6) {
Toast.makeText(getApplicationContext(), "Password too Short",
Toast.LENGTH_SHORT).show();
} else if (!s3.equals(s4)) {
Toast.makeText(getApplicationContext(), "Password Dont Match",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
}
Move this code inside NewAccount.class so firstboot will be set to false only when the user has authenticated.
// 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
I've only rewieved it breefly but I'd put it here:
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
// set firstboot to false here
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}

How to make a toggle button for a widget android

So I've created a widget, and I'm tried my best to simulate a toggle button. Sense Widget doesn't support a toggle button I'm using a imagebutton and plan on changing the image depending on it's state.
Only problem is it's state isn't being saved and I'm not sure why.
package com.tdubstudios.beastmode;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class WidgetClass extends AppWidgetProvider{
private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
private RemoteViews views;
public boolean beastmodeOn = false;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
views = new RemoteViews("com.tdubstudios.beastmode", R.layout.widget_layout);
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, WidgetClass.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_ib, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current App
// Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
if(beastmodeOn){
beastmodeOn = false;
Toast.makeText(context, "beastmode is now off", Toast.LENGTH_SHORT).show();
}else{
beastmodeOn = true;
Toast.makeText(context, "beastmode is now ON", Toast.LENGTH_SHORT).show();
}
}
super.onReceive(context, intent);
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Toast.makeText(context, "onDelete has been called in widgetClass", Toast.LENGTH_LONG).show();
}
}
No matter how many times I press the button I always get the toast "beastmode is now ON"
Any suggestions?
Thank you.
EDIT:
Ok so I added this code:
Log.i("widget","BEFORE beastmode is: "+beastmodeOn);
beastmodeOn = true;
Toast.makeText(context, "beastmode is now ON", Toast.LENGTH_SHORT).show();
Log.i("widget","AFTER beastmode is: "+beastmodeOn);
and my log gives me this back:
BEFORE beastmode is: false
AFTER beastmode is: true
It gives me this EVERY time I press the button. So obviously it creates a new instance or something to that effect. Once it executes it must destroy all variable values or something, maybe someone with more knowledge knows the right words.
So does anyone know a work around then?
So I don't exactly know why the above didn't work, I'm assuming because it creates a new instance. I've managed to make a work around though by using SharedPreferences to keep track of the toggle. Probably not the best way to do it but it works, so I'm happy.
For anyone else having this problem here ya go:
package com.tdubstudios.beastmode;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;
import android.widget.Toast;
public class WidgetClass extends AppWidgetProvider {
private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
private RemoteViews views;
public boolean beastmodeOn;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
views = new RemoteViews("com.tdubstudios.beastmode",
R.layout.widget_layout);
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, WidgetClass.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_ib, pendingIntent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
if (value) {
Editor editor = prefs.edit();
editor.putBoolean("beastmodeOn", false);
editor.commit();
}
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
Editor editor = prefs.edit();
if (value) {
beastmodeOn = true;
} else {
beastmodeOn = false;
}
if (beastmodeOn) {
Toast.makeText(context, "beastmode is now off",
Toast.LENGTH_SHORT).show();
editor.putBoolean("beastmodeOn", false);
editor.commit();
} else {
Toast.makeText(context, "beastmode is now ON",
Toast.LENGTH_SHORT).show();
editor.putBoolean("beastmodeOn", true);
editor.commit();
}
}
super.onReceive(context, intent);
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
if (value) {
Editor editor = prefs.edit();
editor.putBoolean("beastmodeOn", false);
editor.commit();
}
super.onDeleted(context, appWidgetIds);
}
}

Categories

Resources