Why MainActivity cannot be resolved or is not a field? - java

I have a small project where I need to play with the Battery of an Android device. At first, I wanted to be able to print the Battery so I used this tutorial.
Then, I have created a new Android project called "Testing" in Eclipse, and in MainActivity.java I put this code :
package com.example.testing;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.R.*;
public class MainActivity extends Activity {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity); //This is the MainActivity that contains the error
mTextView = (TextView) findViewById(R.id.batterTest);
findViewById(R.id.getBattery).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTextView.setText(String.valueOf(batteryLevel));
}
});
new Thread(new ThreadM()).start();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mArrow);
}
BatteryReceiver mArrow;
private class ThreadM implements Runnable {
#Override
public void run() {
mArrow = new BatteryReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
Intent batteryIntent = registerReceiver(mArrow, mIntentFilter);
batteryLevel = getBatteryLevel(batteryIntent);
Log.e("Battery Level", String.valueOf(batteryLevel));
}
}
float batteryLevel;
private class BatteryReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) {
int level = arg1.getIntExtra("level", 0);
Toast.makeText(MainActivity.this,"Current Battery " + level + " %", Toast.LENGTH_LONG).show();
mTextView.setText(String.valueOf("Battery Level Change Detect through Receiver = " + level));
}
}
}
public float getBatteryLevel(Intent batteryIntent) {
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return 50.0f;
}
return ((float) level / (float) scale) * 100.0f;
}
}
Actually this should just run a simple activity with the Battery level printed on the screen. But it does not because of one error. "MainActivity cannot be resolved or is not a field" (see the commented line).
Do you have any idea why ? I would like to have this code working so I can go on then.
Thank you.

You need to change
setContentView(R.layout.MainActivity);
to
setContentView(R.layout.activity_main);
assuming you have a layout called activity_main.xml and not MainActivity which is actually the name of your Activity class
and Remove
import android.R.*;
and import
import com.example.testing.R;

Related

Android Studio, Screeen To Screen Problem

basically im trying to make it so LoginScreen goes to Category screen .
package Screens;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.hr111.User.R;
import Utils.DisplayUtils;
import Utils.PlanUtils;
import Utils.SharedPreferencesUtils;
public class CategoryScreen extends AppCompatActivity {
Button btnExit;
Button btnChemistry;
Button btnBiology;
Button btnPhysics;
TextView textPlayerName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_screen);
btnExit = findViewById(R.id.btnExit);
textPlayerName = findViewById(R.id.textViewName);
btnBiology = findViewById(R.id.btnBiology);
btnPhysics = findViewById(R.id.btnPhysics);
btnChemistry = findViewById(R.id.btnChemistry);
String username = SharedPreferencesUtils.getStringPreference(CategoryScreen.this, "username");
textPlayerName.append(username);
btnBiology.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnBiology.getText().toString());
}
});
btnPhysics.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnPhysics.getText().toString());
}
});
btnChemistry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnChemistry.getText().toString());
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DisplayUtils.DisplayScript(CategoryScreen.this, "Exit", "Cikmak Istiyor Musunuz?",
"Hayır", "Evet", null, null);
}
});
}
void goToQuestions(String CategoryName){
SharedPreferencesUtils.settingStringPreference(CategoryScreen.this, "category", CategoryName);
SharedPreferencesUtils.settingIntegerPreference(CategoryScreen.this, "questionCount", 1);
SharedPreferencesUtils.settingIntegerPreference(CategoryScreen.this, "score", 0);
PlanUtils.GoToActivity(CategoryScreen.this, GameScreen.class);
}
}
package Screens;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.hr111.User.MainActivity;
import com.hr111.User.R;
import Utils.DisplayUtils;
import Utils.ExcerciseClass;
import Utils.PlanUtils;
import Utils.SharedPreferencesUtils;
public class LoginScreen extends AppCompatActivity implements View.OnClickListener {
Button btnNext;
TextView username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
btnNext = findViewById(R.id.buttonLogin);
username = findViewById(R.id.plaintextName);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = username.getText().toString().trim();
if(nameCheck(name))
{
SharedPreferencesUtils.settingStringPreference(LoginScreen.this, "playername", name);
PlanUtils.GoToActivity(LoginScreen.this, CategoryScreen.class);
}
else
{
DisplayUtils.DisplayScript(LoginScreen.this, "ERROR!", "Gecerli bir oyuncu adi seciniz!", null, null, null, null);
}
}
});
}
boolean nameCheck(String name){
if(name == null) return false;
if(name.length() == 0) return false;
return true;
}
#Override
public void onClick(View v) {
}
}
Both screens are in different Classes.
But it simply crashes before LoginScreen can reach to Category Screen. Any clue why this is not working? I have been trying to figure out and i used different variations of codes but all led me to to nothing. I have also tried on a different project but that also led me to nowhere. Thanks in advance

