How to save the current state of switches in Android Studio? - android-activity

I know very little about programming. I downloaded Android Studio and started tinkering with it. I tried to make the app that they put on the tutorial and it worked. However I tried to add more functionality to it and I've failed so far. Excuse me if you see unnecessary junk on my code, I'm just kinda trying everything at first and I do feel a little misguided.
Anyways, onto the question. I have a Switch (id:toggle_text) with an OnClick action (change_font). When the switch is toggled it should change the font size of a different activity through intent1. Currently not only does it not send the font size variable (the variable keeps the default value you put on getIntExtra), but now that I tried to add the ability to save the current state it just shows errors. Here's the code:
package com.example.myfirstapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
import android.widget.TextView;
import static com.example.myfirstapp.R.id.toggle_text;
import static com.example.myfirstapp.R.string.change_font;
public class ShowAnOption extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_an_option);
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
public void change_font(View v) {
int fssize;
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
fssize=20;
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
fssize=40;
}
Intent intent1 = new Intent (getBaseContext(), DisplayMessageActivity.class);
intent1.putExtra("Font_Size", fssize);
}
}
It says "cannot resolve symbol toggle" on toggle.setChecked() and the if statement. What can I do to fix this? Also, why does it not get sent to the other activity? Here's the code on the other activity:
package com.example.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
Intent intent1 = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int Font_Size = intent1.getIntExtra("Font_Size",50);
TextView textView = new TextView(this);
textView.setTextSize(Font_Size);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Thanks and sorry for the long read. If there's anything else that needs to be known let me know and I'll gladly show.

We did not try to change the font size but here is how to use the switch widget.
Our design is two activities MainActivity and SwitchActivity we changed a CheckBox from unchecked to checked The switch is on the MainActivity code below
setOnCheckedChangeListener();
private void setOnCheckedChangeListener() {
swAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "Switch On", Toast.LENGTH_SHORT).show();
Intent intentSP = new Intent(MainActivity.this, SwitchActivity.class );
Bundle extras = new Bundle();
extras.putString("FONT","true" );
intentSP.putExtras(extras);
startActivity( intentSP );
} else {
Toast.makeText(MainActivity.this, "Switch Off", Toast.LENGTH_SHORT).show();
}
}
});
}
Now in the SwitchAcvity we capture the value from the intent and fire the method
doWhat()
Intent intentSP = getIntent();
Bundle bundle = intentSP.getExtras();
tORf = bundle.getString("FONT");
doWhat(null);
And here is the doWhat method
public void doWhat(View view){
if(tORf.equals("true")){
chkBoxOne.setChecked(true);
}else {
Toast.makeText( SwitchActivity.this, "NOT TRUE", Toast.LENGTH_LONG ).show();
}
}

Related

Use Datawedge with flutter

I am trying to use the datawedge intent API with my flutter application, on a Zebra android scanner. I started to use the Zebra EMDK API from a git repository, which works perfectly. Now I want to migrate it (which is recommended by Zebra) because I want it to be also available on mobiles (if it is possible).
I am trying to follow the instructions from this page and merge it with the code from the git repo, but no scan event is detected in my app.
Has someone already done this and could help me?
Here is my MainActivity.java:
package com.example.test_datawedge;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
// import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugins.GeneratedPluginRegistrant;
import java.util.ArrayList;
public class MainActivity extends FlutterActivity {
private static final String BARCODE_RECEIVED_CHANNEL = "samples.flutter.io/barcodereceived";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
// setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
// registerReceiver(myBroadcastReceiver, filter);
new EventChannel(getFlutterView(), BARCODE_RECEIVED_CHANNEL).setStreamHandler(
new StreamHandler() {
private BroadcastReceiver barcodeBroadcastReceiver;
#Override
public void onListen(Object arguments, EventSink events) {
Log.d("FLUTTERDEMO", "EventChannelOnListen");
barcodeBroadcastReceiver = createBarcodeBroadcastReceiver(events);
registerReceiver(
barcodeBroadcastReceiver, new IntentFilter("readBarcode"));
}
#Override
public void onCancel(Object arguments) {
Log.d("FLUTTERDEMO", "EventChannelOnCancel");
unregisterReceiver(barcodeBroadcastReceiver);
barcodeBroadcastReceiver = null;
}
}
);
}
// #Override
// protected void onDestroy()
// {
// super.onDestroy();
// unregisterReceiver(myBroadcastReceiver);
// }
//
// After registering the broadcast receiver, the next step (below) is to define it.
// Here it's done in the MainActivity.java, but also can be handled by a separate class.
// The logic of extracting the scanned data and displaying it on the screen
// is executed in its own method (later in the code). Note the use of the
// extra keys are defined in the strings.xml file.
//
private BroadcastReceiver createBarcodeBroadcastReceiver(final EventSink events) {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + action);
if(action.equals("readBarcode")){
String barcode = intent.getStringExtra("barcode");
String barcodetype = intent.getStringExtra("barcodetype");
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + barcode);
events.success(barcode);
}
}
};
}
//
// The section below assumes that a UI exists in which to place the data. A production
// application would be driving much of the behavior following a scan.
//
// private void displayScanResult(Intent initiatingIntent, String howDataReceived)
// {
// String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
// String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
// String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
// final TextView lblScanSource = (TextView) findViewById(R.id.lblScanSource);
// final TextView lblScanData = (TextView) findViewById(R.id.lblScanData);
// final TextView lblScanLabelType = (TextView) findViewById(R.id.lblScanDecoder);
// lblScanSource.setText(decodedSource + " " + howDataReceived);
// lblScanData.setText(decodedData);
// lblScanLabelType.setText(decodedLabelType);
// }
}
Zebra EMDK retrieves data by overriding the 'onStatus' and 'onData' functions.
Retrieve your barcode data from 'onData'

