Android - get the value of global variable from every function - java

I use Android Studio to make an app. I have a file named 'GlobalVariables.java' and this code in it:
public class GlobalVariables extends Application {
public String CallingActivity;
public String getCallVariable() {
return CallingActivity;
}
public void setCallVariable(String Value) {
CallingActivity = Value;
}
}
In the manifest file I have:
<application android:name=".GlobalVariables" .....
I also have a LanguageActivity.java file which has this code:
package com.testApp;
//import android.content.Intent;
//import android.support.v7.app.ActionBarActivity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class LanguageActivity extends ListActivity {
// public class CountrycodeActivity extends ListActivity {
public static final String TAG = "MyActivity";
// public static String RESULT_CONTRYCODE = "countrycode";
public String[] countrynames;
private TypedArray imgs;
private List<Country> countryList;
Locale myLocale;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
populateCountryList();
ArrayAdapter<Country> adapter = new CountryListArrayAdapter(this, countryList);
setListAdapter(adapter);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ReadWriteFile RWFile = new ReadWriteFile();
if (position == 0) {
ChangeLanguage("el", getBaseContext());
try {
RWFile.LangWrite("en",getBaseContext());
Log.e(TAG, "LANG === en");
} catch (IOException e) {
e.printStackTrace();
}
}else{
ChangeLanguage("en", getBaseContext());
try {
RWFile.LangWrite("en",getBaseContext());
Log.e(TAG, "LANG === en");
} catch (IOException e) {
e.printStackTrace();
}
}
imgs.recycle(); //recycle images
finish();
}
});
}
private void populateCountryList() {
countryList = new ArrayList<Country>();
countrynames = getResources().getStringArray(R.array.country_names);
//countrycodes = getResources().getStringArray(R.array.country_codes);
imgs = getResources().obtainTypedArray(R.array.country_flags);
for(int i = 0; i < countrynames.length; i++){
countryList.add(new Country(countrynames[i], imgs.getDrawable(i)));
}
}
public class Country {
private String name;
// private String code;
private Drawable flag;
public Country(String name, Drawable flag){
this.name = name;
// this.code = code;
this.flag = flag;
}
public String getName() {
return name;
}
public Drawable getFlag() {
return flag;
}
// public String getCode() {
// return code;
// }
}
public void ChangeLanguage(String value, Context context){
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale(value.toLowerCase());
res.updateConfiguration(conf, dm);
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
String Activity = mApp.getCallVariable();
if (Activity.equals("Login")){
final Intent intent = new Intent(LanguageActivity.this, LoginActivity.class);
startActivity(intent);
}else if (Activity.equals("Signup")){
final Intent intent = new Intent(LanguageActivity.this, SignupActivity.class);
startActivity(intent);
}
}
}
When I run the code, the app craches with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
If I change
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
String Activity = mApp.getCallVariable();
to
String Activity = ((GlobalVariables) this.getApplication()).getCallVariable();
then I get error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.testApp.GlobalVariables.getCallVariable()' on a null object reference
I did many tries but nothing helped. What will solve my problem anyway?
Why do I do this? I want to know which Activity called ChangeLanguage() to restart it to show the selected language.

Dependency injection will solve your problem. If you use dagger2, solve this kind of problem will be better, because will be easier create singletons. If you want i can post here how you can do this. Comment below this answer if you want me to edit this with dagger2 basics.

Add this to the AndroidManifest.xml:
<application
android:name=".GlobalVariables"/>

Try:
public class GlobalVariables extends Application {
public String CallingActivity;
public staric GlobalVariables instance;
#Override
public void onCreate()
{super.onCreate();
this.instance = this;
}
public String getCallVariable() {
return CallingActivity;
}
public void setCallVariable(String Value) {
CallingActivity = Value;
}
public static GlobalVariables getInstance()
{
return instance;
}
}
String Activity = GlobalVariables.getInstance().getCallVariable();

Try replacing the line
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
with:
GlobalVariables mApp = new GlobalVariables();
And in line :
String Activity = mApp.getCallVariable();
Replace 'Activity' with 'activity' because Activity is a pre-defined word.
Edit 1: IS this is how you tried:
GlobalVariables mApp = GlobalVariables.getInstance();
mApp.setCallVariable(value);
mApp.getCallVariable();

Related

How to fix declarations in Android Studio blockchain app