Multiple Choice Quiz app with SQLite (score are not show in new activity)

I'm new to android and I'm just doing a android app by watching Multiple choice quiz app with sqlite integration series(Youtube Playlist). Now I have a problem. In the tutorial, they have 2 activity( Main Activity & Quiz Activity) and the score from QuizActivity are send back to MainActivity. But I Have 3 Activity(Main Activity ,QuestionActivity & ResultActivity). I want to send the score from QuestionActivity to ResultActivity and show it with textView. The problem is score are always show as 0 but when I debug the showResult(), there score are showing Debug Result.Can you please check my coding and please fix it for me.I'm really new to android so please help me guys.
This is the debug result.
MainActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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 buttonGeneral= findViewById(R.id.button_general_english);
buttonGeneral.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GeneralEnglish();
}
});
}
private void GeneralEnglish(){
Intent intent=new Intent(MainActivity.this,QuestionActivity.class);
startActivity(intent);
}
}
QuestionActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class QuestionActivity extends AppCompatActivity {
public static final int REQUEST_CODE_QUIZ = 1;
public static final String EXTRA_SCORE="extra_score";
private TextView textViewQuestion;
private TextView textViewQuestionCount;
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private Button buttonNext;
private ColorStateList textColorDefaultRb;
private List<Question> questionList;
private int questionCounter;
private int questionCountTotal;
private Question currentQuestion;
private int score;
private boolean answered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
textViewQuestion= findViewById(R.id.text_view_question);
textViewQuestionCount= findViewById(R.id.text_view_question_count);
radioGroup= findViewById(R.id.radio_group);
radioButton1= findViewById(R.id.radio_button1);
radioButton2= findViewById(R.id.radio_button2);
radioButton3= findViewById(R.id.radio_button3);
buttonNext= findViewById(R.id.button_next);
QuizDatabseHelper databseHelper=new QuizDatabseHelper(this);
questionList=databseHelper.getAllQuestions();
questionCountTotal=questionList.size();
Collections.shuffle(questionList);
showNextQuestion();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!answered){
if (radioButton1.isChecked() || radioButton2.isChecked() || radioButton3.isChecked()){
checkAnswer();
}else {
Toast.makeText(QuestionActivity.this, "Please select an answer", Toast.LENGTH_SHORT).show();
}
}else {
showNextQuestion();
}
}
});
}
private void showNextQuestion(){
radioGroup.clearCheck();
if (questionCounter<questionCountTotal){
currentQuestion=questionList.get(questionCounter);
textViewQuestion.setText(currentQuestion.getQuestion());
radioButton1.setText(currentQuestion.getOption1());
radioButton2.setText(currentQuestion.getOption2());
radioButton3.setText(currentQuestion.getOption3());
questionCounter++;
textViewQuestionCount.setText("Question: "+ questionCounter + "/" + questionCountTotal);
answered=false;
buttonNext.setText("Next");
}else {
buttonNext.setText("Get Result");
showResult();
}
}
public void showResult(){
Intent resultIntent = new Intent(QuestionActivity.this,ResultActivity.class);
resultIntent.putExtra(EXTRA_SCORE,score);
setResult(RESULT_OK,resultIntent);
startActivityForResult(resultIntent,REQUEST_CODE_QUIZ);
}
private void checkAnswer(){
answered=true;
RadioButton radioButtonselected=findViewById(radioGroup.getCheckedRadioButtonId());
int answernumber = radioGroup.indexOfChild(radioButtonselected) + 1;
if (answernumber == currentQuestion.getAnswernumber()){
score++;
}
showNextQuestion();
}
}
ResultActivity
package com.enkoala.enkoala;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import static com.enkoala.enkoala.QuestionActivity.REQUEST_CODE_QUIZ;
public class ResultActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String KEY_HIGHSCORE = "keyhighscore";
private TextView textViewHighscore;
private int highscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
textViewHighscore = findViewById(R.id.text_view_score);
loadHighscore();
final Button buttonback = findViewById(R.id.button_back);
buttonback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonBack();
}
});
}
private void buttonBack() {
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
startActivity(intent);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ) {
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(QuestionActivity.EXTRA_SCORE, 0);
if (score > highscore) {
updateHighscore(score);
}
}
}
}
private void loadHighscore() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
highscore = sharedPreferences.getInt(KEY_HIGHSCORE, 0);
textViewHighscore.setText("Your score is " + highscore + " out of 25. ");
}
private void updateHighscore(int highscoreNew) {
highscore = highscoreNew;
textViewHighscore.setText("Your score is " + highscore + " out of 25. ");
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_HIGHSCORE, highscore);
editor.apply();
}
}
Are you trying to debug your result activity? In first glance your code is OK. But i think it may be problem with you onActivityResult() methode, as i know it's an async task. So you should transfer your loadHighscore() in onActivityResult() after you recieve your score value. Think it should help.