Android Studio says "Expression expected"

Android Studio tells there is an error in Java file, in string summonButton2(); Android Studio says "Expression expected".
I want the method summonButton2 to be launched automatically. I undesrtand that I'm doing it wrong. What exactly and is there any other way to start a method, except adding it to onCreate method? Thanks in advance.
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.LinearLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int numberOfLinesLeft = 3;
Button secondaryActivityAddButton;
LinearLayout llForSecondaryButton;
LinearLayout llForSecondaryEditText;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
summonButton2();
}
public void summonButton2(View view){
llForSecondaryButton = findViewById(R.id.secondaryButton);
secondaryActivityAddButton = new Button(this);
secondaryActivityAddButton.setText("" + numberOfLinesLeft);
llForSecondaryButton.addView(secondaryActivityAddButton);
secondaryActivityAddButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
plusTextField();
if(numberOfLinesLeft == 0) {
view.setVisibility(View.GONE);
}
}
});
}
public void plusTextField() {
llForSecondaryEditText = findViewById(R.id.linearLayout1);
// add edittext
et = new EditText(this);
et.setText("text" + numberOfLinesLeft );
llForSecondaryEditText.addView(et);
numberOfLinesLeft--;
secondaryActivityAddButton.setText("" + numberOfLinesLeft);
}
}
summonButton2(new View(this));
Helped in my case.

The operator - under defined for the arguement type(s) EditText, int

Im trying to create an activity which adds name, age, and maxhr to sqlite and will be displayed in a listview in Eclipse. name and age is an input text. Maxhr is age(input text) minus 220. But im getting "The operator - under defined for the arguement type(s) EditText, int" error. I can't seem to find the answer for this error. Does anyone know how to fix it?
package com.heartrate.monitoring.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.heartratemonitoringapp.R;
import com.heartrate.monitoring.dao.UserDAO;
import com.heartrate.monitoring.model.User;
public class AddUserActivity extends Activity implements OnClickListener {
public static final String TAG = "AddUserActivity";
private EditText mTxtName;
private EditText mTxtAge;
private Button mBtnAdd;
private UserDAO mUserDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
getActionBar().setDisplayHomeAsUpEnabled(true);
initViews();
this.mUserDao = new UserDAO(this);
}
private void initViews() {
this.mTxtName = (EditText) findViewById(R.id.txt_name);
this.mTxtAge = (EditText) findViewById(R.id.txt_age);
this.mBtnAdd = (Button) findViewById(R.id.btn_add);
this.mBtnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Editable name = mTxtName.getText();
Editable age = mTxtAge.getText();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)){
// add the user to database
double mhr;
double maxhr;
mhr = Double.parseDouble(mTxtAge.getText().toString());;
maxhr = mhr - 220;
User createdUser = mUserDao.createUser(
name.toString(), age.toString(),
maxhr.toString());
Log.d(TAG, "added user : "+ createdUser.getName());
Intent intent = new Intent();
intent.putExtra(ListUserActivity.EXTRA_ADDED_USER, createdUser);
setResult(RESULT_OK, intent);
Toast.makeText(this, R.string.user_created_successfully, Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mUserDao.close();
}
}
Remove the extra ; on this line: mhr = Double.parseDouble(mTxtAge.getText().toString());;

When click button in menu it opens xml file

i am trying to make a menu in my app. when i click the menu button i made called aboutUs it is supposed to open an XML file that explains what this app is about. Except when i run the app and click on the menu button the app just force closes. heres my mainactivity.java
package com.JordanZimmittiDevelopers.BlazeCustomerService1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.JordanZimmittiDevelopers.BlazeCustomerService.R;
public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mail = (Button)findViewById(R.id.button1);
mail.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[]{"jordanzimmitti#gmail.com", "",};
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I Have A Question Or Probelm:");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "My question or problem is:");
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Click Your Defult E-mail To Send Your Message:"));
finish();
break;
}
}
Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.aboutUs:
Intent i = new Intent("com.JordanZimmittiDevelopers.BlazeCustomerService.AboutThisApp");
startActivity(i);
}
return false;
}
}
Make an activity that explain the application then override onCreateOptionsMenu() like this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add("Help").setIcon(R.drawable.HelpButton).setIntent(new Intent(this,HelpActivity.class));
return super.onCreateOptionsMenu(menu);
}

Capture 5 images after a button click in android

I am developing android application. The aim is to capture the 5 images after click a capture button. I am able to capture a single image by using the following code. But how can I take 5 images after a single button click. Please Can someone help me to do this?
Code snippet:
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.camera.facedetectionexample.R;
public class FaceDetectionExample extends Activity {
private static final int TAKE_PICTURE_CODE = 100;
private Bitmap cameraBitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.take_picture)).setOnClickListener(btnClick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(TAKE_PICTURE_CODE == requestCode){
processCameraImage(data);
}
}
private void openCamera(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_CODE);
}
private void processCameraImage(Intent intent){
setContentView(R.layout.detectlayout);
((Button)findViewById(R.id.detect_face)).setOnClickListener(btnClick);
ImageView imageView = (ImageView)findViewById(R.id.image_view);
cameraBitmap = (Bitmap)intent.getExtras().get("data");
imageView.setImageBitmap(cameraBitmap);
}
private View.OnClickListener btnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.take_picture:
openCamera();
break;
}
}
};
}
you are going to want to use burst mode, have a look at
How to make burst mode available to Camera
should make it pretty clear.