Found a tutorial online for building a simple blockchain app on android studio but when I finished it has key missing declarations which are coming up as unused. My capabilities allow me to resolve most minor errors through the Run and Logcat monitors while debugging but a series of stacked issues like this seems to pose too large of an issue. Here are the pages that it specifies as missing declarations:
BlockChainManager
package com.example.blockchain.managers;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.blockchain.adapter.BlockAdapter;
import com.example.blockchain.models.BlockModel;
import java.util.ArrayList;
import java.util.List;
public class BlockChainManager {
private final int difficulty;
private final List<BlockModel> blocks;
public final BlockAdapter adapter;
public BlockChainManager(int difficulty, #NonNull Context context) {
this.difficulty = difficulty;
blocks = new ArrayList<>();
BlockModel block = new BlockModel(0,System.currentTimeMillis(),null,"Genesis Block");
block.mineBlock(difficulty);
blocks.add(block);
adapter = new BlockAdapter(blocks,context);
}
public BlockModel newBlock(String data){
BlockModel latestBlock = lastestBlock();
return new BlockModel(latestBlock.getIndex()+1,System.currentTimeMillis(),latestBlock.getHash(),data);
}
private BlockModel lastestBlock() {
return blocks.get(blocks.size()-1);
}
public void addBlock(BlockModel block){
if (block!= null){
block.mineBlock(difficulty);
blocks.add(block);
}
}
private boolean isFirstBlockValid(){
BlockModel firstBlock = blocks.get(0);
if (firstBlock.getIndex()!=0){
return false;
}
if (firstBlock.getPreviousHash()!=null){
return false;
}
return firstBlock.getHash()!=null &&
BlockModel.calculateHash_detail(firstBlock).equals(firstBlock.getHash());
}
private boolean isValidNewBlock(#Nullable BlockModel newBlock, #Nullable BlockModel previousBlock){
if (newBlock!=null && previousBlock!= null){
if (previousBlock.getIndex()+1!=newBlock.getIndex()){
return false;
}
if (newBlock.getPreviousHash()==null || !newBlock.getPreviousHash().equals(newBlock.getData())){
return false;
}
return newBlock.getHash()!=null &&
BlockModel.calculateHash_detail(newBlock).equals(newBlock.getHash());
}
return false;
}
public boolean isBlockChainValid(){
if (!isFirstBlockValid()){
return false;
}
for (int i = 1 ; i<blocks.size();i++){
BlockModel currentBlock = blocks.get(i);
BlockModel previousBlock = blocks.get(i-1);
if (!isValidNewBlock(currentBlock,previousBlock))
return false;
}
return true;
}
}
BlockModel
package com.example.blockchain.models;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BlockModel {
private int index,nonce;
private long timestamp;
private String hash,previousHash,data;
public BlockModel(int index, long timestamp, String previousHash, String data) {
this.index = index;
this.timestamp = timestamp;
this.previousHash = previousHash;
this.data = data;
nonce = 0;
hash = BlockModel.calculateHash_detail(this);
}
public static String calculateHash_detail(BlockModel blockModel) {
if (blockModel!= null){
MessageDigest messageDigest;
try{
messageDigest = MessageDigest.getInstance("SHA-256");
}
catch (NoSuchAlgorithmException e){
return null;
}
String txt = blockModel.str();
final byte[] bytes = messageDigest.digest(txt.getBytes());
final StringBuilder builder = new StringBuilder();
for (final byte b: bytes){
String hex = Integer.toHexString(0xff & b);
if (hex.length()==1){
builder.append('0');
}
builder.append(hex);
}
return builder.toString();
}
return null;
}
private String str() {
return index + timestamp + previousHash + data + nonce;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getNonce() {
return nonce;
}
public void setNonce(int nonce) {
this.nonce = nonce;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public void mineBlock(int difficulty){
nonce = 0;
while(!getHash().substring(0,difficulty).equals(addZeros(difficulty))){
nonce++;
hash = BlockModel.calculateHash_detail(this);
}
}
private String addZeros(int difficulty) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i<difficulty; i++) {
builder.append('0');
}
return builder.toString();
}
}
CipherUtils
package com.example.blockchain.utils;
import android.util.Base64;
import androidx.annotation.NonNull;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class CipherUtils {
private static final String PASSWORD = "Saf fur yoU";
private static final String ALGORITHM = "DES";
public static String encryptIt(#NonNull String value){
try{
DESKeySpec keySpec = new DESKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = keyFactory.generateSecret(keySpec);
byte [] clearText = value.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("ALGORITHM");
cipher.init(Cipher.ENCRYPT_MODE,key);
return Base64.encodeToString(cipher.doFinal(clearText),Base64.DEFAULT);
}
catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException e){
e.printStackTrace();
}
return value;
}
public static String decryptIt(#NonNull String value){
try{
DESKeySpec keySpec = new DESKeySpec(PASSWORD.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = keyFactory.generateSecret(keySpec);
byte [] encryptedPwdBytes = Base64.decode(value,Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("ALGORITHM");
cipher.init(Cipher.DECRYPT_MODE,key);
byte [] decryptedValueBytes = (cipher.doFinal(encryptedPwdBytes));
return new String(decryptedValueBytes);
}
catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException e){
e.printStackTrace();
}
return value;
}
}
MainActivity
package com.example.blockchain;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.blockchain.fragments.PowFragment;
import com.example.blockchain.databinding.ActivityMainBinding;
import com.example.blockchain.databinding.ContentMainBinding;
import com.example.blockchain.managers.BlockChainManager;
import com.example.blockchain.managers.SharedPreferencesManager;
import com.example.blockchain.utils.CipherUtils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ContentMainBinding viewBindingContent;
private ProgressDialog progressDialog;
private SharedPreferencesManager prefs;
private BlockChainManager blockChain;
private boolean isEncryptionActivated, isDarkActivated;
private static final String TAG_POW_DIALOG = "proof_of_work_dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
prefs = new SharedPreferencesManager(this);
isDarkActivated = prefs.isDarkTheme();
PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
boolean isPowerSaveMode = false;
if (powerManager!=null){
isPowerSaveMode = powerManager.isPowerSaveMode();
}
if(isPowerSaveMode){
isPowerSaveMode = powerManager.isPowerSaveMode();
}else{
if (isDarkActivated){
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES
);
}else{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO
);
}
}
super.onCreate(savedInstanceState);
final ActivityMainBinding viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
viewBindingContent = ContentMainBinding.bind(viewBinding.contentMain.getRoot());
setContentView(R.layout.activity_main);
isEncryptionActivated = prefs.getEncryptionStatus();
viewBindingContent.recyclerContent.setHasFixedSize(true);
viewBindingContent.recyclerContent.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL,false));
showProgressDialog(getResources().getString(R.string.text_creating_block_chain));
new Thread(() -> runOnUiThread(() -> {
blockChain = new BlockChainManager(prefs.getPowValue(),this);
viewBindingContent.recyclerContent.setAdapter(blockChain.adapter);
cancelProgressDialog(progressDialog);
})).start();
viewBindingContent.btnSendData.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
}
private void startBlockChain() {
showProgressDialog(getResources().getString(R.string.text_mining_blocks));
runOnUiThread(() -> {
if (blockChain != null && viewBindingContent.editMessage.getText() != null && viewBindingContent.recyclerContent.getAdapter() != null) {
String message = viewBindingContent.editMessage.getText().toString();
if (!message.isEmpty()) {
if (!isEncryptionActivated) {
blockChain.addBlock(blockChain.newBlock(message));
} else {
try {
blockChain.addBlock(blockChain.newBlock(CipherUtils.encryptIt(message).trim()));
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Something fishy happened", Toast.LENGTH_SHORT).show();
}
}
viewBindingContent.recyclerContent.scrollToPosition(blockChain.adapter.getItemCount() - 1);
if (blockChain.isBlockChainValid()) {
viewBindingContent.recyclerContent.getAdapter().notifyDataSetChanged();
viewBindingContent.editMessage.setText("");
} else {
Toast.makeText(this, "BlockChain Corrupted", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Error empty data", Toast.LENGTH_SHORT).show();
}
cancelProgressDialog(progressDialog);
} else {
Toast.makeText(this, "Something wrong happened", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View view) {
if (view.getId()==R.id.btn_send_data)
startBlockChain();
}
private void showProgressDialog(#NonNull String loadingMessage){
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage(loadingMessage);
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.show();
}
private void cancelProgressDialog(#NonNull ProgressDialog progressDialog){
if(progressDialog!=null){
progressDialog.cancel();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1,menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem checkEncrypt = menu.findItem(R.id.action_encrypt);
checkEncrypt.setChecked(isEncryptionActivated);
MenuItem checkTheme = menu.findItem(R.id.action_dark);
checkTheme.setChecked(isDarkActivated);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.action_pow:
PowFragment powFragment = PowFragment.newInstance();
powFragment.show(this.getSupportFragmentManager(),TAG_POW_DIALOG);
break;
case R.id.action_encrypt:
isEncryptionActivated = !item.isChecked();
item.setChecked(isEncryptionActivated);
if (item.isChecked()){
Toast.makeText(this, "Message Encryption ON", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Message Encryption OFF", Toast.LENGTH_SHORT).show();
}
prefs.setEncryptionStatus(isEncryptionActivated);
return true;
case R.id.action_dark:
isDarkActivated =!item.isChecked();
item.setChecked(isDarkActivated);
prefs.setDarkTheme(isDarkActivated);
Intent intent = this.getPackageManager().getLaunchIntentForPackage(this.getPackageName());
startActivity(intent);
finish();
return true;
case R.id.action_exit:
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
}
PoWFragment
package com.example.blockchain.fragments;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.example.blockchain.R;
import com.example.blockchain.databinding.FragmentPowBinding;
import com.example.blockchain.managers.SharedPreferencesManager;
/**
* A simple {#link Fragment} subclass.
* Use the {#link PowFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PowFragment extends DialogFragment implements View.OnClickListener {
private FragmentPowBinding viewBinding;
private Context mcontext;
private SharedPreferencesManager prefs;
public PowFragment() {
// Required empty public constructor
}
public static PowFragment newInstance() {
return new PowFragment();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mcontext = context.getApplicationContext();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
viewBinding = FragmentPowBinding.inflate(getLayoutInflater(), container, false);
return viewBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
prefs = new SharedPreferencesManager(mcontext);
viewBinding.edtSetPow.setText(String.valueOf(prefs.getPowValue()));
viewBinding.btnClose.setOnClickListener(this);
viewBinding.btnContinue.setOnClickListener(this);
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialog.getWindow() != null) {
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
return dialog;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_close:
dismiss();
break;
case R.id.btn_continue:
if (viewBinding.edtSetPow.getText() != null) {
String pow = viewBinding.edtSetPow.getText().toString();
prefs.setPowValue(Integer.parseInt(pow));
if (getActivity() != null) {
Intent intent = mcontext.getPackageManager().getLaunchIntentForPackage(mcontext.getPackageName());
startActivity(intent);
getActivity().finish();
} else {
dismiss();
}
break;
}
}
}
#Override
public void onDetach() {
super.onDetach();
viewBinding = null;
mcontext = null;
}
}
SharedPreferencesManager
package com.example.blockchain.managers;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferencesManager {
private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;
private static final String PREFERENCES_DATA = "com.example.blockchain";
private static final String ENCRYPTION_STATUS = "encryption_status";
private static final String DARK_THEME = "dark_theme";
private static final String PROOF_OF_WORK = "proof_of_work";
public static final int DEFAULT_PROOF_OF_WORK = 2;
public SharedPreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_DATA,Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();
}
public void setPowValue(int powValue){
editor.putInt(PROOF_OF_WORK,powValue);
editor.commit();
}
public int getPowValue(){
return sharedPreferences.getInt(PROOF_OF_WORK,DEFAULT_PROOF_OF_WORK);
}
public void setEncryptionStatus(boolean isActivated){
editor.putBoolean(ENCRYPTION_STATUS,isActivated);
editor.commit();
}
public boolean getEncryptionStatus(){
return sharedPreferences.getBoolean(ENCRYPTION_STATUS,false);
}
public void setDarkTheme(boolean isActivated){
editor.putBoolean(DARK_THEME,isActivated);
editor.commit();
}
public boolean isDarkTheme(){
return sharedPreferences.getBoolean(DARK_THEME,false);
}
}
If for any reason the Manifest will help:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.blockchain">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:fullBackupContent="#xml/backup_descriptor">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
These errors seem to be centered around a specific class meant to integrate the BlockChain into the App FrameWork, but this has used its declarations:
Block Adapter
package com.example.blockchain.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.blockchain.R;
import com.example.blockchain.models.BlockModel;
import com.example.blockchain.viewholder.RecyclerViewHolder;
import java.util.Date;
import java.util.List;
public class BlockAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private final List<BlockModel> blocks;
private final Context mcontext;
private int lastPosition = -1;
public BlockAdapter(#Nullable List<BlockModel> blocks, #NonNull Context mcontext) {
this.blocks = blocks;
this.mcontext = mcontext;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(viewType,parent,false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
holder.txtIndex.setText(String.format(
mcontext.getString(R.string.title_block_number),blocks.get(position).getIndex()
));
holder.txtPreviousHash.setText(blocks.get(position).getPreviousHash()!=null ? blocks.get(position).getPreviousHash(): "Null");
holder.txtTimestamp.setText(String.valueOf(new Date(blocks.get(position).getTimestamp())));
holder.txtData.setText(blocks.get(position).getData());
holder.txtHash.setText(blocks.get(position).getHash());
setAnimation(holder.itemView,position);
}
private void setAnimation(View itemView, int position) {
if (position>lastPosition){
Animation animation = AnimationUtils.loadAnimation(mcontext,android.R.anim.fade_in);
itemView.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemViewType(int position) {
return R.layout.item_block_data;
}
#Override
public int getItemCount() {
return blocks == null ? 0:blocks.size();
}
}
Let me know if anything else might help resolve these issues.
Here is the link to the video however the advertised "FREE" learning actually requires $30 for the source code once you realize what you have received does not work: https://www.youtube.com/watch?v=c5E_yBMt7Io&t=1s
Since I'm not an idiot I did not send someone money simply because they shared a few chopped up videos and asked for it in an email, but the lengthy 7-part series to deceive people into obligatorily purchasing after the "FREE" learning is illegal misrepresentation as well as unethically conning people interested in the fledgling blockchain technologies.
Any help is greatly appreciated!

How can I populate a ListView on a SecondActivity with data from FirstActivity in Android?

I'm working on a book-searching app project. The user enters a title, and the app searches Google Books for it.
I initially had one activity and layout. I decided to use two layouts (one for user to enter title, and the other displays results); had to create another activity because the results layout was throwing an exception about 'null' object reference.
After creating the second activity, I used an intent to transfer List data between the two activities; no sooner did I find out that I had to use a Serialize or Parcelable object for the purpose.
Following instructions at Pass list of objects from one activity to other activity in android & https://www.vogella.com/tutorials/AndroidParcelable/article.html, I failed at implementing both, because Serialize sent an empty ArrayList (thus, an empty results page, even though there're book hits) and Parcelable was throwing out different exceptions everytime I used it, probably because I'm using an ArrayAdapter to populate the ListView with books.
I don't think I'm ready to implement the API at https://www.vogella.com/tutorials/AutoValue/article.html and can't use Fragments as well. A better structure would be to use a single activity, View.GONE the background image I so much cherish, and display list of book objects under the search field. But it would be good to make a follow-up on Serialize & Parcelable -- for future projects.
So, fellow developers, what's the solution to this?
FirstActivity screenshot
SecondActivity screeenshot
Here's my code:
MainActivity:
package project.android.gbookslisting;
import android.app.LoaderManager;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import static project.android.gbookslisting.ResultsActivity.adapter;
//import android.support.v4.content.AsyncTaskLoader;
//import android.support.v7.app.AppCompatActivity;
public class ParamsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>>, Serializable {
private static final int LOADER_ID = 0;
private static String LOG_TAG = ParamsActivity.class.getName();
EditText text;
String query;
private LoaderManager loaderManager = getLoaderManager();
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parameters);
Button query = findViewById(R.id.search_button);
text = findViewById(R.id.deets_field);
query.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view) {
if (text.getText().toString().length() > 0) { loaderManager.initLoader(LOADER_ID, null, ParamsActivity.this);
} else if (text.getText().length() < 1) {
text.setHint("Please enter book title/details");
text.setHintTextColor(Color.RED);
}
}
});
}
#Override
public Loader<List<Book>> onCreateLoader (int i, Bundle bundle) {
query = text.getText().toString();
return new BookLoader(this, query);
}
#Override
public void onLoadFinished (Loader<List<Book>> loader, List<Book> data) {
// If there is a valid list of {#link Book}s, then add them to the adapter's dataset. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
data = new ArrayList<Book>();
Intent i = new Intent(getApplicationContext(), ResultsActivity.class);
i.putExtra("data", (Serializable) data);
startActivity(i);
}
}
#Override
public void onLoaderReset (Loader loader) {
adapter = new Adapt(this, new ArrayList<Book>());
adapter.clear();
}
}
SecondActivity:
package project.android.gbookslisting;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import androidx.appcompat.app.AppCompatActivity;
public class ResultsActivity extends AppCompatActivity implements Serializable {
static Adapt adapter;
static TextView emptyResult;
ListView bookEntries;
String LOG_TAG = ResultsActivity.class.getName();
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hits_page);
Intent i = getIntent();
ArrayList<Book> books = (ArrayList<Book>) i.getSerializableExtra("data");
emptyResult = findViewById(R.id.matches_nill);
emptyResult.setText(R.string.matches0);
if (!books.isEmpty()) {
emptyResult.setVisibility(View.GONE);
// Create a new adapter that takes a rich (or otherwise empty) list of books as input
adapter = new Adapt(this, new ArrayList<Book>());
// Get the list of books from {#link Search}
bookEntries = findViewById(R.id.catalog);
bookEntries.setAdapter(adapter);
bookEntries.setEmptyView(emptyResult);
bookEntries.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> adapterView, View view, int position, long l) {
// Find the current book that was clicked on
Book currentBook = adapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri bookUri = Uri.parse(currentBook.getPage());
// Create a new intent to view the book URI
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
// Send the intent to launch a new activity
startActivity(websiteIntent);
}
});
// adapter.clear();
adapter.addAll(books);
} else {
emptyResult.setVisibility(View.VISIBLE);
emptyResult.setText(R.string.matches0);
}
}
}
Book obj.:
package project.android.gbookslisting;
import java.io.Serializable;
import java.util.Date;
public class Book {
private String book_title;
private String author;
private String publishing_year;
private String page;
public Book (String theTitle, String theAuthor, String theYear, String thePage) {
this.book_title = theTitle;
this.author = theAuthor;
this.publishing_year = theYear;
this.page = thePage;
}
public Book setBook_title (String book_title) {
this.book_title = book_title;
return this;
}
public Book setAuthor (String author) {
this.author = author;
return this;
}
public Book setPublishing_year (String publishing_year) {
this.publishing_year = publishing_year;
return this;
}
public Book setPage (String page) {
this.page = page;
return this;
}
protected String getAuthor () {
return author;
}
protected String getPublishing_year () { return publishing_year; }
protected String getPage () {
return page;
}
protected String getBook_title () {
return book_title;
}
}
You can declare the a variable that will handle your data = new ArrayList<Book>(); as public static.. However it's not recommended for high level codebase but for the structures of yours, you can implement it.
just declare a variable like this above protected void onCreate() in FirstActivity ..
public static List<Book> book_data = new ArrayList<>();
and transfer the data from public void onLoadFinished (Loader<List<Book>> loader, List<Book> data) to book_data
#Override
public void onLoadFinished (Loader<List<Book>> loader, List<Book> data) {
// If there is a valid list of {#link Book}s, then add them to the adapter's dataset. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
//data = new ArrayList<Book>();
book_data = data;
Intent i = new Intent(getApplicationContext(), ResultsActivity.class);
startActivity(i);
}
}`
You can also try to debug it if it contains a value
Log.d(TAG, String.valueOf(data.size()));
and in SecondActivity
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hits_page);
List<Book> books = new ArrayList<>();
books = FirstActivity.book_data; //Get the data from the First Activity
....
....
}
All right, so I was able to correct my implementation of the Parcelable interface and the FirstActivity now passes data to SecondActivity. This is it:
package project.android.gbookslisting;
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
private String book_title;
private String author;
private String publishing_year;
private String page;
public Book (String theTitle, String theAuthor, String theYear, String thePage) {
this.book_title = theTitle;
this.author = theAuthor;
this.publishing_year = theYear;
this.page = thePage;
}
public Book(Parcel in) {
this.book_title = in.readString();
this.author = in.readString();
this.publishing_year = in.readString();
this.page = in.readString();
}
public static final Creator<Book> CREATOR = new Creator<Book>() {
#Override
public Book createFromParcel (Parcel in) {
return new Book(in);
}
#Override
public Book[] newArray (int size) {
return new Book[size];
}
};
protected String getAuthor () { return author; }
protected String getPublishing_year () { return publishing_year; }
protected String getPage () {
return page;
}
protected String getBook_title () {
return book_title;
}
#Override
public int describeContents () {
return 0;
}
#Override
public void writeToParcel (Parcel parcel, int flags) {
parcel.writeString(book_title);
parcel.writeString(author);
parcel.writeString(publishing_year);
parcel.writeString(page);
}
}
I've shared the repository on GitHub #GBooks Listing, pending more features/updates.
ResultsActivity
Sure looks lame, but I'll improve the theming & whatever affects appearance. Thanks.

Unable to start receiver ClassCastExceptioncannot be cast to retrofit2.Call

The error tells me to cast this Call > arrayListCall= RetrofitBuilder.getRecipes();
but i cast it but still is wrong.My goal is to create a widget with the arraylist of ingredients for the selected recipe in the main. The error message shows:
Unable to start receiver com.example.mac.francosbakingapp.Widget.BankingAppWidgetProvider: java.lang.ClassCastException: $Proxy0 cannot be cast to retrofit2.Call
package com.example.mac.francosbakingapp.Widget;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.example.mac.francosbakingapp.MainActivity;
import com.example.mac.francosbakingapp.Model.Ingredient;
import com.example.mac.francosbakingapp.Model.Recipe;
import com.example.mac.francosbakingapp.R;
import com.example.mac.francosbakingapp.RetrofitBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
public class RecipeIngredientsWidgetService extends RemoteViewsService{
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return (new ListViewFactory(this.getApplicationContext()) );
}
class ListViewFactory implements RemoteViewsService.RemoteViewsFactory{
private ArrayList<Ingredient> mIngredientsList;
private Context context;
public ListViewFactory( Context context) {
this.context = context;
}
#Override
public void onCreate() {
}
#Override
public void onDataSetChanged() {
loadData();
}
private void loadData() {
Call <ArrayList<Recipe>> arrayListCall= RetrofitBuilder.getRecipes();
try{
Response<ArrayList<Recipe>> arrayListResponse=arrayListCall.execute();
if (arrayListResponse!=null){
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(context);
int position=sharedPreferences.getInt(MainActivity.POSITION_KEY,0);
Recipe recipe= arrayListResponse.body().get(position);
mIngredientsList= (ArrayList<Ingredient>) recipe.getIngredients();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
if(mIngredientsList !=null){
mIngredientsList=null;
}
}
#Override
public int getCount() {
return mIngredientsList==null ? 0: mIngredientsList.size();
}
#Override
public RemoteViews getViewAt(int position) {
Ingredient actIngredient=mIngredientsList.get(position);
RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.ingredient_list_item_widget_layout);
String ingredientName= actIngredient.getIngredient();
double ingredientQuantity=actIngredient.getQuantity();
String ingredientMeasure=actIngredient.getMeasure();
String ingredientString=String.format("${title}",ingredientName,ingredientQuantity,ingredientMeasure);
remoteViews.setTextViewText(R.id.tv_widget_population,ingredientString);
return remoteViews;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
Blockquote
The getRecipes
public static RecipesInterface getRecipes(){
interfaceRecipes= new Retrofit.Builder()
.baseUrl("http://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/")
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
.build().create(RecipesInterface.class);
return interfaceRecipes;
}
Shows the error in the code
The problem i have is in the cast of;
Call > arrayListCall= RetrofitBuilder.getRecipes();
Complete project on :
https://github.com/franquicidad/FrancosBakingApp

React Native: write in AsyncStorage with java

So I have this text on the java-side that arrives from an Intent, which I'd like to save to AsyncStorage to being able to access it through React afterwards.
Any chance I can achieve this?
I have:
package com.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.content.Intent;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "BrowseItLater", null);
setContentView(mReactRootView);
// This code is from http://developer.android.com/training/sharing/receive.html
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
handleSendText(intent);
}
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// How can I handle this ????
}
}
// ...
}
Or is there any other solution to make MainActivity.java communicate with JS?
After quite some fight I finally found a solution. It doesn't use AsyncStorage as I read in the source code AsyncStorage could actually be located differently (SQLite, or something else) depending on the phone. Would be dirty to duplicate this logic.
Instead, I created a module like the doc suggests and passed the inputText as an argument to the .addPackage(new EphemeralStoragePackage(inputText)) call in MainActivity.java.
The module exposes a method readOnceAsync to the JS world, which I can later call with:
NativeModules.EphemeralStorage.readOnceAsync((text :string) => {
if (text.length) {
this._addValue(text); // this method is in charge of storing in AsyncStorage
}
})
Here's the detail:
// android/app/src/main/java/com/appname/modules/ephemeralstorage/EphemeralStorageModule.java
package com.browseitlater.modules.ephemeralstorage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import java.util.Map;
public class EphemeralStorageModule extends ReactContextBaseJavaModule {
private String inputText;
public EphemeralStorageModule(ReactApplicationContext reactContext, String _inputText) {
super(reactContext);
this.inputText = _inputText;
}
#Override
public String getName() {
return "EphemeralStorage";
}
public String getInputText() {
return inputText;
}
#ReactMethod
public void readOnceAsync(Callback successCallback) {
successCallback.invoke(getInputText());
this.inputText = null;
}
}
And
// android/app/src/main/java/com/appname/modules/ephemeralstorage/EphemeralStoragePackage.java
package com.browseitlater.modules.ephemeralstorage;
import android.app.Activity;
import java.util.*;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
public class EphemeralStoragePackage implements ReactPackage {
private String inputText;
public EphemeralStoragePackage(String _inputText) {
super();
this.inputText = _inputText;
}
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new EphemeralStorageModule(reactContext, getInputText()));
return modules;
}
#Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
public String getInputText() {
return inputText;
}
}
Finally in MainActivity.java, my onCreate method looks like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
String inputText = intent.getStringExtra(Intent.EXTRA_TEXT);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage(new EphemeralStoragePackage(inputText))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "BrowseItLater", null);
setContentView(mReactRootView);
}
If you don't want to write a native module, you can do this in MainActivity.java
Declare a global variable inside MainActivity class (don't forget to import com.facebook.react.modules.storage.ReactDatabaseSupplier):
private ReactDatabaseSupplier mReactDatabaseSupplier;
Inside onCreatemethod initialize the global variable:
mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(getApplicationContext());
Declare a private method to save the key/value pair inside AsyncStorage
private void saveKeyValuePair(String key, String value) {
String sql = "INSERT OR REPLACE INTO catalystLocalStorage VALUES (?, ?);";
SQLiteStatement statement = mReactDatabaseSupplier.get().compileStatement(sql);
try {
mReactDatabaseSupplier.get().beginTransaction();
statement.clearBindings();
statement.bindString(1, key);
statement.bindString(2, value);
statement.execute();
mReactDatabaseSupplier.get().setTransactionSuccessful();
} catch (Exception e) {
Log.w("YOUR_TAG", e.getMessage(), e);
} finally {
try {
mReactDatabaseSupplier.get().endTransaction();
} catch (Exception e) {
Log.w("YOUR_TAG", e.getMessage(), e);
}
}
}
Then you can save key/value pairs like this (inside onCreate, for example):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(getApplicationContext());
saveKeyValuePair("myAsyncStorageKey", "myValueInAsyncStorageKey");
}
This is a simple way to save in AsyncStorage of a React Native application. Consider writing a native module.

getDefaultSharedPreferences and an IntentService crash

I am trying to run this but It crashes when It gets to getDefaultSharedPreferences().
Why?
Here is the preferences activity. It fires an IntentService when it is destroyed
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class CCTDetectorActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private SharedPreferences settings;
static public String nameOfFile = "name_of_file";
static public String nameOfFileDefaultValue = "detected_f.xml";
static public String portNumber = "port_number";
static public String portNumberDefaultValue = "25015";
static public String keepAlive = "keep_alive";
static public String keepAliveDefaultValue = "3";
static public String nameOfSettings = "settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.cct_detector_preferences_ui);
settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(this);
updateViews();
}
#Override
protected void onDestroy() {
Intent intent = new Intent(getBaseContext(), CCTDetectorService.class);
startService(intent);
super.onDestroy();
}
private void updateViews() {
setSummeryfromPreferencesView(nameOfFile, nameOfFileDefaultValue);
setSummeryfromPreferencesView(portNumber, portNumberDefaultValue);
setSummeryfromPreferencesView(keepAlive, keepAliveDefaultValue);
}
private void setSummeryfromPreferencesView(String viewName, String DefValue) {
String value = settings.getString(viewName, DefValue);
EditTextPreference editTextView = (EditTextPreference) findPreference(viewName);
editTextView.setText(value);
editTextView.setSummary(value);
}
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
updateViews();
}
}
Here is the IntentService that crashes.
The line of the crash is marked with: "here it crashes!"
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class CCTDetectorService extends IntentService {
private File serializedXmlFile;
private DatagramSocket udpSocket;
private boolean m_Listening = true;
private ActiveCCTs activeCCTs = new ActiveCCTs();
private SharedPreferences preferences;
private Serializer serializer = new Persister();
public CCTDetectorService() throws SocketException {
super("CCTDetectorServiceThread");
int port;
String FILENAME;
// here it crashes!
preferences = PreferenceManager.getDefaultSharedPreferences(this);
port = getIntFromSettingsEditText(CCTDetectorActivity.portNumber,
CCTDetectorActivity.portNumberDefaultValue);
activeCCTs.keepAlive = getIntFromSettingsEditText(
CCTDetectorActivity.keepAlive,
CCTDetectorActivity.keepAliveDefaultValue);
FILENAME = preferences.getString(CCTDetectorActivity.nameOfFile,
CCTDetectorActivity.nameOfFileDefaultValue);
serializedXmlFile = new File(FILENAME);
udpSocket = new DatagramSocket(port);
udpSocket.setBroadcast(true);
}
}
You're doing a lot of stuff in the constructor of a Service.
Do not do that. Override #onCreate() and do your setup there. Remember to call super.onCreate().
In case of IntentService, it is better to do initialization in OnHandleIntent .
Also In your Case the Context may not have been initialized. So move the code in constructor to OnHandleIntent

Categories

Resources