How to capture and pass Mat object to a new activity?

I am planning on implementing ocr, the idea is for the user to capture an image and the app will write it as text to a file on the phone. I have managed to display the feed from the camera to the javacameraview using CvCameraViewListener2.
I now want to capture the frame as an Mat object and pass it to a new activity. The solution's I saw all involve saving the photo, or displaying the processed image or live processing. I just need to pass the Mat to another class for processing then I can release it. I'm having trouble find a methodology for doing this though it seems as though it should be fairly straightforward.
The question is essentially how to get the Mat object from the cameraview?
Any help or direction would be greatly appreciated.
Thank you stackoverflow
The relevant code is here
import android.Manifest;
import android.content.Intent;
Import android.content.pm.ActivityInfo; importandroid.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation != 90) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.cameraInit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//marshmallow permissions
takePhoto();
}
});
}
private void callCamera(){
Intent startCameraIntent = new Intent(getApplicationContext(), OpenCVCamera.class);
startActivity(startCameraIntent);
}
public void takePhoto() {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this, "This app requires camera access", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
callCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
public class OpenCVCamera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
// need to correct view size (i think this can be done in the xml
// else refer to cmaera video app
// also orientation needs to be corrected
private static final String TAG = "OpenCVCamera";
private CameraBridgeViewBase cameraBridgeViewBase;
private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
cameraBridgeViewBase.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_open_cvcamera);
cameraBridgeViewBase = (CameraBridgeViewBase) findViewById(R.id.camera_view);
cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
cameraBridgeViewBase.setCvCameraViewListener(this);
}
#Override
public void onResume(){
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, baseLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
baseLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
//original just returns inputFrame.rgba()
Core.rotate(inputFrame.rgba(), inputFrame.rgba(), Core.ROTATE_90_CLOCKWISE); //ROTATE_180 or ROTATE_90_COUNTERCLOCKWISE
return inputFrame.rgba();
}
}

QR scanning, result - "com.google.android.gms.vision.barcode.Barcode#ecd6456"

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...

Custom Typeface not working on Android 5.0 but works elsewhere

I am using custom fonts in my app, the thing is, it works on android version less than Lollipop and greater than lolliop but on Lollipop it just goes blank
Please find the code and screenshots attached
SelectionPage.java
package com.execube.volantis.views;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.execube.volantis.R;
import com.execube.volantis.receiver.customHandler;
import com.flaviofaria.kenburnsview.KenBurnsView;
import com.flaviofaria.kenburnsview.RandomTransitionGenerator;
import com.pushbots.push.Pushbots;
import io.fabric.sdk.android.Fabric;
public class SelectionPage extends AppCompatActivity {
private Button mEventsButton;
private Button mAlertsButton;
private Button mAboutButton;
private Button mDirectionsButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.selection_page);
Pushbots.sharedInstance().init(this);
Pushbots.sharedInstance().setCustomHandler(customHandler.class);
mEventsButton=(Button)findViewById(R.id.events_button);
mAboutButton=(Button)findViewById(R.id.about_button);
mAlertsButton=(Button)findViewById(R.id.alerts_button);
mDirectionsButton=(Button)findViewById(R.id.directions_button);
Typeface gothamRoundedMedium= Typeface.createFromAsset(getAssets(),"fonts/Gotham-Rounded-Medium.ttf");
mEventsButton.setTypeface(gothamRoundedMedium);
mAboutButton.setTypeface(gothamRoundedMedium);
mDirectionsButton.setTypeface(gothamRoundedMedium);
mAlertsButton.setTypeface(gothamRoundedMedium);
mEventsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(SelectionPage.this,EventActivity.class);
startActivity(intent);
}
});
mDirectionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String geoUri = "http://maps.google.com/maps?q=loc:" + "12.9021902" + "," + "77.518582" + " (" + "RNS Institute Of Technlogy" + ")";
Intent intent= new Intent(Intent.ACTION_VIEW, Uri.parse(geoUri));
startActivity(intent);
}
});
mAlertsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(SelectionPage.this,AlertsActivity.class);
startActivity(intent);
}
});
mAboutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(SelectionPage.this,AboutActivity.class);
startActivity(intent);
}
});
}
}
The buttons use custom fonts.
Is there any way to set custom fonts only if android version is not equal to Lollipop?
Here's Marshmallow API 23
Here's Lollipop API 21
Define type face in application class.
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
You then need to overload the few default fonts, for example in an application class:
public final class Application extends android.app.Application {
#Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
}
}
API 21 Android 5.0 use default theme
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>

Categories