I am developing an app that I use in DarkMode theme that I put a Switch to on and off darkMode and I save it inside a boolian whitch means darkMode get true or false (boolean isDarkMode =false;)
it work well and I use SharedPreferences to save this true or false value to use it in another activitys .
it work but ...
when I close app and run app again the value of SharedPreferences is not saved and it goes back to first value of boolian
(thank u)
SettingActivity.java (to set boolian true or false)
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class SettingActivity extends AppCompatActivity {
Switch mySwitch;
boolean isDarkMode =false;
private static final String DARKMODE = "login";
#Override
protected void onCreate(Bundle savedInstanceState) {
myboolian();
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode =true;
} else {
setTheme(R.style.AppTheme);
isDarkMode =false;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toast.makeText(this, ""+ isDarkMode, Toast.LENGTH_SHORT).show();
mySwitch = findViewById(R.id.switch1);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
mySwitch.setChecked(true);
}
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode =true;
restartApp();
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode =false;
restartApp();
}
}
});
Button buttonGoMain=findViewById(R.id.btn_go_MainAct);
buttonGoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SettingActivity.this,MainActivity.class));
}
});
}
public void restartApp() {
Intent intentRestartApp = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(intentRestartApp);
finish();
}
public void myboolian(){
isDarkMode =!isDarkMode; //change isDarkMode from false to true by this
SharedPreferences sharedPreferences =getSharedPreferences(DARKMODE,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("ISDARKMODE", isDarkMode);
editor.apply();
}
}
and MainActivity.java
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String DARKMODE = "login";
boolean isDarkMode = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
getData();
if (isDarkMode){
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode =true;
} else {
setTheme(R.style.AppTheme);
isDarkMode =false;
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button_go_to_setting_activity);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SettingActivity.class));
}
});
}
private void getData() {
SharedPreferences sharedPreferences = getSharedPreferences(DARKMODE, MODE_PRIVATE);
isDarkMode = sharedPreferences.getBoolean("ISDARKMODE", false);
}
}
In your checkedChangedListener you set darkMode to true and false respectively.
And in your myboolian method is the only place where your write the variable.
This method is only called from your onCreate and nowhere else. In addition to that, this method always sets darkMode = !darkMode, swapping the value.
You have to call myboolian in the onCheckedChanged and remove the darkMode = !darkMode or you will always reset to the value before.
thanks to #Grisgram for help
I solowed this problam by some changes and andrestanding mure about
settingActivity.java
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class SettingActivity extends AppCompatActivity {
public static Switch mySwitch;
boolean isDarkMode =false;
private static final String DARKMODE = "dark";
#Override
protected void onCreate(Bundle savedInstanceState) {
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darkTheme);
isDarkMode=true;
} else {
setTheme(R.style.AppTheme);
isDarkMode=false;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toast.makeText(this, ""+ isDarkMode, Toast.LENGTH_SHORT).show();
mySwitch = findViewById(R.id.switch1);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
mySwitch.setChecked(true);
}
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode=true;
myboolian();
restartApp();
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode=false;
myboolian();
restartApp();
}
}
});
myboolian();
Button buttonGoMain=findViewById(R.id.btn_go_MainAct);
buttonGoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SettingActivity.this,MainActivity.class));
}
});
}
public void restartApp() {
Intent intentRestartApp = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(intentRestartApp);
finish();
}
public void myboolian(){
// isDarkMode =!isDarkMode; //change isDarkMode from false to true by this
SharedPreferences sharedPreferences =getSharedPreferences(DARKMODE,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("ISDARKMODE", isDarkMode);
editor.apply();
}
}
and main activity
package com.kurdfoxx.nightmodewithsharedprefrense;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String DARKMODE = "dark";
boolean isDarkMode ;
#Override
protected void onCreate(Bundle savedInstanceState) {
getData();
Toast.makeText(this, "is datk ?"+isDarkMode, Toast.LENGTH_SHORT).show();
if (isDarkMode){
setTheme(R.style.darkTheme);
}else {setTheme(R.style.AppTheme);}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button_go_to_setting_activity);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SettingActivity.class));
}
});
}
private void getData() {
SharedPreferences sharedPreferences = getSharedPreferences(DARKMODE, MODE_PRIVATE);
isDarkMode = sharedPreferences.getBoolean("ISDARKMODE", false);
}
}
Related
I've tried many other threads and articles but I just can't find the right stuff that I am looking for.
So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press.
I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity.
I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.
MainAcitivity
package com.saad.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
int Start;
TextView txt;
Button btnU,btnT,btnR;
Switch sw,sw2;
private ConstraintLayout Clayout;
Vibrator vibe;
Boolean switchPref;
SharedPreferences sharedPreferences;
private static long back_pressed;
private Vibrator Vibrator;
//Double Tap Exit
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
//Inflater for Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbarid);
setSupportActionBar(toolbar);
MobileAds.initialize(this, "-APPID-");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
Clayout = findViewById(R.id.MainLayout);
btnT = findViewById(R.id.tapbtn);
btnR = findViewById(R.id.resetbtn);
btnU = findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
sw2 = findViewById(R.id.darkswch);
txt = findViewById(R.id.txtv);
txt.setTextColor(Color.BLACK);
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
loadData();
setData();
incrementbtn();
undobtn();
resetbtn();
switchbtn();
themeswitch();
}
public void loadData(){
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
}
private void setData(){
Start = sharedPreferences.getInt("0",0);
if(Start==0){
txt.setText("0");
}
else{
txt.setText(Integer.toString(Start));
}
}
public void incrementbtn(){
btnT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incvibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start += 1;
txt.setText(Integer.toString(Start));
txtresize();
} else {
Start += 1;
txt.setText(Integer.toString(Start));
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void undobtn(){
btnU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
undovibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start -= 1;
txt.setText(Integer.toString(Start));
}
else{
return;
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void resetbtn(){
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetvibe();
Start = 0;
txt.setText(Integer.toString(Start));
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void switchbtn(){
sw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
txt.setTextColor(Color.RED);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
if(sw2.isChecked()){
txt.setTextColor(Color.WHITE);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void themeswitch(){
sw2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw2.isChecked()){
Clayout.setBackgroundColor(Color.DKGRAY);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.WHITE);
}
}
else{
Clayout.setBackgroundColor(Color.WHITE);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void txtresize(){
if(Start > 1000 && Start < 10000){
txt.setTextSize(80);
}
else if (Start > 10000 && Start < 100000){
txt.setTextSize(60);
}
else if (Start > 100000){
txt.setTextSize(40);
}
else{
return;
}
}
StringBuilder info = new StringBuilder();
public void undovibe(){
vibe.vibrate(100);
}
public void resetvibe(){
vibe.vibrate(150);
}
public void incvibe(){
vibe.vibrate(40);
}
}//Real one
SettingActivity (created it from NEW > SettingActivity)
I did try some stuff by myself in here but it crashed my app.
package com.saad.tapcounter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
root_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory app:title="Settings"
app:iconSpaceReserved="false">
<SwitchPreferenceCompat
app:key="Switchsett1"
app:title="Vibration"
app:summaryOff="Turn Vibration On"
app:summaryOn="Turn Vibration Off"
app:iconSpaceReserved="false"
app:defaultValue="true"
/>
<SwitchPreferenceCompat
app:key="Switchset2"
app:iconSpaceReserved="false"
app:summaryOff="#string/attachment_summary_off"
app:summaryOn="#string/attachment_summary_on"
app:title="#string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity
To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean
Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:
public class MainActivity extends AppCompatActivity {
Boolean switchPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
switchPref = prefs.getBoolean("Switchsett1", false);
Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.
You can do the same for Switchset2 SwitchPreferenceCompat
Ya guys i have tried a lot of answers on this website and that all doesn't work at all
I have a webview app that i would love to save image in the website.
I have implemented long press to copy text in the app.
but not able to save image on long press.
those answers on context is not working
this is my main activity code can anyone please edit and answer me
and keep in mind that i only have some basic coding in java and I made most of this app from the codes of different sources
My Main Activity:
package com.example.ragulsundaram.typicaltamilan;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
SwipeRefreshLayout swipe;
private long backPressedTime;
private static final String TAG = "MainActivity";
public static int TIME_OUT=4000;
#Override
public void onBackPressed() {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
return;
}else{
Toast.makeText(getBaseContext(),"Press back again to exit,",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()){
mWebView.goBack();
}
else {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}else{
Toast.makeText(getBaseContext(),"Press back again to exit",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"Pogatheeey",Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Vankakkam",Toast.LENGTH_LONG).show();
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
public void onRefresh(){
LoadWeb();
}
});
LoadWeb();
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_DENIED){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
}
});
}
public void LoadWeb()
{
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.loadUrl("https://typicaltamila.blogspot.com/ ");
swipe.setRefreshing(true);
mWebView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
mWebView.loadUrl("file://android_asset/error.html");
}
public void onPageFinished(WebView view, String url)
{
//hide the swipe refreshlayout
swipe.setRefreshing(false);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith("magnet")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in system.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
//torrent
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url=request.getUrl().toString();
if (url.startsWith("magnet")) { Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in Android.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
//downloading files
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request= new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = android.webkit.CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription(("Downloading"));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url,contentDisposition,mimetype));
DownloadManager dm=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(MainActivity.this,"Your file is downloading",Toast.LENGTH_SHORT).show();
}
});
}
}
I have problem, dont know what to do, Goal is to make QR scanner, you enter value then press OK it should store the values in object podaci and to use same values in other activitiy.
But what happens it scans QR code but it doesnt show real value it shows something like this : "com.google.android.gms.vision.barcode.Barcode#ecd6456" and there is no value stored in object podaci in MainActivity.
here is my QR class :
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class QRActivity extends AppCompatActivity{
SurfaceView camera_preview;
Intent main;
EditText txtUnosUplacenog;
TextView txtQRIspis;
Button btnOK;
private Podaci podaci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qr_activity);
camera_preview = findViewById(R.id.camera_preview);
txtUnosUplacenog = findViewById(R.id.txtUnosUplacenog);
btnOK = findViewById(R.id.btnOK);
txtQRIspis = findViewById(R.id.txtQRIspis);
podaci = new Podaci();
createCameraSource();
}
private void createCameraSource() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(620, 480)
.build();
camera_preview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(QRActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(camera_preview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});//camera_preview
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if(barcodes.size() > 0){
podaci.setQrvalue(barcodes.valueAt(0).toString());
podaci.setUplata(Double.parseDouble(txtUnosUplacenog.getText().toString()));
txtQRIspis.setText(podaci.getQrvalue());
}
}
});//barcodeDetector
}//CreateCameraSource
public void btnOK(View view){
if(podaci.getUplata() != 0 && podaci.getQrvalue() != "")
izadji(podaci);
}
public void izadji(Podaci podatak){
main = new Intent(this, MainActivity.class);
main.putExtra("barcode", podatak.getQrvalue() );
main.putExtra("vrijednost", podatak.getUplata() );
startActivity(main);
finish();
}
public void izadji(View view){
main = new Intent(this, MainActivity.class);
startActivity(main);
finish();
}
}
And here is my MainActivity class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
public class MainActivity extends AppCompatActivity {
Button btnSkenirajQR;
Button btnOpcije;
Button btnExit;
TextView txtIspis;
boolean baterija_ispisano = false;
BroadcastReceiver batteryInfo = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if(level <= 10 && !baterija_ispisano){
Toast.makeText(getApplicationContext(),
"Molim vas napunite bateriju (<10%)",Toast.LENGTH_LONG);
baterija_ispisano = true;
}else if(level >= 11 && baterija_ispisano){
baterija_ispisano = false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSkenirajQR = findViewById(R.id.btnSkener);
btnOpcije = findViewById(R.id.btnOpcije);
btnExit = findViewById(R.id.btnExit);
txtIspis = findViewById(R.id.txtIspis);
}
public void open_Skener(View view){
Intent qrskeniranje = new Intent(this, QRActivity.class);
startActivityForResult(qrskeniranje,0);
finish();
}
public void open_Opcije(View view){
Intent opcije = new Intent(this, OpcijeActivity.class);
startActivity(opcije);
finish();
}
public void izadji(View view){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data != null){
String qr = data.getParcelableExtra("barcode");
String value = data.getParcelableExtra("vrijednost");
txtIspis.setText("Barcode vrijednost : " + qr);
} else {
txtIspis.setText("Nije ocitalo");
}
}
}
Ps :And it is changing value while im holding in front of QR code.
#gr54943, #ac45c04 etc...
im making a simple app with youtube views and stuff but whenever i run the app i get no errors but the app doesn't open and on my simulator it says "CFBC (the name of my app) Has stopped running" here is my code i have 6 activities i know its a lot but if anyone can tell me why its crashing with 0 errors would help a ton
package org.cfbcla.cfbc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kwia on 8/4/17.
*/
public class Display extends AppCompatActivity {
YouTubePlayerView mYouTubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
btnPlay = (Button) findViewById(R.id.btnPlay);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlay);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
List<String> videoList = new ArrayList<>();
videoList.add("QOwE0XQei_M");
videoList.add("5sTXWESDBB0");
youTubePlayer.loadVideos(videoList);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mYouTubePlayerView.initialize(YTConfig.getApiKey(), mOnInitializedListener);
}
});
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button3) {
Intent i4 = new Intent(Display.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by kwia on 8/4/17.
*/
public class Display2 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display2);
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button) {
Intent i4 = new Intent(Display2.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by kwia on 8/4/17.
*/
public class Display3 extends AppCompatActivity{
YouTubePlayerView mYouTubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display3);
btnPlay = (Button) findViewById(R.id.btnPlay);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlay);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("sFXQ1vAaKXA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mYouTubePlayerView.initialize(YTConfig.getApiKey(), mOnInitializedListener);
}
});
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button) {
Intent i4 = new Intent(Display3.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by kwia on 8/4/17.
*/
public class Display4 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display4);
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.button4) {
Intent i4 = new Intent(Display4.this, MainActivity.class);
startActivity(i4);
}
}
}
package org.cfbcla.cfbc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v) {
if (v.getId() == R.id.A) {
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
}
public void onButtonClick2(View v2) {
if (v2.getId() == R.id.C) {
Intent i2 = new Intent(MainActivity.this, Display2.class);
startActivity(i2);
}
}
public void onbuttonClick3(View v3) {
if (v3.getId() == R.id.S) {
Intent i3 = new Intent(MainActivity.this, Display3.class);
startActivity(i3);
}
}
public void onButtonclick4(View v4) {
if (v4.getId() == R.id.M) {
Intent i4 = new Intent(MainActivity.this, Display4.class);
startActivity(i4);
}
}
}
I'm trying to create a switch which when enabled hides a button called button but it returns an error for SetOnCheckedChangeListener and buttonView which says Cannot resolve symbol
package com.jordthedev.firstapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void switchActivity(View v){
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggle.setVisibility(toggle.INVISIBLE);
} else {
toggle.setVisibility(toggle.VISIBLE);
}
}
});
}
Maybe you have to place ToggleButton in onCreate() method try below code
package com.jordthedev.firstapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggle.setVisibility(toggle.INVISIBLE);
} else {
toggle.setVisibility(toggle.VISIBLE);
}
}
});
}
public void switchActivity(View v){
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
}
Replace your OnCheckedChangeListener Code with this
ToggleButton toggle =(ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggle.setVisibility(toggle.INVISIBLE);
} else {
toggle.setVisibility(toggle.VISIBLE);
}
}
});